diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 0cafc18..163a3a2 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1,5 +1,5 @@ # CODEOWNERS: https://help.github.com/articles/about-codeowners/ # Primary repo maintainers -* @ethanfrey -* @alpe +* @terpnetwork +* @discoverdefiteam diff --git a/.github/ISSUE_TEMPLATE/bug.md b/.github/ISSUE_TEMPLATE/bug.md new file mode 100644 index 0000000..5a17f5a --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug.md @@ -0,0 +1,30 @@ +--- +name: Report a bug +about: Issue tracker is used for reporting bugs +title: '' +labels: 'type:bug' +assignees: '' +--- + +#### Specifications + +Terp-Core version: `Terpd version` +OS & Version: Windows/Linux/OSX +Commit hash: + +#### Expected behavior + + +#### Actual behavior + + +#### Steps to reproduce the behavior + + +#### Backtrace + +```` +[backtrace] +```` + +When submitting logs: please submit them as text and not screenshots. diff --git a/.github/ISSUE_TEMPLATE/config.yaml b/.github/ISSUE_TEMPLATE/config.yaml new file mode 100644 index 0000000..a49eab2 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yaml @@ -0,0 +1 @@ +blank_issues_enabled: true \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..b165f6a --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,31 @@ + + +# Summary + + + +## Problem Definition + + + +## Proposal + + + +____ + +### For Admin Use + +- [ ] Not duplicate issue +- [ ] Appropriate labels applied +- [ ] Appropriate contributors tagged +- [ ] Contributor-assigned/self-assigned +- [ ] Is a spike necessary to map out how the issue should be approached? diff --git a/.github/ISSUE_TEMPLATE/issue.md b/.github/ISSUE_TEMPLATE/issue.md new file mode 100644 index 0000000..23175c9 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/issue.md @@ -0,0 +1,27 @@ +--- +name: General issue +about: A template for general issues with acceptance criteria +title: '' +assignees: '' +--- + + +## Background + +> This is where you can provide code examples or context (e.g. past PR's) +> e.g. +> - The following PRs contributed to... + +## Suggested Design + +> Here, you can put concrete steps as to what to do next +> e.g. +> - create test file in... + +## Acceptance Criteria + +> Goals & criteria for success +> e.g. +> - all existing and new tests should pass diff --git a/.github/workflows/codacy.yml b/.github/workflows/codacy.yml deleted file mode 100644 index af5c62c..0000000 --- a/.github/workflows/codacy.yml +++ /dev/null @@ -1,61 +0,0 @@ -# This workflow uses actions that are not certified by GitHub. -# They are provided by a third-party and are governed by -# separate terms of service, privacy policy, and support -# documentation. - -# This workflow checks out code, performs a Codacy security scan -# and integrates the results with the -# GitHub Advanced Security code scanning feature. For more information on -# the Codacy security scan action usage and parameters, see -# https://github.com/codacy/codacy-analysis-cli-action. -# For more information on Codacy Analysis CLI in general, see -# https://github.com/codacy/codacy-analysis-cli. - -name: Codacy Security Scan - -on: - push: - branches: [ "main", "release/v*" ] - pull_request: - # The branches below must be a subset of the branches above - branches: [ "main", "release/v*" ] - schedule: - - cron: '24 14 * * 5' - -permissions: - contents: read - -jobs: - codacy-security-scan: - permissions: - contents: read # for actions/checkout to fetch code - security-events: write # for github/codeql-action/upload-sarif to upload SARIF results - actions: read # only required for a private repository by github/codeql-action/upload-sarif to get the Action run status - name: Codacy Security Scan - runs-on: ubuntu-latest - steps: - # Checkout the repository to the GitHub Actions runner - - name: Checkout code - uses: actions/checkout@v3 - - # Execute Codacy Analysis CLI and generate a SARIF output with the security issues identified during the analysis - - name: Run Codacy Analysis CLI - uses: codacy/codacy-analysis-cli-action@5cc54a75f9ad88159bb54046196d920e40e367a5 - with: - # Check https://github.com/codacy/codacy-analysis-cli#project-token to get your project token from your Codacy repository - # You can also omit the token and run the tools that support default configurations - project-token: ${{ secrets.CODACY_PROJECT_TOKEN }} - verbose: true - output: results.sarif - format: sarif - # Adjust severity of non-security issues - gh-code-scanning-compat: true - # Force 0 exit code to allow SARIF file generation - # This will handover control about PR rejection to the GitHub side - max-allowed-issues: 2147483647 - - # Upload the SARIF file generated in the previous step - - name: Upload SARIF results file - uses: github/codeql-action/upload-sarif@v2 - with: - sarif_file: results.sarif \ No newline at end of file diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 527164a..d832b9b 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -2,7 +2,14 @@ name: Build Docker Image on PR on: - pull_request: + push: + branches: + - master + - main + +env: + REGISTRY: ghcr.io + IMAGE_NAME: ${{ github.repository }} jobs: docker: diff --git a/.github/workflows/interchaintest-E2E.yml b/.github/workflows/interchaintest-E2E.yml new file mode 100644 index 0000000..5a8e319 --- /dev/null +++ b/.github/workflows/interchaintest-E2E.yml @@ -0,0 +1,206 @@ +name: ictest E2E + +on: + push: + tags: + - '**' + branches: + - '**' + paths: + - '**.yml' + - '**.go' + - '**.mod' + - '**.sum' + +env: + REGISTRY: ghcr.io + IMAGE_NAME: ${{ github.repository }}-e2e + GO_VERSION: 1.20.0 + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + build-and-push-image: + runs-on: ubuntu-latest + outputs: + branchTag: ${{ steps.meta.outputs.version }} + permissions: + contents: read + packages: write + + steps: + - name: Checkout repository + uses: actions/checkout@v3 + + # We setup go & cache dependencies here. This way each child job + # does not have to reinstall all dependencies individually. + # Should ID be unique to this job only? + - name: Setup Golang with cache + uses: magnetikonline/action-golang-cache@v4 + with: + go-version: ${{ env.GO_VERSION }} + id: go + + - name: Download dependencies + run: | + go mod download + cd interchaintest && go mod download + + - name: Set up QEMU + uses: docker/setup-qemu-action@v2 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + + - name: Log in to the Container registry + uses: docker/login-action@v2 + with: + registry: ${{ env.REGISTRY }} + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Extract metadata (tags, labels) for Docker + id: meta + uses: docker/metadata-action@v4 + with: + images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} + + - name: Build and push Docker image + id: push + uses: docker/build-push-action@v4 + with: + context: . + platforms: linux/amd64 + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=gha + cache-to: type=gha,mode=max + + # make terp-core:branchname here for all needs.build-and-push-image.outputs.branchTag + # then upload to github. Then download for each as a cache. This way its only built once + + # TODO: Add reusable job template here, just changing the `make` command for each + + test-terp-basic: + runs-on: ubuntu-latest + needs: build-and-push-image + steps: + - name: checkout chain + uses: actions/checkout@v2 + + - name: Setup Golang with cache + uses: magnetikonline/action-golang-cache@v4 + with: + go-version: ${{ env.GO_VERSION }} + id: go + + - run: make ictest-basic + env: + BRANCH_CI: ${{needs.build-and-push-image.outputs.branchTag}} + + test-terp-ibc: + runs-on: ubuntu-latest + needs: build-and-push-image + steps: + - name: Setup Golang with cache + uses: magnetikonline/action-golang-cache@v4 + with: + go-version: ${{ env.GO_VERSION }} + id: go + + - name: checkout chain + uses: actions/checkout@v2 + + - run: make ictest-ibc + env: + BRANCH_CI: ${{needs.build-and-push-image.outputs.branchTag}} + + test-terp-upgrade: + runs-on: ubuntu-latest + needs: build-and-push-image + steps: + - name: checkout chain + uses: actions/checkout@v2 + + - name: Setup Golang with cache + uses: magnetikonline/action-golang-cache@v4 + with: + go-version: ${{ env.GO_VERSION }} + id: go + + - run: make ictest-upgrade + env: + BRANCH_CI: ${{needs.build-and-push-image.outputs.branchTag}} + + test-terp-ibchooks: + runs-on: ubuntu-latest + needs: build-and-push-image + steps: + - name: checkout chain + uses: actions/checkout@v2 + + - name: Setup Golang with cache + uses: magnetikonline/action-golang-cache@v4 + with: + go-version: ${{ env.GO_VERSION }} + id: go + + - run: make ictest-ibchooks + env: + BRANCH_CI: ${{needs.build-and-push-image.outputs.branchTag}} + + + # === UNITY CONTRACT === + test-terp-unity-deploy: + runs-on: ubuntu-latest + needs: build-and-push-image + steps: + - name: checkout chain + uses: actions/checkout@v2 + + - name: Setup Golang with cache + uses: magnetikonline/action-golang-cache@v4 + with: + go-version: ${{ env.GO_VERSION }} + id: go + + - run: make ictest-unity-deploy + env: + BRANCH_CI: ${{needs.build-and-push-image.outputs.branchTag}} + + test-terp-unity-gov: + runs-on: ubuntu-latest + needs: build-and-push-image + steps: + - name: checkout chain + uses: actions/checkout@v2 + + - name: Setup Golang with cache + uses: magnetikonline/action-golang-cache@v4 + with: + go-version: ${{ env.GO_VERSION }} + id: go + + - run: make ictest-unity-gov + env: + BRANCH_CI: ${{needs.build-and-push-image.outputs.branchTag}} + + test-terp-pfm: + runs-on: ubuntu-latest + needs: build-and-push-image + steps: + - name: checkout chain + uses: actions/checkout@v2 + + - name: Setup Golang with cache + uses: magnetikonline/action-golang-cache@v4 + with: + go-version: ${{ env.GO_VERSION }} + id: go + + - run: make ictest-pfm + env: + BRANCH_CI: ${{needs.build-and-push-image.outputs.branchTag}} \ No newline at end of file diff --git a/.github/workflows/push-docker-image.yml b/.github/workflows/push-docker-image.yml new file mode 100644 index 0000000..55d0b0d --- /dev/null +++ b/.github/workflows/push-docker-image.yml @@ -0,0 +1,75 @@ +# This workflow pushes new juno docker images on every new tag. +# +# On every new `vX.Y.Z` tag the following images are pushed: +# +# terpnetwork/terp-core:vX.Y.Z # is pushed +# terpnetwork/terp-core:X.Y.Z # is pushed +# terpnetwork/terp-core:X.Y # is updated to X.Y.Z +# terpnetwork/terp-core:X # is updated to X.Y.Z +# terpnetwork/terp-core:latest # is updated to X.Y.Z +# +# terpnetwork/terp-core-e2e:vX.Y.Z # is pushed +# terpnetwork/terp-core-e2e:X.Y.Z # is pushed +# terpnetwork/terp-core-e2e:X.Y # is updated to X.Y.Z +# terpnetwork/terp-core-e2e:X # is updated to X.Y.Z +# terpnetwork/terp-core-e2e:latest # is updated to X.Y.Z +# +# All the images above have support for linux/amd64 and linux/arm64. +# +# Due to QEMU virtualization used to build multi-platform docker images +# this workflow might take a while to complete. + +name: Push Docker Images + +on: + release: + types: [published, created, edited] + push: + tags: + - 'v[0-9]+.[0-9]+.[0-9]+' # ignore rc + +jobs: + terp-images: + runs-on: ubuntu-latest + steps: + - + name: Check out the repo + uses: actions/checkout@v3 + - + name: Set up QEMU + uses: docker/setup-qemu-action@v2 + - + name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + - name: Login to GitHub Container Registry + uses: docker/login-action@v2 + with: + registry: ghcr.io + username: ${{ github.repository_owner }} + password: ${{ secrets.GITHUB_TOKEN }} + - + name: Parse tag + id: tag + run: | + VERSION=$(echo ${{ github.ref_name }} | sed "s/v//") + MAJOR_VERSION=$(echo $VERSION | cut -d '.' -f 1) + MINOR_VERSION=$(echo $VERSION | cut -d '.' -f 2) + PATCH_VERSION=$(echo $VERSION | cut -d '.' -f 3) + echo "VERSION=$VERSION" >> $GITHUB_ENV + echo "MAJOR_VERSION=$MAJOR_VERSION" >> $GITHUB_ENV + echo "MINOR_VERSION=$MINOR_VERSION" >> $GITHUB_ENV + echo "PATCH_VERSION=$PATCH_VERSION" >> $GITHUB_ENV + - + name: Build and push + id: build_push_image + uses: docker/build-push-action@v4 + with: + file: Dockerfile + context: . + push: true + platforms: linux/amd64,linux/arm64 + tags: | + ghcr.io/terpnetwork/terp-core:${{ env.MAJOR_VERSION }} + ghcr.io/terpnetwork/terp-core:${{ env.MAJOR_VERSION }}.${{ env.MINOR_VERSION }} + ghcr.io/terpnetwork/terp-core:${{ env.MAJOR_VERSION }}.${{ env.MINOR_VERSION }}.${{ env.PATCH_VERSION }} + ghcr.io/terpnetwork/terp-core:v${{ env.MAJOR_VERSION }}.${{ env.MINOR_VERSION }}.${{ env.PATCH_VERSION }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..525239a --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,35 @@ +--- +name: release binary + +on: + release: + types: [created] + +jobs: + release-alpine-static: + permissions: write-all + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v3 + + - name: Docker compose + run: STAKE_TOKEN="uterpx" TIMEOUT_COMMIT=500ms docker-compose up -d + + - name: Copy binary + run: docker cp terpd_node_1:/usr/bin/terpd ./terpd + + - name: Save sha256 sum + run: sha256sum ./terpd > ./terpd_sha256.txt + + - name: Release + uses: softprops/action-gh-release@v1 + with: + token: ${{ github.token }} + files: | + terpd + terpd_sha256.txt + + - name: Dump docker logs on failure + if: failure() + uses: jwalton/gh-docker-logs@v2 diff --git a/.sonarcloud.properties b/.sonarcloud.properties deleted file mode 100644 index 39468de..0000000 --- a/.sonarcloud.properties +++ /dev/null @@ -1,5 +0,0 @@ -# see https://docs.sonarcloud.io/advanced-setup/automatic-analysis/ -sonar.sources=. -sonar.exclusions=**/tests/**,**/benchmarks/**,**/ibctesting/**,**/wasmtesting/**,**/simulation/**,**/testdata/**,**/*.pb.go,**/*.pb.gw.go,**/*.test.go,**/test_*.go,**/*_fixtures.go,**/mock_*.go,**/*_mock.go - -sonar.tests=. diff --git a/CHANGELOG.md b/CHANGELOG.md deleted file mode 100644 index ad4edda..0000000 --- a/CHANGELOG.md +++ /dev/null @@ -1,482 +0,0 @@ -# Changelog - -## [Unreleased](https://github.com/CosmWasm/wasmd/tree/HEAD) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.30.0...HEAD) - -## [v0.30.0](https://github.com/CosmWasm/wasmd/tree/v0.30.0) (2022-12-02) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.29.2...v0.30.0) - -- Provide source, builder and codehash information in store code proposal message[\#1072](https://github.com/CosmWasm/wasmd/pull/1072) -- Add new CLI query/ endpoint to get contracts by creator address [\#998](https://github.com/CosmWasm/wasmd/pull/998) -- Upgrade to Go v1.19 [\#1044](https://github.com/CosmWasm/wasmd/pull/1044) -- Upgrade to Cosmos-sdk to v0.45.11 [/#1096](https://github.com/CosmWasm/wasmd/pull/1096/) -- Upgrade to IBC v4.2.0 with interchain-accounts v0.2.4 [\#1088](https://github.com/CosmWasm/wasmd/pull/1088) -- Preserve contract history/ created date on genesis import [\#878](https://github.com/CosmWasm/wasmd/issues/878) -- Authz module integration - more granularity for WasmExecuteMsg authorizations [\#803](https://github.com/CosmWasm/wasmd/issues/803) -- StoreAndInstantiate gov proposal [\#785](https://github.com/CosmWasm/wasmd/issues/785) -- Start developer guide for contributors [\#654](https://github.com/CosmWasm/wasmd/issues/654) - -### Notable changes - -- IBC fee middleware is setup in `app.go`. Please note that it can be enabled with new channels only. A nice read is this [article](https://medium.com/the-interchain-foundation/ibc-relaying-as-a-service-the-in-protocol-incentivization-story-2c008861a957). -- Authz for wasm contracts can be granted via `wasmd tx wasm grant` and executed via `wasmd tx authz exec` command -- Go v1.19 required to prevent a mixed chain setup with older versions. Just to be on the safe side. -- Store code proposal types have new metadata fields added that can help to build client side tooling to verify the wasm contract in the proposal - -### Migration notes - -- The wasmd module version was bumped and a [state migration](https://github.com/CosmWasm/wasmd/pull/1021/files#diff-4357c2137e24f583b8f852cc210320cb71af18e2fdfb8c21b55d8667cfe54690R20) registered. -- See ibc-go [migration notes](https://github.com/cosmos/ibc-go/blob/v4.2.0/docs/migrations) -- See interchain-accounts [`MsgRegisterAccount.Version` field](https://github.com/cosmos/interchain-accounts-demo/compare/v0.1.0...v0.2.4#diff-ac8bca25810de6d3eef95f74fc9acf2223f3687822e6227b584e0d3b40db6566). Full diff [v0.1.0 to v0.2.4](https://github.com/cosmos/interchain-accounts-demo/compare/v0.1.0...v0.2.4) - -## [v0.29.2](https://github.com/CosmWasm/wasmd/tree/v0.29.2) (2022-11-08) - -- Fixes missing instantiate-anyof-addresses flag declaration for gov [/#1084](https://github.com/CosmWasm/wasmd/issues/1084) - -## [v0.29.1](https://github.com/CosmWasm/wasmd/tree/v0.29.1) (2022-10-14) - -- Upgrade to Cosmos-sdk to v45.9 [/#1052](https://github.com/CosmWasm/wasmd/pull/1052/) - -## [v0.29.0](https://github.com/CosmWasm/wasmd/tree/v0.29.0) (2022-10-10) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.28.0...v0.29.0) - -- Add dependencies for protobuf and remove third_party forlder [/#1030](https://github.com/CosmWasm/wasmd/pull/1030) -- Check wasmvm version on startup [\#1029](https://github.com/CosmWasm/wasmd/pull/1029/) -- Allow AccessConfig to use a list of addresses instead of just a single address [\#945](https://github.com/CosmWasm/wasmd/issues/945) -- Make contract addresses predictable \("deterministic"\) [\#942](https://github.com/CosmWasm/wasmd/issues/942) -- Add query for the total supply of a coin [\#903](https://github.com/CosmWasm/wasmd/pull/903) ([larry0x](https://github.com/larry0x)) -- Upgrade go to v1.18 [\#866] ([faddat](https://github.com/faddat)) -- Upgrade to ibc-go v3.3.0 REQUIRES [MIGRATION](https://github.com/cosmos/ibc-go/blob/v3.2.3/docs/migrations/support-denoms-with-slashes.md) [\#1016](https://github.com/CosmWasm/wasmd/pull/1016) -- Upgrade to cosmos-sdk v0.45.8 [\#964](https://github.com/CosmWasm/wasmd/pull/964/) ([faddat](https://github.com/faddat)) -- Upgrade wasmvm to v1.1.1 [\#1012](https://github.com/CosmWasm/wasmd/pull/1012), see [wasmvm v1.1.1](https://github.com/CosmWasm/wasmvm/releases/tag/v1.1.1) -- Add documentation how to add x/wasm to a new Cosmos SDK chain [\#876](https://github.com/CosmWasm/wasmd/issues/876) -- Upgrade keyring / go-keychain dependencies (removes deprecate warning) [\#957](https://github.com/CosmWasm/wasmd/issues/957) -- Make contract pinning an optional field in StoreCode proposals [\#972](https://github.com/CosmWasm/wasmd/issues/972) -- Add gRPC query for WASM params [\#889](https://github.com/CosmWasm/wasmd/issues/889) -- Expose Keepers in app.go? [\#881](https://github.com/CosmWasm/wasmd/issues/881) -- Remove unused `flagProposalType` flag in gov proposals [\#849](https://github.com/CosmWasm/wasmd/issues/849) -- Restrict code access config modifications [\#901](https://github.com/CosmWasm/wasmd/pull/901) -- Prevent migration to a restricted code [\#900](https://github.com/CosmWasm/wasmd/pull/900) -- Charge gas to unzip wasm code [\#898](https://github.com/CosmWasm/wasmd/pull/898) - -### Notable changes - -- BaseAccount and pruned vesting account types can be re-used for contracts addresses -- A new [MsgInstantiateContract2](https://github.com/CosmWasm/wasmd/pull/1014/files#diff-bf58b9da4b674719f07dd5421c532c1ead13a15f8896b59c1f724215d2064b73R75) was introduced which is an additional value for `message` type events -- Store event contains a new attribute with the code checksum now -- New `wasmd tx wasm instantiate2` CLI command for predictable addresses on instantiation -- New `cosmwasm_1_1` CosmWasm capability (former "feature") was introduced in [cosmwasm/#1356](https://github.com/CosmWasm/cosmwasm/pull/1356) to support total supply queries -- Protobuf files are published to [buf.build](https://buf.build/cosmwasm/wasmd/docs/main:cosmwasm.wasm.v1) - -### Migration notes - -- See ibc-go [migration notes](https://github.com/cosmos/ibc-go/blob/v3.3.0/docs/migrations/support-denoms-with-slashes.md) - -## [v0.28.0](https://github.com/CosmWasm/wasmd/tree/v0.28.0) (2022-07-29) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.27.0...v0.28.0) - -**API Breaking** - -No - -**Fixed Bugs** - -- Fix: Make events in reply completely determinisitic by stripping out anything coming from Cosmos SDK (not CosmWasm codebase) [\#917](https://github.com/CosmWasm/wasmd/pull/917) ([assafmo](https://github.com/assafmo)) - -Migration notes: - -- Contracts can no longer parse events from any calls except if they call another contract (or instantiate it, migrate it, etc). -The main issue here is likely "Custom" queries from a blockchain, which want to send info (eg. how many tokens were swapped). -Since those custom bindings are maintained by the chain, they can use the data field to pass any deterministic information -back to the contract. We recommend using JSON encoding there with some documented format the contracts can parse out easily. -- For possible non-determinism issues, we also sort all attributes in events. Better safe than sorry. - -## [v0.27.0](https://github.com/CosmWasm/wasmd/tree/v0.27.0) (2022-05-19) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.26.0...v0.27.0) - -**API Breaking** -Yes - -**Fixed bugs:** - -- Fix: allow no admin in instantiation through proposal [\#828](https://github.com/CosmWasm/wasmd/pull/828) ([jhernandezb](https://github.com/jhernandezb)) -- Fix SudoContractProposal and ExecuteContractProposal [\#808](https://github.com/CosmWasm/wasmd/pull/808) ([the-frey](https://github.com/the-frey)) - -**Implemented Enhancements** - -- Add UpdateInstantiateConfig governance proposal [\#820](https://github.com/CosmWasm/wasmd/pull/796) ([jhernandezb](https://github.com/jhernandezb)) -- Upgrade wasmvm to v1.0.0 [\#844](https://github.com/CosmWasm/wasmd/pull/844) and [\#858](https://github.com/CosmWasm/wasmd/pull/858) -- Support state sync [\#478](https://github.com/CosmWasm/wasmd/issues/478) -- Upgrade to ibc-go v3 [\#806](https://github.com/CosmWasm/wasmd/issues/806) -- Initial ICA integration [\#837](https://github.com/CosmWasm/wasmd/pull/837) ([ethanfrey](https://github.com/ethanfrey)) -- Consolidate MaxWasmSize constraints into a single var [\#826](https://github.com/CosmWasm/wasmd/pull/826) -- Add AccessConfig to CodeInfo query response [\#829](https://github.com/CosmWasm/wasmd/issues/829) -- Bump sdk to v0.45.4 [\#818](https://github.com/CosmWasm/wasmd/pull/818) ([alpe](https://github.com/alpe)) -- Bump buf docker image to fix proto generation issues [\#820](https://github.com/CosmWasm/wasmd/pull/820) ([alpe](https://github.com/alpe)) -- Add MsgStoreCode and MsgInstantiateContract support to simulations [\#831](https://github.com/CosmWasm/wasmd/pull/831) ([pinosu](https://github.com/pinosu)) - -**Implemented Enhancements** - -- Make MaxLabelSize a var not const [\#822](https://github.com/CosmWasm/wasmd/pull/822) - -## [v0.26.0](https://github.com/CosmWasm/wasmd/tree/v0.26.0) (2022-04-21) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.25.0...v0.26.0) - -**Fixed bugs:** - -- Unpack contract details from genesis [\#802](https://github.com/CosmWasm/wasmd/pull/802) - -**Closed issues:** - -- Issue Updating uploadAccess Param [\#804](https://github.com/CosmWasm/wasmd/issues/804) -- Add tx query to wasmd QueryPlugins for smart contract [\#788](https://github.com/CosmWasm/wasmd/issues/788) - -**Merged pull requests:** - -- Disable stargate queries [\#812](https://github.com/CosmWasm/wasmd/pull/812) -- Gov param change examples [\#805](https://github.com/CosmWasm/wasmd/pull/805) -- Create link to SECURITY.md in other repo [\#801](https://github.com/CosmWasm/wasmd/pull/801) -- Tests some event edge cases [\#799](https://github.com/CosmWasm/wasmd/pull/799) - -## [v0.25.0](https://github.com/CosmWasm/wasmd/tree/v0.25.0) (2022-04-06) - -**API Breaking** - -- Upgrade wasmvm to v1.0.0-beta10 [\#790](https://github.com/CosmWasm/wasmd/pull/790), [\#800](https://github.com/CosmWasm/wasmd/pull/800) - -**Implemented Enhancements** - -- Fix: close iterators [\#792](https://github.com/CosmWasm/wasmd/pull/792) -- Use callback pattern for contract state iterator [\#794](https://github.com/CosmWasm/wasmd/pull/794) -- Bump github.com/stretchr/testify from 1.7.0 to 1.7.1 [\#787](https://github.com/CosmWasm/wasmd/pull/787) -- Bump github.com/cosmos/ibc-go/v2 from 2.0.3 to 2.2.0 [\#786](https://github.com/CosmWasm/wasmd/pull/786) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.24.0...v0.25.0) - -## [v0.24.0](https://github.com/CosmWasm/wasmd/tree/v0.24.0) (2022-03-09) - -**API Breaking** - -- Add cosmwasm project prefix to REST query paths [\#743](https://github.com/CosmWasm/wasmd/issues/743) -- Add support for old contract addresses of length 20 [\#758](https://github.com/CosmWasm/wasmd/issues/758) -- Update wasmvm to 1.0.0-beta7 (incl wasmer 2.2) [\#774](https://github.com/CosmWasm/wasmd/issues/774) - -**Fixed bugs** - -- Add missing colons in String of some proposals [\#752](https://github.com/CosmWasm/wasmd/pull/752) -- Replace custom codec with SDK codec (needed for rosetta) [\#760](https://github.com/CosmWasm/wasmd/pull/760) -- Support `--no-admin` flag on cli for gov instantiation [\#771](https://github.com/CosmWasm/wasmd/pull/771) - -**Implemented Enhancements** - -- Add support for Buf Build [\#753](https://github.com/CosmWasm/wasmd/pull/753), [\#755](https://github.com/CosmWasm/wasmd/pull/755), [\#756](https://github.com/CosmWasm/wasmd/pull/756) -- Redact most errors sent to contracts, for better determinism guarantees [\#765](https://github.com/CosmWasm/wasmd/pull/765), [\#775](https://github.com/CosmWasm/wasmd/pull/775) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.23.0...v0.24.0) - -## [v0.23.0](https://github.com/CosmWasm/wasmd/tree/v0.23.0) (2022-01-28) - -**Fixed bugs** - -- Set end block order [\#736](https://github.com/CosmWasm/wasmd/issues/736) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.22.0...v0.23.0) - -## [v0.22.0](https://github.com/CosmWasm/wasmd/tree/v0.22.0) (2022-01-20) - -**Api Breaking:** - -- Upgrade to cosmos-sdk v0.45.0 [\#717](https://github.com/CosmWasm/wasmd/pull/717) -- Upgrade wasmvm to v1.0.0-beta5 [\#714](https://github.com/CosmWasm/wasmd/pull/714) - -**Implemented Enhancements:** - -- Use proper SystemError::NoSuchContract on ContractInfo if missing [\#687](https://github.com/CosmWasm/wasmd/issues/687) -- Benchmark tests flickering: directory not empty [\#659](https://github.com/CosmWasm/wasmd/issues/659) -- Implement PinCode and UnpinCode proposal client handlers [\#707](https://github.com/CosmWasm/wasmd/pull/707) ([orkunkl](https://github.com/orkunkl)) -- Use replace statements to enforce consistent versioning. [\#692](https://github.com/CosmWasm/wasmd/pull/692) ([faddat](https://github.com/faddat)) -- Fixed circleci by removing the golang executor from a docker build -- Go 1.17 provides a much clearer go.mod file [\#679](https://github.com/CosmWasm/wasmd/pull/679) ([faddat](https://github.com/faddat)) -- Autopin wasm code uploaded by gov proposal [\#726](https://github.com/CosmWasm/wasmd/pull/726) ([ethanfrey](https://github.com/ethanfrey)) -- You must explicitly declare --no-admin on cli instantiate if that is what you want [\#727](https://github.com/CosmWasm/wasmd/pull/727) ([ethanfrey](https://github.com/ethanfrey)) -- Add governance proposals for Wasm Execute and Sudo [\#730](https://github.com/CosmWasm/wasmd/pull/730) ([ethanfrey](https://github.com/ethanfrey)) -- Remove unused run-as flag from Wasm Migrate proposals [\#730](https://github.com/CosmWasm/wasmd/pull/730) ([ethanfrey](https://github.com/ethanfrey)) -- Expose wasm/Keeper.SetParams [\#732](https://github.com/CosmWasm/wasmd/pull/732) ([ethanfrey](https://github.com/ethanfrey)) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.21.0...v0.22.0) - -## [v0.21.0](https://github.com/CosmWasm/wasmd/tree/v0.21.0) (2021-11-17) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.20.0...v0.21.0) - -**Fixed bugs + Api Breaking:** - -- Prevent infinite gas consumption in simulation queries [\#670](https://github.com/CosmWasm/wasmd/issues/670) -- Amino JSON representation of inner message in Msg{Instantiate,Migrate,Execute}Contract [\#642](https://github.com/CosmWasm/wasmd/issues/642) - -**Implemented Enhancements:** - -- Bump wasmvm to v1.0.0-beta2 [\#676](https://github.com/CosmWasm/wasmd/pull/676) -- Add Benchmarks to compare with native modules [\#635](https://github.com/CosmWasm/wasmd/issues/635) -- Document M1 is not supported [\#653](https://github.com/CosmWasm/wasmd/issues/653) -- Open read access to sequences [\#669](https://github.com/CosmWasm/wasmd/pull/669) -- Remove unused flags from command prompt for storing contract [\#647](https://github.com/CosmWasm/wasmd/issues/647) -- Ran `make format` [\#649](https://github.com/CosmWasm/wasmd/issues/649) -- Add golangci lint check to circleci jobs [\620](https://github.com/CosmWasm/wasmd/issues/620) -- Updated error log statements in initGenesis for easier debugging: [\#643](https://github.com/CosmWasm/wasmd/issues/643) -- Bump github.com/cosmos/iavl from 0.17.1 to 0.17.2 [\#673](https://github.com/CosmWasm/wasmd/pull/673) -- Bump github.com/rs/zerolog from 1.25.0 to 1.26.0 [\#666](https://github.com/CosmWasm/wasmd/pull/666) - -## [v0.20.0](https://github.com/CosmWasm/wasmd/tree/v0.20.0) (2021-10-08) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.19.0...v0.20.0) - -**Fixed bugs:** - -- Add capabilities to begin block [\#626](https://github.com/CosmWasm/wasmd/pull/626) - -**Api Breaking:** - -- Update to wasmvm 1.0.0-soon2 [\#624](https://github.com/CosmWasm/wasmd/issues/624) - -**Implemented Enhancements:** - -- Upgrade Cosmos-sdk v0.42.10 [\#627](https://github.com/CosmWasm/wasmd/pull/627) ([alpe](https://github.com/alpe)) -- Add transaction index implemented as counter [\#601](https://github.com/CosmWasm/wasmd/issues/601) -- Fix inconsistent return of `contractAddress` from `keeper/init()`? [\#616](https://github.com/CosmWasm/wasmd/issues/616) -- Query pinned wasm codes [\#596](https://github.com/CosmWasm/wasmd/issues/596) -- Doc IBC Events [\#593](https://github.com/CosmWasm/wasmd/issues/593) -- Allow contract Info query from the contract [\#584](https://github.com/CosmWasm/wasmd/issues/584) -- Revisit reply gas costs for submessages. [\#450](https://github.com/CosmWasm/wasmd/issues/450) -- Benchmarks for gas pricing [\#634](https://github.com/CosmWasm/wasmd/pull/634) -- Treat all contracts as pinned for gas costs in reply [\#630](https://github.com/CosmWasm/wasmd/pull/630) -- Bump github.com/spf13/viper from 1.8.1 to 1.9.0 [\#615](https://github.com/CosmWasm/wasmd/pull/615) - -## [v0.19.0](https://github.com/CosmWasm/wasmd/tree/v0.19.0) (2021-09-15) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.18.0...v0.19.0) - -**Fixed bugs:** - -- Ensure Queries are executed read only [\#610](https://github.com/CosmWasm/wasmd/issues/610) -- Fix bug in query handler initialization on reply [\#604](https://github.com/CosmWasm/wasmd/issues/604) - -**Api Breaking:** - -- Bump Go version to 1.16 [\#612](https://github.com/CosmWasm/wasmd/pull/612) - -**Implemented Enhancements:** - -- Ensure query isolation [\#611](https://github.com/CosmWasm/wasmd/pull/611) -- Optimize BalanceQuery [\#609](https://github.com/CosmWasm/wasmd/pull/609) -- Bump wasmvm to v0.16.1 [\#605](https://github.com/CosmWasm/wasmd/pull/605) -- Bump github.com/rs/zerolog from 1.23.0 to 1.25.0 [\#603](https://github.com/CosmWasm/wasmd/pull/603) -- Add decorator options [\#598](https://github.com/CosmWasm/wasmd/pull/598) -- Bump github.com/spf13/cast from 1.4.0 to 1.4.1 [\#592](https://github.com/CosmWasm/wasmd/pull/592) - -## [v0.18.0](https://github.com/CosmWasm/wasmd/tree/v0.18.0) (2021-08-16) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.17.0...v0.18.0) - -**Api Breaking:** - -- Events documented and refactored [\#448](https://github.com/CosmWasm/wasmd/issues/448), [\#589](https://github.com/CosmWasm/wasmd/pull/589), [\#587](https://github.com/CosmWasm/wasmd/issues/587) -- Add organisation to grpc gateway path [\#578](https://github.com/CosmWasm/wasmd/pull/578) -- Move Proto version from `v1beta1` to `v1` for all cosmwasm.wasm.* types - [\#563](https://github.com/CosmWasm/wasmd/pull/563) -- Renamed InitMsg and MigrateMsg fields to Msg. This applies to protobuf Msg - and Proposals, as well as REST and CLI [\#563](https://github.com/CosmWasm/wasmd/pull/563) -- Removed source and builder fields from StoreCode and CodeInfo. They were rarely used. - [\#564](https://github.com/CosmWasm/wasmd/pull/564) -- Changed contract address derivation function. If you hardcoded the first contract - addresses anywhere (in scripts?), please update them. - [\#565](https://github.com/CosmWasm/wasmd/pull/565) - -**Implemented Enhancements:** - -- Cosmos SDK 0.42.9, wasmvm 0.16.0 [\#582](https://github.com/CosmWasm/wasmd/pull/582) -- Better ibc contract interface [\#570](https://github.com/CosmWasm/wasmd/pull/570) ([ethanfrey](https://github.com/ethanfrey)) -- Reject invalid events/attributes returned from contracts [\#560](https://github.com/CosmWasm/wasmd/pull/560) -- IBC Query methods from Wasm contracts only return OPEN channels [\#568](https://github.com/CosmWasm/wasmd/pull/568) -- Extendable gas costs [\#525](https://github.com/CosmWasm/wasmd/issues/525) -- Limit init/migrate/execute payload message size [\#203](https://github.com/CosmWasm/wasmd/issues/203) -- Add cli alias [\#496](https://github.com/CosmWasm/wasmd/issues/496) -- Remove max gas limit [\#529](https://github.com/CosmWasm/wasmd/pull/529) ([alpe](https://github.com/alpe)) -- Add SECURITY.md [\#303](https://github.com/CosmWasm/wasmd/issues/303) - -## [v0.17.0](https://github.com/CosmWasm/wasmd/tree/v0.17.0) (2021-05-26) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.16.0...v0.17.0) - -**Features:** - -- Remove json type cast for contract msgs [\#520](https://github.com/CosmWasm/wasmd/pull/520) ([alpe](https://github.com/alpe)) -- Bump github.com/cosmos/cosmos-sdk from 0.42.4 to 0.42.5 [\#519](https://github.com/CosmWasm/wasmd/pull/519) ([dependabot-preview[bot]](https://github.com/apps/dependabot-preview)) - -## [v0.16.0](https://github.com/CosmWasm/wasmd/tree/v0.16.0) (2021-04-30) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.15.1...v0.16.0) - -**Features:** - -- Upgrade to wasmvm v0.14.0-rc1 [\#508](https://github.com/CosmWasm/wasmd/pull/508) ([alpe](https://github.com/alpe)) -- Use the cache metrics from WasmVM [\#500](https://github.com/CosmWasm/wasmd/issues/500) -- Update IBC.md [\#494](https://github.com/CosmWasm/wasmd/pull/494) ([ethanfrey](https://github.com/ethanfrey)) -- Extend ContractInfo for custom data [\#492](https://github.com/CosmWasm/wasmd/pull/492) ([alpe](https://github.com/alpe)) -- Reply response on submessages can overwrite "caller" result [\#495](https://github.com/CosmWasm/wasmd/issues/495) -- Update to sdk 0.42.4 [\#485](https://github.com/CosmWasm/wasmd/issues/485) -- Add extension points to the CLI [\#477](https://github.com/CosmWasm/wasmd/pull/477) ([alpe](https://github.com/alpe)) -- Simplify staking reward query [\#399](https://github.com/CosmWasm/wasmd/issues/399) -- Update IBC.md [\#398](https://github.com/CosmWasm/wasmd/issues/398) -- Add IBCQuery support [\#434](https://github.com/CosmWasm/wasmd/issues/434) -- Follow proto dir best practice \(in cosmos eco\) [\#342](https://github.com/CosmWasm/wasmd/issues/342) -- Remove internal package [\#464](https://github.com/CosmWasm/wasmd/pull/464) ([alpe](https://github.com/alpe)) -- Introduce new interfaces for extendability [\#471](https://github.com/CosmWasm/wasmd/pull/471) ([alpe](https://github.com/alpe)) -- Handle non default IBC transfer port in message encoder [\#396](https://github.com/CosmWasm/wasmd/issues/396) -- Collect Contract Metrics [\#387](https://github.com/CosmWasm/wasmd/issues/387) -- Add Submessages for IBC callbacks [\#449](https://github.com/CosmWasm/wasmd/issues/449) -- Handle wasmvm Burn message [\#489](https://github.com/CosmWasm/wasmd/pull/489) ([alpe](https://github.com/alpe)) -- Add telemetry [\#463](https://github.com/CosmWasm/wasmd/pull/463) ([alpe](https://github.com/alpe)) -- Handle non default transfer port id [\#462](https://github.com/CosmWasm/wasmd/pull/462) ([alpe](https://github.com/alpe)) -- Allow subsecond block times [\#453](https://github.com/CosmWasm/wasmd/pull/453) ([ethanfrey](https://github.com/ethanfrey)) -- Submsg and replies [\#441](https://github.com/CosmWasm/wasmd/pull/441) ([ethanfrey](https://github.com/ethanfrey)) -- Ibc query support [\#439](https://github.com/CosmWasm/wasmd/pull/439) ([ethanfrey](https://github.com/ethanfrey)) -- Pin/Unpin contract in cache [\#436](https://github.com/CosmWasm/wasmd/pull/436) ([alpe](https://github.com/alpe)) -- Stargate msg and query [\#435](https://github.com/CosmWasm/wasmd/pull/435) ([ethanfrey](https://github.com/ethanfrey)) -- Sudo entry point [\#433](https://github.com/CosmWasm/wasmd/pull/433) ([ethanfrey](https://github.com/ethanfrey)) -- Add custom message handler option [\#402](https://github.com/CosmWasm/wasmd/pull/402) ([alpe](https://github.com/alpe)) -- Expose contract pinning [\#401](https://github.com/CosmWasm/wasmd/issues/401) -- Add support for Stargate CosmosMsg/QueryRequest [\#388](https://github.com/CosmWasm/wasmd/issues/388) -- Add MsgInstantiateContractResponse.data [\#385](https://github.com/CosmWasm/wasmd/issues/385) -- Added randomized simulation parameters generation [\#389](https://github.com/CosmWasm/wasmd/pull/389) ([bragaz](https://github.com/bragaz)) -- Implement IBC contract support [\#394](https://github.com/CosmWasm/wasmd/pull/394) ([alpe](https://github.com/alpe)) - -**Api breaking:** - -- Improve list contracts by code query [\#497](https://github.com/CosmWasm/wasmd/pull/497) ([alpe](https://github.com/alpe)) -- Rename to just `funds` [/#423](https://github.com/CosmWasm/wasmd/issues/423) - -**Fixed bugs:** - -- Correct order for migrated contracts [\#323](https://github.com/CosmWasm/wasmd/issues/323) -- Keeper Send Coins does not perform expected validation [\#414](https://github.com/CosmWasm/wasmd/issues/414) - -## [v0.15.1](https://github.com/CosmWasm/wasmd/tree/v0.15.1) (2021-02-18) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.15.0...v0.15.1) - -**Implemented enhancements:** - -- Support custom MessageHandler in wasm [\#327](https://github.com/CosmWasm/wasmd/issues/327) - -**Fixed bugs:** - -- Fix Parameter change via proposal [\#392](https://github.com/CosmWasm/wasmd/issues/392) - -## [v0.15.0](https://github.com/CosmWasm/wasmd/tree/v0.15.0) (2021-01-27) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.14.1...v0.15.0) - -**Features:** - -- Upgrade to cosmos-sdk v0.41.0 [\#390](https://github.com/CosmWasm/wasmd/pull/390) - -## [v0.14.1](https://github.com/CosmWasm/wasmd/tree/v0.14.1) (2021-01-20) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.14.0...v0.14.1) - -**Features:** - -- Upgrade to cosmos-sdk v0.40.1 final + Tendermint 0.34.3 [\#380](https://github.com/CosmWasm/wasmd/pull/380) - -## [v0.14.0](https://github.com/CosmWasm/wasmd/tree/v0.14.0) (2021-01-11) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.13.0...v0.14.0) - -**Features:** - -- Upgrade to cosmos-sdk v0.40.0 final [\#354](https://github.com/CosmWasm/wasmd/pull/369) -- Refactor to GRPC message server [\#366](https://github.com/CosmWasm/wasmd/pull/366) -- Make it easy to initialize contracts in genesis file with new CLI commands[\#326](https://github.com/CosmWasm/wasmd/issues/326) -- Upgrade to WasmVM v0.13.0 [\#358](https://github.com/CosmWasm/wasmd/pull/358) -- Upgrade to cosmos-sdk v0.40.0-rc6 [\#354](https://github.com/CosmWasm/wasmd/pull/354) -- Upgrade to cosmos-sdk v0.40.0-rc5 [\#344](https://github.com/CosmWasm/wasmd/issues/344) -- Add Dependabot to keep dependencies secure and up-to-date [\#336](https://github.com/CosmWasm/wasmd/issues/336) - -**Fixed bugs:** - -- Dependabot can't resolve your Go dependency files [\#339](https://github.com/CosmWasm/wasmd/issues/339) -- Errors in `InitGenesis` [\#335](https://github.com/CosmWasm/wasmd/issues/335) -- Invalid homeDir for export command [\#334](https://github.com/CosmWasm/wasmd/issues/334) - -## [v0.13.0](https://github.com/CosmWasm/wasmd/tree/v0.13.0) (2020-12-04) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.12.1...v0.13.0) - -**Fixed bugs:** - -- REST handler wrong `Sender` source [\#324](https://github.com/CosmWasm/wasmd/issues/324) - -**Closed issues:** - -- Change proto package to match \.\.\ [\#329](https://github.com/CosmWasm/wasmd/issues/329) -- Out of gas causes panic when external contract store query executed [\#321](https://github.com/CosmWasm/wasmd/issues/321) -- Check codecov report [\#298](https://github.com/CosmWasm/wasmd/issues/298) -- cosmwasm.GoAPI will not work on sdk.ValAddress [\#264](https://github.com/CosmWasm/wasmd/issues/264) -- Stargate: Add pagination support for queries [\#242](https://github.com/CosmWasm/wasmd/issues/242) - -**Merged pull requests:** - -- Rename protobuf package [\#330](https://github.com/CosmWasm/wasmd/pull/330) ([alpe](https://github.com/alpe)) -- Use base request data for sender [\#325](https://github.com/CosmWasm/wasmd/pull/325) ([alpe](https://github.com/alpe)) -- Handle panics in query contract smart [\#322](https://github.com/CosmWasm/wasmd/pull/322) ([alpe](https://github.com/alpe)) - -## [v0.12.1](https://github.com/CosmWasm/wasmd/tree/v0.12.1) (2020-11-23) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.12.0...v0.12.1) - -**Closed issues:** - -- Complete IBC Mock testing [\#255](https://github.com/CosmWasm/wasmd/issues/255) -- Idea: do multiple queries in one API call [\#72](https://github.com/CosmWasm/wasmd/issues/72) - -**Merged pull requests:** - -- Exclude generate proto code files in coverage [\#320](https://github.com/CosmWasm/wasmd/pull/320) ([alpe](https://github.com/alpe)) -- Upgrade wasmvm to 0.12.0 [\#319](https://github.com/CosmWasm/wasmd/pull/319) ([webmaster128](https://github.com/webmaster128)) -- Fix chain id setup in contrib/local/setup\_wasmd.sh [\#318](https://github.com/CosmWasm/wasmd/pull/318) ([orkunkl](https://github.com/orkunkl)) -- Add pagination to grpc queries [\#317](https://github.com/CosmWasm/wasmd/pull/317) ([alpe](https://github.com/alpe)) - -## [v0.12.0](https://github.com/CosmWasm/wasmd/tree/v0.12.0) (2020-11-17) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.12.0-alpha1...v0.12.0) - -**Closed issues:** - -- Merge wasmd and wasmcli into a single binary [\#308](https://github.com/CosmWasm/wasmd/issues/308) -- Change bech32 prefix for wasmd [\#313](https://github.com/CosmWasm/wasmd/issues/313) -- Upgrade go-cowasmwasm to wasmvm 0.12 [\#309](https://github.com/CosmWasm/wasmd/issues/309) -- Use string type for AccAddresses in proto [\#306](https://github.com/CosmWasm/wasmd/issues/306) -- Upgrade to cosmos/sdk v0.40.0-rc2 [\#296](https://github.com/CosmWasm/wasmd/issues/296) -- Generate protobuf outputs in a container [\#295](https://github.com/CosmWasm/wasmd/issues/295) -- Instantiate contract process ordering [\#292](https://github.com/CosmWasm/wasmd/issues/292) -- Make Wasm maxSize a configuration option [\#289](https://github.com/CosmWasm/wasmd/issues/289) -- Return error if wasm to big [\#287](https://github.com/CosmWasm/wasmd/issues/287) - -**Merged pull requests:** - -- Set bech32 prefix [\#316](https://github.com/CosmWasm/wasmd/pull/316) ([alpe](https://github.com/alpe)) -- Replace sdk.AccAddress with bech32 string [\#314](https://github.com/CosmWasm/wasmd/pull/314) ([alpe](https://github.com/alpe)) -- Integrate wasmcli into wasmd [\#312](https://github.com/CosmWasm/wasmd/pull/312) ([alpe](https://github.com/alpe)) -- Upgrade wasmvm aka go-cosmwasm [\#311](https://github.com/CosmWasm/wasmd/pull/311) ([alpe](https://github.com/alpe)) -- Upgrade to Stargate RC3 [\#305](https://github.com/CosmWasm/wasmd/pull/305) ([alpe](https://github.com/alpe)) -- Containerized Protobuf generation [\#304](https://github.com/CosmWasm/wasmd/pull/304) ([alpe](https://github.com/alpe)) -- Reject wasm code exceeding limit [\#302](https://github.com/CosmWasm/wasmd/pull/302) ([alpe](https://github.com/alpe)) -- Support self calling contract on instantiation [\#300](https://github.com/CosmWasm/wasmd/pull/300) ([alpe](https://github.com/alpe)) -- Upgrade to Stargate RC2 [\#299](https://github.com/CosmWasm/wasmd/pull/299) ([alpe](https://github.com/alpe)) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 05cb53b..0000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,110 +0,0 @@ -# Contributing - -Thank you for considering making contributions to Wasmd! - -Contributing to this repo can mean many things, such as participating in -discussion or proposing code changes. To ensure a smooth workflow for all -contributors, the general procedure for contributing has been established: - -1. Start by browsing [new issues](https://github.com/terpnetwork/terp-core/issues). - * Looking for a good place to start contributing? How about checking out some [good first issues](https://github.com/terpnetwork/terp-core/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) or [bugs](https://github.com/terpnetwork/terp-core/issues?q=is%3Aopen+is%3Aissue+label%3Abug)? -2. Determine whether a GitHub issue or discussion is more appropriate for your needs: - 1. If the issue you want addressed is a specific proposal or a bug, then open a [new issue](https://github.com/terpnetwork/terp-core/issues/new). - 2. Review existing [issues](https://github.com/terpnetwork/terp-core/issues) to find an issue you'd like to help with. -3. Participate in thoughtful discussion on that issue. -4. If you would like to contribute: - 1. Ensure that the proposal has been accepted. - 2. Ensure that nobody else has already begun working on this issue. If they have, - make sure to contact them to collaborate. - 3. If nobody has been assigned for the issue and you would like to work on it, - make a comment on the issue to inform the community of your intentions - to begin work. -5. To submit your work as a contribution to the repository follow standard GitHub best practices. See [pull request guideline](#pull-requests) below. - -**Note:** For very small or blatantly obvious problems such as typos, you are -not required to an open issue to submit a PR, but be aware that for more complex -problems/features, if a PR is opened before an adequate design discussion has -taken place in a GitHub issue, that PR runs a high likelihood of being rejected. - -## Development Procedure - -* The latest state of development is on `main`. -* `main` must never fail `make lint test test-race`. -* No `--force` onto `main` (except when reverting a broken commit, which should seldom happen). -* Create a branch to start work: - * Fork the repo (core developers must create a branch directly in the Wasmd repo), - branch from the HEAD of `main`, make some commits, and submit a PR to `main`. - * For core developers working within the `wasmd` repo, follow branch name conventions to ensure a clear - ownership of branches: `{issue#}-branch-name`. - * See [Branching Model](#branching-model-and-release) for more details. -* Be sure to run `make format` before every commit. The easiest way - to do this is have your editor run it for you upon saving a file (most of the editors - will do it anyway using a pre-configured setup of the programming language mode). -* Follow the [CODING GUIDELINES](CODING_GUIDELINES.md), which defines criteria for designing and coding a software. - -Code is merged into main through pull request procedure. - -### Testing - -Tests can be executed by running `make test` at the top level of the wasmd repository. - -### Pull Requests - -Before submitting a pull request: - -* merge the latest main `git merge origin/main`, -* run `make lint test` to ensure that all checks and tests pass. - -Then: - -1. If you have something to show, **start with a `Draft` PR**. It's good to have early validation of your work and we highly recommend this practice. A Draft PR also indicates to the community that the work is in progress. - Draft PRs also helps the core team provide early feedback and ensure the work is in the right direction. -2. When the code is complete, change your PR from `Draft` to `Ready for Review`. -3. Be sure to include a relevant changelog entry in the `Unreleased` section of `CHANGELOG.md` (see file for log format). The entry should be on top of all others changes in the section. - -PRs name should start upper case. -Additionally, each PR should only address a single issue. - -NOTE: when merging, GitHub will squash commits and rebase on top of the main. - -## Protobuf - -We use [Protocol Buffers](https://developers.google.com/protocol-buffers) along with [gogoproto](https://github.com/cosmos/gogoproto) to generate code for use in Wasmd. - -For deterministic behavior around Protobuf tooling, everything is containerized using Docker. Make sure to have Docker installed on your machine, or head to [Docker's website](https://docs.docker.com/get-docker/) to install it. - -For formatting code in `.proto` files, you can run `make proto-format` command. - -For linting we use [buf](https://buf.build/). You can use the commands `make proto-lint` to lint your proto files. - -To generate the protobuf stubs, you can run `make proto-gen`. - -We also added the `make proto-all` command to run all the above commands sequentially. - -In order for imports to properly compile in your IDE, you may need to manually set your protobuf path in your IDE's workspace settings/config. - -For example, in vscode your `.vscode/settings.json` should look like: - -```json -{ - "protoc": { - "options": [ - "--proto_path=${workspaceRoot}/proto", - ] - } -} -``` - -## Branching Model and Release - -User-facing repos should adhere to the trunk based development branching model: https://trunkbaseddevelopment.com. User branches should start with a user name, example: `{moniker}/{issue#}-branch-name`. - -Wasmd utilizes [semantic versioning](https://semver.org/). - -### PR Targeting - -Ensure that you base and target your PR on the `main` branch. - -All feature additions and all bug fixes must be targeted against `main`. Exception is for bug fixes which are only related to a released version. In that case, the related bug fix PRs must target against the release branch. - -If needed, we backport a commit from `main` to a release branch (excluding consensus breaking feature, API breaking and similar). \ No newline at end of file diff --git a/Makefile b/Makefile index f6069ef..9c37a41 100644 --- a/Makefile +++ b/Makefile @@ -1,21 +1,31 @@ #!/usr/bin/make -f -PACKAGES_SIMTEST=$(shell go list ./... | grep '/simulation') -VERSION := $(shell echo $(shell git describe --tags) | sed 's/^v//') +BRANCH := $(shell git rev-parse --abbrev-ref HEAD) COMMIT := $(shell git log -1 --format='%H') -LEDGER_ENABLED ?= true -SDK_PACK := $(shell go list -m github.com/cosmos/cosmos-sdk | sed 's/ /\@/g') BINDIR ?= $(GOPATH)/bin -SIMAPP = ./app +APP = ./app + +# don't override user values +ifeq (,$(VERSION)) + VERSION := $(shell git describe --tags) + # if VERSION is empty, then populate it with branch's name and raw commit hash + ifeq (,$(VERSION)) + VERSION := $(BRANCH)-$(COMMIT) + endif +endif -# for dockerized protobuf tools +PACKAGES_SIMTEST=$(shell go list ./... | grep '/simulation') +LEDGER_ENABLED ?= true +SDK_PACK := $(shell go list -m github.com/cosmos/cosmos-sdk | sed 's/ /\@/g') +BFT_VERSION := $(shell go list -m github.com/cometbft/cometbft | sed 's:.* ::') # grab everything after the space in "github.com/cometbft/cometbft v0.34.7" DOCKER := $(shell which docker) -BUF_IMAGE=bufbuild/buf@sha256:3cb1f8a4b48bd5ad8f09168f10f607ddc318af202f5c057d52a45216793d85e5 #v1.4.0 DOCKER_BUF := $(DOCKER) run --rm -v $(CURDIR):/workspace --workdir /workspace $(BUF_IMAGE) -HTTPS_GIT := https://github.com/terpnetwork/terp-core.git - +BUILDDIR ?= $(CURDIR)/build +VERSION := $(shell echo $(shell git describe --tags) | sed 's/^v//') +E2E_UPGRADE_VERSION := "v14" export GO111MODULE = on +# for dockerized protobuf tools # process build tags build_tags = netgo @@ -42,8 +52,8 @@ ifeq ($(LEDGER_ENABLED),true) endif endif -ifeq ($(WITH_CLEVELDB),yes) - build_tags += gcc +ifeq (cleveldb,$(findstring cleveldb,$(TERP_BUILD_OPTIONS))) + build_tags += gcc cleveldb endif build_tags += $(BUILD_TAGS) build_tags := $(strip $(build_tags)) @@ -61,22 +71,37 @@ ldflags = -X github.com/cosmos/cosmos-sdk/version.Name=terp \ -X github.com/cosmos/cosmos-sdk/version.Commit=$(COMMIT) \ -X github.com/terpnetwork/terp-core/app.Bech32Prefix=terp \ -X "github.com/cosmos/cosmos-sdk/version.BuildTags=$(build_tags_comma_sep)" + -X github.com/cometbft/cometbft/version.TMCoreSemVer=$(BFT_VERSION) -ifeq ($(WITH_CLEVELDB),yes) +ifeq (cleveldb,$(findstring cleveldb,$(TERP_BUILD_OPTIONS))) ldflags += -X github.com/cosmos/cosmos-sdk/types.DBBackend=cleveldb endif ifeq ($(LINK_STATICALLY),true) ldflags += -linkmode=external -extldflags "-Wl,-z,muldefs -static" endif +ifeq (,$(findstring nostrip,$(TERP_BUILD_OPTIONS))) + ldflags += -w -s +endif ldflags += $(LDFLAGS) ldflags := $(strip $(ldflags)) -BUILD_FLAGS := -tags "$(build_tags_comma_sep)" -ldflags '$(ldflags)' -trimpath +BUILD_FLAGS := -tags "$(build_tags)" -ldflags '$(ldflags)' +# check for nostrip option +ifeq (,$(findstring nostrip,$(TERP_BUILD_OPTIONS))) + BUILD_FLAGS += -trimpath +endif # The below include contains the tools and runsim targets. include contrib/devtools/Makefile -all: install lint test +all: install + @echo "--> project root: go mod tidy" + @go mod tidy + @echo "--> project root: linting --fix" + @GOGC=1 golangci-lint run --fix --timeout=8m + +install: go.sum + go install -mod=readonly $(BUILD_FLAGS) ./cmd/terpd build: go.sum ifeq ($(OS),Windows_NT) @@ -96,34 +121,15 @@ else go build -mod=readonly $(BUILD_FLAGS) -o build/contract_tests ./cmd/contract_tests endif -install: go.sum - go install -mod=readonly $(BUILD_FLAGS) ./cmd/terpd - -######################################## -### Tools & dependencies - -go-mod-cache: go.sum - @echo "--> Download go modules to local cache" - @go mod download +test-node: + CHAIN_ID="local-1" HOME_DIR="~/.terp1" TIMEOUT_COMMIT="500ms" CLEAN=true sh scripts/test_node.sh -go.sum: go.mod - @echo "--> Ensure dependencies have not been modified" - @go mod verify -draw-deps: - @# requires brew install graphviz or apt-get install graphviz - go install github.com/RobotsAndPencils/goviz@latest - @goviz -i ./cmd/terpd -d 2 | dot -Tpng -o dependency-graph.png -clean: - rm -rf snapcraft-local.yaml build/ - -distclean: clean - rm -rf vendor/ - -######################################## -### Testing +############################################################################### +### Testing ### +############################################################################### test: test-unit test-all: check test-race test-cover @@ -142,15 +148,18 @@ benchmark: test-sim-import-export: runsim @echo "Running application import/export simulation. This may take several minutes..." - @$(BINDIR)/runsim -Jobs=4 -SimAppPkg=$(SIMAPP) -ExitOnFail 50 5 TestAppImportExport + @$(BINDIR)/runsim -Jobs=4 -SimAppPkg=$(APP) -ExitOnFail 50 5 TestAppImportExport test-sim-multi-seed-short: runsim @echo "Running short multi-seed application simulation. This may take awhile!" - @$(BINDIR)/runsim -Jobs=4 -SimAppPkg=$(SIMAPP) -ExitOnFail 50 5 TestFullAppSimulation + @$(BINDIR)/runsim -Jobs=4 -SimAppPkg=$(APP) -ExitOnFail 50 5 TestFullAppSimulation test-sim-deterministic: runsim @echo "Running short multi-seed application simulation. This may take awhile!" - @$(BINDIR)/runsim -Jobs=4 -SimAppPkg=$(SIMAPP) -ExitOnFail 1 1 TestAppStateDeterminism + @$(BINDIR)/runsim -Jobs=4 -SimAppPkg=$(APP) -ExitOnFail 1 1 TestAppStateDeterminism + +benchmark: + @go test -mod=readonly -bench=. $(PACKAGES_UNIT) ############################################################################### @@ -170,11 +179,57 @@ format: format-tools find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./client/lcd/statik/statik.go" | xargs gofumpt -w find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./client/lcd/statik/statik.go" | xargs goimports -w -local github.com/terpnetwork/terp-core +############################################################################### +### e2e interchain test ### +############################################################################### + + # Executes basic chain tests via interchaintest +ictest-basic: rm-testcache + cd interchaintest && go test -race -v -run TestBasicTerpStart . + +ictest-ibchooks: rm-testcache + cd interchaintest && go test -race -v -run TestTerpIBCHooks . + +ictest-pfm: rm-testcache + cd interchaintest && go test -race -v -run TestPacketForwardMiddlewareRouter . + + +# Executes a basic chain upgrade test via interchaintest +ictest-upgrade: rm-testcache + cd interchaintest && go test -race -v -run TestBasicTerpUpgrade . + +# Executes a basic chain upgrade locally via interchaintest after compiling a local image as terp-core:local +ictest-upgrade-local: local-image ictest-upgrade + +# Executes IBC tests via interchaintest +ictest-ibc: rm-testcache + cd interchaintest && go test -race -v -run TestTerpGaiaIBCTransfer . +rm-testcache: + go clean -testcache + +.PHONY: test-mutation ictest-basic ictest-upgrade ictest-ibc + +############################################################################### +### heighliner ### +############################################################################### + +get-heighliner: + git clone https://github.com/strangelove-ventures/heighliner.git + cd heighliner && go install + +local-image: +ifeq (,$(shell which heighliner)) + echo 'heighliner' binary not found. Consider running `make get-heighliner` +else + heighliner build -c terpnetwork --local -f ./chains.yaml +endif + +.PHONY: get-heighliner local-image ############################################################################### ### Protobuf ### ############################################################################### -protoVer=0.11.6 +protoVer=0.13.1 protoImageName=ghcr.io/cosmos/proto-builder:$(protoVer) protoImage=$(DOCKER) run --rm -v $(CURDIR):/workspace --workdir /workspace $(protoImageName) @@ -184,11 +239,14 @@ proto-gen: @echo "Generating Protobuf files" @$(protoImage) sh ./scripts/protocgen.sh +proto-swagger-gen: + @echo "Generating Protobuf Swagger" + @$(protoImage) sh ./scripts/protoc_swagger_openapi_gen.sh + $(MAKE) update-swagger-docs + proto-format: @echo "Formatting Protobuf files" @$(protoImage) find ./ -name "*.proto" -exec clang-format -i {} \; -proto-swagger-gen: - @./scripts/protoc-swagger-gen.sh proto-lint: @$(DOCKER_BUF) lint --error-format=json diff --git a/docs/SECURITY.md b/SECURITY.md similarity index 100% rename from docs/SECURITY.md rename to SECURITY.md diff --git a/UPGRADING.md b/UPGRADING.md deleted file mode 100644 index 21de9cd..0000000 --- a/UPGRADING.md +++ /dev/null @@ -1,277 +0,0 @@ -# Upgrading - -With stargate, we have access to the `x/upgrade` module, which we can use to perform -inline upgrades. Please first read both the basic -[x/upgrade spec](https://github.com/cosmos/cosmos-sdk/blob/master/x/upgrade/spec/01_concepts.md) -and [go docs](https://godoc.org/github.com/cosmos/cosmos-sdk/x/upgrade#hdr-Performing_Upgrades) -for the background on the module. - -In this case, we will demo an update with no state migration. This is for cases when -there is a state-machine-breaking (but not state-breaking) bugfix or enhancement. -There are some -[open issues running some state migrations](https://github.com/cosmos/cosmos-sdk/issues/8265) -and we will wait for that to be fixed before trying those. - -The following will lead through running an upgrade on a local node, but the same process -would work on a real network (with more ops and governance coordination). - -## Setup - -We need to have two different versions of `wasmd` which depend on state-compatible -versions of the Cosmos SDK. We only focus on upgrade starting with stargate. You will -have to use the "dump state and restart" approach to move from launchpad to stargate. - -For this demo, we will show an upgrade from `v0.14.0` to musselnet branch. - -### Handler - -You will need to register a handler for the upgrade. This is specific to a particular -testnet and upgrade path, and the default `wasmd` will never have a registered handler -on master. In this case, we make a `musselnet` branch off of `v0.14.0` just -registering one handler with a given name. - -Look at [PR 351](https://github.com/terpnetwork/terp-core/pull/351/files) for an example -of a minimal handler. We do not make any state migrations, but rather use this -as a flag to coordinate all validators to stop the old version at one height, and -start the specified v2 version on the next block. - -### Prepare binaries - -Let's get the two binaries we want to test, the pre-upgrade and the post-upgrade -binaries. In this case the pre-release is already a published to docker hub and -can be downloaded simply via: - -`docker pull cosmwasm/wasmd:v0.14.0` - -(If this is not yet released, build it from the tip of master) - -The post-release is not published, so we can build it ourselves. Check out this -`wasmd` repo, and the proper `musselnet` branch: - -``` -# use musselnet-v2 tag once that exists -git checkout musselnet -docker build . -t wasmd:musselnet-v2 -``` - -Verify they are both working for you locally: - -``` -docker run cosmwasm/wasmd:v0.14.0 wasmd version -docker run wasmd:musselnet-v2 wasmd version -``` - -## Start the pre-release chain - -Follow the normal setup stage, but in this case we will want to have super short -governance voting period, 5 minutes rather than 2 days (or 2 weeks!). - -**Setup a client with private key** - -```sh -## TODO: I think we need to do this locally??? -docker volume rm -f musselnet_client - -docker run --rm -it \ - -e PASSWORD=1234567890 \ - --mount type=volume,source=musselnet_client,target=/root \ - cosmwasm/wasmd:v0.14.0 /opt/setup_wasmd.sh - -# enter "1234567890" when prompted -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - cosmwasm/wasmd:v0.14.0 wasmd keys show -a validator -# use the address returned above here -CLIENT=wasm1anavj4eyxkdljp27sedrdlt9dm26c8a7a8p44l -``` - -**Setup the blockchain node** - -```sh -docker volume rm -f musselnet - -# add your testing address here, so you can do something with the client -docker run --rm -it \ - --mount type=volume,source=musselnet,target=/root \ - cosmwasm/wasmd:v0.14.0 /opt/setup_wasmd.sh $CLIENT - -# Update the voting times in the genesis file -docker run --rm -it \ - --mount type=volume,source=musselnet,target=/root \ - cosmwasm/wasmd:v0.14.0 sed -ie 's/172800s/300s/' /root/.terp/config/genesis.json - -# start up the blockchain and all embedded servers as one process -docker run --rm -it -p 26657:26657 -p 26656:26656 -p 1317:1317 \ - --mount type=volume,source=musselnet,target=/root \ - cosmwasm/wasmd:v0.14.0 /opt/run_wasmd.sh -``` - -## Sanity checks - -Let's use our client node to query the current state and send some tokens to a -random address: - -```sh -RCPT=wasm1pypadqklna33nv3gl063rd8z9q8nvauaalz820 - -# note --network=host so it can connect to the other docker image -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - query bank balances $CLIENT - -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - query bank balances $RCPT - -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - tx send validator $RCPT 500000ucosm,600000ustake --chain-id testing - -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - query bank balances $RCPT -``` - -## Take majority control of the chain - -In genesis we have a valiator with 250 million `ustake` bonded. We want to be easily -able to pass a proposal with our client. Let us bond 700 million `ustake` to ensure -we have > 67% of the voting power and will pass with the validator not voting. - -```sh -# get the "operator_address" (wasmvaloper...) from here -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - query staking validators -VALIDATOR=...... - -# and stake here -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - tx staking delegate $VALIDATOR 750000000ustake \ - --from validator --chain-id testing -``` - -## Vote on the upgrade - -Now that we see the chain is running and producing blocks, and our client has -enough token to control the netwrok, let's create a governance -upgrade proposal for the new chain to move to `musselnet-v2` (this must be the -same name as we use in the handler we created above, change this to match what -you put in your handler): - -```sh -# create the proposal -# check the current height and add 100-200 or so for the upgrade time -# (the voting period is ~60 blocks) -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - tx gov submit-proposal software-upgrade musselnet-v2 \ - --upgrade-height=500 --deposit=10000000ustake \ - --title="Upgrade" --description="Upgrade to musselnet-v2" \ - --from validator --chain-id testing - -# make sure it looks good -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - query gov proposal 1 - -# vote for it -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - tx gov vote 1 yes \ - --from validator --chain-id testing - -# ensure vote was counted -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - query gov votes 1 -``` - -## Swap out binaries - -Now, we just wait about 5 minutes for the vote to pass, and ensure it is passed: - -```sh -# make sure it looks good -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - query gov proposal 1 -``` - -After this, we just let the chain run and open the terminal so you can see the log files. -It should keep producing blocks until it hits height 500 (or whatever you set there), -when the process will print a huge stacktrace and hang. Immediately before the stack trace, you -should see a line like this (burried under tons of tendermint logs): - -`8:50PM ERR UPGRADE "musselnet-v2" NEEDED at height: 100:` - -Kill it with Ctrl-C, and then try to restart with the pre-upgrade version and it should -immediately fail on startup, with the same error message as above. - -```sh -docker run --rm -it -p 26657:26657 -p 26656:26656 -p 1317:1317 \ - --mount type=volume,source=musselnet,target=/root \ - cosmwasm/wasmd:v0.14.0 /opt/run_wasmd.sh -``` - -Then, we start with the post-upgrade version and see it properly update: - -```sh -docker run --rm -it -p 26657:26657 -p 26656:26656 -p 1317:1317 \ - --mount type=volume,source=musselnet,target=/root \ - wasmd:musselnet-v2 /opt/run_wasmd.sh -``` - -On a real network, operators will have to be awake when the upgrade plan is activated -and manually perform this switch, or use some automated tooling like -[cosmosvisor](https://github.com/cosmos/cosmos-sdk/blob/master/cosmovisor/README.md). - -## Check final state - -Now that we have upgraded, we can use the new client version. Let's do a brief -sanity check to ensure our balances are proper, and our stake remains -delegated. That and continued block production should be a good sign the upgrade -was successful: - -```sh -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - wasmd:musselnet-v2 wasmd \ - query bank balances $CLIENT - -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - wasmd:musselnet-v2 wasmd \ - query bank balances $RCPT - -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - wasmd:musselnet-v2 wasmd \ - query staking delegations $CLIENT -``` diff --git a/api_migration.md b/api_migration.md deleted file mode 100644 index c9aedd8..0000000 --- a/api_migration.md +++ /dev/null @@ -1,36 +0,0 @@ -# Changes to the api - -## [\#196](https://github.com/CosmWasm/wasmd/issues/196) - Move history of contract code migrations to their own prefix store - -The `ContractDetails.initMsg` used in cosmJs was moved into a new entity `ContractCodeHistoryEntry`. They contain code updates to a contract. - -### Route -This data is available via a new route `/wasm/contract/{contractAddr}/history` - -### Response -A list of ContractCodeHistoryEntries with following fields: -* `operation` can be any of `"Init", "Migrate", "Genesis"` -* `code_id` uint64 -* `msg` as raw json - -### Errors -* 404 - for an unknown contract - -### CLI -`wasmd query wasm contract-history [bech32_address] to print all the code changes.` -Example: -`wasmd query wasm contract-history cosmos18r5szma8hm93pvx6lwpjwyxruw27e0k5uw835c` -```json -[ - { - "operation": "Init", - "code_id": 1, - "msg": "\"init-msg\"" - }, - { - "operation": "Migrate", - "code_id": 2, - "msg": "\"migrate-msg\"" - } -] -``` diff --git a/app/ante.go b/app/ante.go index 2d26608..e408372 100644 --- a/app/ante.go +++ b/app/ante.go @@ -9,8 +9,8 @@ import ( 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" + wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" + wasmTypes "github.com/CosmWasm/wasmd/x/wasm/types" ) // HandlerOptions extend the SDK's AnteHandler options by requiring the IBC diff --git a/app/app.go b/app/app.go index a9d5c9a..8b868be 100644 --- a/app/app.go +++ b/app/app.go @@ -10,6 +10,8 @@ import ( autocliv1 "cosmossdk.io/api/cosmos/autocli/v1" reflectionv1 "cosmossdk.io/api/cosmos/reflection/v1" + errorsmod "cosmossdk.io/errors" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" dbm "github.com/cometbft/cometbft-db" abci "github.com/cometbft/cometbft/abci/types" @@ -32,7 +34,18 @@ import ( "github.com/cosmos/cosmos-sdk/store/streaming" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/address" "github.com/cosmos/cosmos-sdk/types/module" + icq "github.com/strangelove-ventures/async-icq/v7" + icqkeeper "github.com/strangelove-ventures/async-icq/v7/keeper" + icqtypes "github.com/strangelove-ventures/async-icq/v7/types" + packetforward "github.com/strangelove-ventures/packet-forward-middleware/v7/router" + packetforwardkeeper "github.com/strangelove-ventures/packet-forward-middleware/v7/router/keeper" + packetforwardtypes "github.com/strangelove-ventures/packet-forward-middleware/v7/router/types" + "github.com/terpnetwork/terp-core/v2/x/ibchooks" + ibchookskeeper "github.com/terpnetwork/terp-core/v2/x/ibchooks/keeper" + ibchookstypes "github.com/terpnetwork/terp-core/v2/x/ibchooks/types" + "github.com/cosmos/cosmos-sdk/version" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/auth/ante" @@ -121,20 +134,13 @@ import ( 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" govclient "github.com/cosmos/cosmos-sdk/x/gov/client" - "github.com/terpnetwork/terp-core/x/wasm" - wasmkeeper "github.com/terpnetwork/terp-core/x/wasm/keeper" - wasmtypes "github.com/terpnetwork/terp-core/x/wasm/types" - - // token factory - "github.com/terpnetwork/terp-core/x/tokenfactory" - tokenfactorykeeper "github.com/terpnetwork/terp-core/x/tokenfactory/keeper" - tokenfactorytypes "github.com/terpnetwork/terp-core/x/tokenfactory/types" + "github.com/CosmWasm/wasmd/x/wasm" + wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" + wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" // unnamed import of statik for swagger UI support _ "github.com/cosmos/cosmos-sdk/client/docs/statik" // statik for swagger UI support @@ -197,6 +203,37 @@ var ( Bech32PrefixConsPub = Bech32Prefix + sdk.PrefixValidator + sdk.PrefixConsensus + sdk.PrefixPublic ) +func init() { + SetAddressPrefixes() +} + +// SetAddressPrefixes builds the Config with Bech32 addressPrefix and publKeyPrefix for accounts, validators, and consensus nodes and verifies that addreeses have correct format. +func SetAddressPrefixes() { + config := sdk.GetConfig() + config.SetBech32PrefixForAccount(Bech32PrefixAccAddr, Bech32PrefixAccPub) + config.SetBech32PrefixForValidator(Bech32PrefixValAddr, Bech32PrefixValPub) + config.SetBech32PrefixForConsensusNode(Bech32PrefixConsAddr, Bech32PrefixConsPub) + + // This is copied from the cosmos sdk v0.43.0-beta1 + // source: https://github.com/cosmos/cosmos-sdk/blob/v0.43.0-beta1/types/address.go#L141 + config.SetAddressVerifier(func(bytes []byte) error { + if len(bytes) == 0 { + return errorsmod.Wrap(sdkerrors.ErrUnknownAddress, "addresses cannot be empty") + } + + if len(bytes) > address.MaxAddrLen { + return errorsmod.Wrapf(sdkerrors.ErrUnknownAddress, "address max length is %d, got %d", address.MaxAddrLen, len(bytes)) + } + + // TODO: Do we want to allow addresses of lengths other than 20 and 32 bytes? + if len(bytes) != 20 && len(bytes) != 32 { + return errorsmod.Wrapf(sdkerrors.ErrUnknownAddress, "address length must be 20 or 32 bytes, got %d", len(bytes)) + } + + return nil + }) +} + var ( // ModuleBasics defines the module BasicManager is in charge of setting up basic, // non-dependant module elements, such as codec registration @@ -236,7 +273,9 @@ var ( transfer.AppModuleBasic{}, ica.AppModuleBasic{}, ibcfee.AppModuleBasic{}, - tokenfactory.AppModuleBasic{}, + icq.AppModuleBasic{}, + ibchooks.AppModuleBasic{}, + packetforward.AppModuleBasic{}, ) // module account permissions @@ -250,9 +289,9 @@ var ( nft.ModuleName: nil, ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner}, ibcfeetypes.ModuleName: nil, + icqtypes.ModuleName: nil, icatypes.ModuleName: nil, wasm.ModuleName: {authtypes.Burner}, - tokenfactorytypes.ModuleName: {authtypes.Minter, authtypes.Burner}, } ) @@ -296,14 +335,18 @@ type TerpApp struct { IBCKeeper *ibckeeper.Keeper // IBC Keeper must be a pointer in the app, so we can SetRouter on it correctly IBCFeeKeeper ibcfeekeeper.Keeper + IBCHooksKeeper *ibchookskeeper.Keeper + PacketForwardKeeper *packetforwardkeeper.Keeper + ICQKeeper icqkeeper.Keeper ICAControllerKeeper icacontrollerkeeper.Keeper - TokenFactoryKeeper tokenfactorykeeper.Keeper ICAHostKeeper icahostkeeper.Keeper TransferKeeper ibctransferkeeper.Keeper WasmKeeper wasm.Keeper + ContractKeeper *wasmkeeper.PermissionedKeeper ScopedIBCKeeper capabilitykeeper.ScopedKeeper ScopedICAHostKeeper capabilitykeeper.ScopedKeeper + ScopedICQKeeper capabilitykeeper.ScopedKeeper ScopedICAControllerKeeper capabilitykeeper.ScopedKeeper ScopedTransferKeeper capabilitykeeper.ScopedKeeper ScopedIBCFeeKeeper capabilitykeeper.ScopedKeeper @@ -317,6 +360,10 @@ type TerpApp struct { // module configurator configurator module.Configurator + + // Middleware wrapper + Ics20WasmHooks *ibchooks.WasmHooks + HooksICS4Wrapper ibchooks.ICS4Middleware } // NewTerpApp returns a reference to an initialized TerpApp. @@ -365,9 +412,11 @@ func NewTerpApp( ibctransfertypes.StoreKey, ibcfeetypes.StoreKey, wasm.StoreKey, + icqtypes.StoreKey, + packetforwardtypes.StoreKey, + ibchookstypes.StoreKey, icahosttypes.StoreKey, icacontrollertypes.StoreKey, - tokenfactorytypes.StoreKey, ) tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey) @@ -412,6 +461,7 @@ func NewTerpApp( scopedICAHostKeeper := app.CapabilityKeeper.ScopeToModule(icahosttypes.SubModuleName) scopedICAControllerKeeper := app.CapabilityKeeper.ScopeToModule(icacontrollertypes.SubModuleName) scopedTransferKeeper := app.CapabilityKeeper.ScopeToModule(ibctransfertypes.ModuleName) + scopedICQKeeper := app.CapabilityKeeper.ScopeToModule(icqtypes.ModuleName) scopedWasmKeeper := app.CapabilityKeeper.ScopeToModule(wasm.ModuleName) app.CapabilityKeeper.Seal() @@ -471,14 +521,6 @@ func NewTerpApp( 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( appCodec, @@ -570,6 +612,20 @@ func NewTerpApp( app.BankKeeper, ) + // Configure the hooks keeper + hooksKeeper := ibchookskeeper.NewKeeper( + keys[ibchookstypes.StoreKey], + ) + app.IBCHooksKeeper = &hooksKeeper + + terpPrefix := sdk.GetConfig().GetBech32AccountAddrPrefix() + wasmHooks := ibchooks.NewWasmHooks(app.IBCHooksKeeper, app.ContractKeeper, &app.WasmKeeper, terpPrefix) // The contract keeper needs to be set later // The contract keeper needs to be set later + app.Ics20WasmHooks = &wasmHooks + app.HooksICS4Wrapper = ibchooks.NewICS4Middleware( + app.IBCKeeper.ChannelKeeper, + app.Ics20WasmHooks, + ) + // create evidence keeper with router evidenceKeeper := evidencekeeper.NewKeeper( appCodec, @@ -582,10 +638,25 @@ func NewTerpApp( // IBC Fee Module keeper app.IBCFeeKeeper = ibcfeekeeper.NewKeeper( - appCodec, keys[ibcfeetypes.StoreKey], - app.IBCKeeper.ChannelKeeper, // may be replaced with IBC middleware + appCodec, + keys[ibcfeetypes.StoreKey], + app.HooksICS4Wrapper, // replaced with IBC middleware + app.IBCKeeper.ChannelKeeper, + &app.IBCKeeper.PortKeeper, + app.AccountKeeper, + app.BankKeeper, + ) + + // Initialize packet forward middleware router + app.PacketForwardKeeper = packetforwardkeeper.NewKeeper( + appCodec, + keys[packetforwardtypes.StoreKey], + app.GetSubspace(packetforwardtypes.ModuleName), + app.TransferKeeper, // Will be zero-value here. Reference is set later on with SetTransferKeeper. + app.IBCKeeper.ChannelKeeper, + app.DistrKeeper, + app.BankKeeper, app.IBCKeeper.ChannelKeeper, - &app.IBCKeeper.PortKeeper, app.AccountKeeper, app.BankKeeper, ) // Create Transfer Keepers @@ -593,7 +664,8 @@ func NewTerpApp( appCodec, keys[ibctransfertypes.StoreKey], app.GetSubspace(ibctransfertypes.ModuleName), - app.IBCFeeKeeper, // ISC4 Wrapper: fee IBC middleware + // The ICS4Wrapper is replaced by the PacketForwardKeeper instead of the channel so that sending can be overridden by the middleware + app.PacketForwardKeeper, app.IBCKeeper.ChannelKeeper, &app.IBCKeeper.PortKeeper, app.AccountKeeper, @@ -601,6 +673,8 @@ func NewTerpApp( scopedTransferKeeper, ) + app.PacketForwardKeeper.SetTransferKeeper(app.TransferKeeper) + // IBC Fee Module keeper app.IBCFeeKeeper = ibcfeekeeper.NewKeeper( appCodec, keys[ibcfeetypes.StoreKey], @@ -609,11 +683,23 @@ func NewTerpApp( &app.IBCKeeper.PortKeeper, app.AccountKeeper, app.BankKeeper, ) + // ICQ Keeper + app.ICQKeeper = icqkeeper.NewKeeper( + appCodec, + keys[icqtypes.StoreKey], + app.GetSubspace(icqtypes.ModuleName), + app.IBCKeeper.ChannelKeeper, // may be replaced with middleware + app.IBCKeeper.ChannelKeeper, + &app.IBCKeeper.PortKeeper, + scopedICQKeeper, + NewQuerierWrapper(bApp), + ) + app.ICAHostKeeper = icahostkeeper.NewKeeper( appCodec, keys[icahosttypes.StoreKey], app.GetSubspace(icahosttypes.SubModuleName), - app.IBCFeeKeeper, // use ics29 fee as ics4Wrapper in middleware stack + app.HooksICS4Wrapper, app.IBCKeeper.ChannelKeeper, &app.IBCKeeper.PortKeeper, app.AccountKeeper, @@ -639,16 +725,15 @@ func NewTerpApp( // The last arguments can contain custom message handlers, and custom query handlers, // if we want to allow any custom callbacks - // 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...) + availableCapabilities := strings.Join(AllCapabilities(), ",") app.WasmKeeper = wasm.NewKeeper( appCodec, - keys[wasm.StoreKey], + app.keys[wasm.StoreKey], app.AccountKeeper, app.BankKeeper, app.StakingKeeper, distrkeeper.NewQuerier(app.DistrKeeper), + app.IBCFeeKeeper, app.IBCKeeper.ChannelKeeper, &app.IBCKeeper.PortKeeper, scopedWasmKeeper, @@ -673,6 +758,14 @@ func NewTerpApp( var transferStack porttypes.IBCModule transferStack = transfer.NewIBCModule(app.TransferKeeper) transferStack = ibcfee.NewIBCMiddleware(transferStack, app.IBCFeeKeeper) + transferStack = ibchooks.NewIBCMiddleware(transferStack, &app.HooksICS4Wrapper) + transferStack = packetforward.NewIBCMiddleware( + transferStack, + app.PacketForwardKeeper, + 0, + packetforwardkeeper.DefaultForwardTransferPacketTimeoutTimestamp, + packetforwardkeeper.DefaultRefundTransferPacketTimeoutTimestamp, + ) // Create Interchain Accounts Stack // SendPacket, since it is originating from the application to core IBC: @@ -695,12 +788,16 @@ func NewTerpApp( wasmStack = wasm.NewIBCHandler(app.WasmKeeper, app.IBCKeeper.ChannelKeeper, app.IBCFeeKeeper) wasmStack = ibcfee.NewIBCMiddleware(wasmStack, app.IBCFeeKeeper) + // create ICQ module + icqModule := icq.NewIBCModule(app.ICQKeeper) + // Create static IBC router, add app routes, then set and seal it ibcRouter := porttypes.NewRouter(). AddRoute(ibctransfertypes.ModuleName, transferStack). AddRoute(wasm.ModuleName, wasmStack). AddRoute(icacontrollertypes.SubModuleName, icaControllerStack). - AddRoute(icahosttypes.SubModuleName, icaHostStack) + AddRoute(icahosttypes.SubModuleName, icaHostStack). + AddRoute(icqtypes.ModuleName, icqModule) app.IBCKeeper.SetRouter(ibcRouter) /**** Module Options ****/ @@ -735,12 +832,14 @@ func NewTerpApp( groupmodule.NewAppModule(appCodec, app.GroupKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry), nftmodule.NewAppModule(appCodec, app.NFTKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry), consensus.NewAppModule(appCodec, app.ConsensusParamsKeeper), - tokenfactory.NewAppModule(app.TokenFactoryKeeper, app.AccountKeeper, app.BankKeeper), wasm.NewAppModule(appCodec, &app.WasmKeeper, app.StakingKeeper, app.AccountKeeper, app.BankKeeper, app.MsgServiceRouter(), app.GetSubspace(wasmtypes.ModuleName)), ibc.NewAppModule(app.IBCKeeper), transfer.NewAppModule(app.TransferKeeper), ibcfee.NewAppModule(app.IBCFeeKeeper), ica.NewAppModule(&app.ICAControllerKeeper, &app.ICAHostKeeper), + icq.NewAppModule(app.ICQKeeper), + packetforward.NewAppModule(app.PacketForwardKeeper), + ibchooks.NewAppModule(app.AccountKeeper), crisis.NewAppModule(app.CrisisKeeper, skipGenesisInvariants, app.GetSubspace(crisistypes.ModuleName)), // always be last to make sure that it checks for all invariants and not only part of them ) @@ -760,7 +859,9 @@ func NewTerpApp( ibcexported.ModuleName, icatypes.ModuleName, ibcfeetypes.ModuleName, - tokenfactorytypes.ModuleName, + icqtypes.ModuleName, + packetforwardtypes.ModuleName, + ibchookstypes.ModuleName, wasm.ModuleName, ) @@ -776,7 +877,9 @@ func NewTerpApp( ibcexported.ModuleName, icatypes.ModuleName, ibcfeetypes.ModuleName, - tokenfactorytypes.ModuleName, + icqtypes.ModuleName, + packetforwardtypes.ModuleName, + ibchookstypes.ModuleName, wasm.ModuleName, ) @@ -799,8 +902,10 @@ func NewTerpApp( ibcexported.ModuleName, icatypes.ModuleName, ibcfeetypes.ModuleName, + icqtypes.ModuleName, + packetforwardtypes.ModuleName, + ibchookstypes.ModuleName, // wasm after ibc transfer - tokenfactorytypes.ModuleName, wasm.ModuleName, } app.ModuleManager.SetOrderInitGenesis(genesisModuleOrder...) @@ -868,6 +973,10 @@ func NewTerpApp( app.ScopedICAHostKeeper = scopedICAHostKeeper app.ScopedICAControllerKeeper = scopedICAControllerKeeper + // set the contract keeper for the Ics20WasmHooks + app.ContractKeeper = wasmkeeper.NewDefaultPermissionKeeper(app.WasmKeeper) + app.Ics20WasmHooks.ContractKeeper = app.ContractKeeper + // 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. @@ -1133,9 +1242,10 @@ func initParamsKeeper(appCodec codec.BinaryCodec, legacyAmino *codec.LegacyAmino paramsKeeper.Subspace(crisistypes.ModuleName) paramsKeeper.Subspace(ibctransfertypes.ModuleName) paramsKeeper.Subspace(ibcexported.ModuleName) - paramsKeeper.Subspace(tokenfactorytypes.ModuleName) paramsKeeper.Subspace(icahosttypes.SubModuleName) paramsKeeper.Subspace(icacontrollertypes.SubModuleName) + paramsKeeper.Subspace(icqtypes.ModuleName) + paramsKeeper.Subspace(packetforwardtypes.ModuleName) paramsKeeper.Subspace(wasm.ModuleName) return paramsKeeper diff --git a/app/app_test.go b/app/app_test.go index f7f4ba3..5a245cb 100644 --- a/app/app_test.go +++ b/app/app_test.go @@ -11,7 +11,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/terpnetwork/terp-core/x/wasm" + "github.com/CosmWasm/wasmd/x/wasm" ) var emptyWasmOpts []wasm.Option diff --git a/app/apptesting/test_suite.go b/app/apptesting/test_suite.go index 6974e77..26fc4d8 100644 --- a/app/apptesting/test_suite.go +++ b/app/apptesting/test_suite.go @@ -28,12 +28,11 @@ import ( "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" + authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" - "github.com/terpnetwork/terp-core/app" + "github.com/terpnetwork/terp-core/v2/app" ) type KeeperTestHelper struct { diff --git a/app/encoding.go b/app/encoding.go index b9c0d93..8ebe3ed 100644 --- a/app/encoding.go +++ b/app/encoding.go @@ -3,7 +3,7 @@ package app import ( "github.com/cosmos/cosmos-sdk/std" - "github.com/terpnetwork/terp-core/app/params" + "github.com/terpnetwork/terp-core/v2/app/params" ) // MakeEncodingConfig creates a new EncodingConfig with all modules registered diff --git a/app/openapiconsole/console.go b/app/openapiconsole/console.go new file mode 100644 index 0000000..465f5bb --- /dev/null +++ b/app/openapiconsole/console.go @@ -0,0 +1,25 @@ +package openapiconsole + +import ( + "embed" + "html/template" + "net/http" +) + +//go:embed index.tpl +var index embed.FS + +// Handler returns an http handler that servers OpenAPI console for an OpenAPI spec at specURL. +func Handler(title, specURL string) http.HandlerFunc { + t, _ := template.ParseFS(index, "index.tpl") + + return func(w http.ResponseWriter, req *http.Request) { + t.Execute(w, struct { //nolint:errcheck + Title string + URL string + }{ + title, + specURL, + }) + } +} diff --git a/app/openapiconsole/index.tpl b/app/openapiconsole/index.tpl new file mode 100644 index 0000000..d88cd5b --- /dev/null +++ b/app/openapiconsole/index.tpl @@ -0,0 +1,25 @@ + + + + + {{ .Title }} + + + + +
+ + + + + \ No newline at end of file diff --git a/app/params/const.go b/app/params/const.go new file mode 100644 index 0000000..519cbd8 --- /dev/null +++ b/app/params/const.go @@ -0,0 +1,22 @@ +package params + +const ( + // Name defines the application name of Terp network. + Name = "terp" + + // BondDenom defines the native staking token denomination. + BondDenom = "uterp" + + // DisplayBondDenom defines the name, symbol, and display value of the Terp token. + DisplayBondDenom = "TERP" + + // BondDenom defines the native gas token denomination. + GasDenom = "uthiol" + + // DisplayGasDenom defines the name, symbol, and display value of the Thiol token. + DisplayGasDenom = "THIOL" + + // DefaultGasLimit - set to the same value as cosmos-sdk flags.DefaultGasLimit + // this value is currently only used in tests. + DefaultGasLimit = 200000 +) diff --git a/app/querier.go b/app/querier.go new file mode 100644 index 0000000..b1c37d7 --- /dev/null +++ b/app/querier.go @@ -0,0 +1,26 @@ +// this file used from osmosis +// Original Author: https://github.com/nicolaslara + +package app + +import ( + abci "github.com/cometbft/cometbft/abci/types" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// QuerierWrapper is a local wrapper around BaseApp that exports only the Queryable interface. +// This is used to pass the baseApp to Async ICQ without exposing all methods +type QuerierWrapper struct { + querier sdk.Queryable +} + +var _ sdk.Queryable = QuerierWrapper{} + +func NewQuerierWrapper(querier sdk.Queryable) QuerierWrapper { + return QuerierWrapper{querier: querier} +} + +func (q QuerierWrapper) Query(req abci.RequestQuery) abci.ResponseQuery { + return q.querier.Query(req) +} diff --git a/app/sim_test.go b/app/sim_test.go index 9e84c78..239fd45 100644 --- a/app/sim_test.go +++ b/app/sim_test.go @@ -36,7 +36,7 @@ import ( stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/stretchr/testify/require" - "github.com/terpnetwork/terp-core/x/wasm" + "github.com/CosmWasm/wasmd/x/wasm" ) // SimAppChainID hardcoded chainID for simulation diff --git a/app/test_helpers.go b/app/test_helpers.go index a448d6d..c746b23 100644 --- a/app/test_helpers.go +++ b/app/test_helpers.go @@ -42,8 +42,8 @@ import ( stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/stretchr/testify/require" - "github.com/terpnetwork/terp-core/x/wasm" - wasmtypes "github.com/terpnetwork/terp-core/x/wasm/types" + "github.com/CosmWasm/wasmd/x/wasm" + wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" ) // SetupOptions defines arguments that are passed into `TerpApp` constructor. diff --git a/app/upgrades.go b/app/upgrades.go index 6cf7fa0..a462071 100644 --- a/app/upgrades.go +++ b/app/upgrades.go @@ -21,7 +21,7 @@ import ( 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" + wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" ) // UpgradeName defines the on-chain upgrade name for the sample SimApp upgrade diff --git a/app/upgrades/types.go b/app/upgrades/types.go new file mode 100644 index 0000000..3e1736b --- /dev/null +++ b/app/upgrades/types.go @@ -0,0 +1,47 @@ +package upgrades + +import ( + "strings" + + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/terpnetwork/terp-core/v2/app" + + 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" +) + +// 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) *tmproto.ConsensusParams + StoreConsensusParams(ctx sdk.Context, cp *tmproto.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, + *app.TerpApp, + ) upgradetypes.UpgradeHandler + + // Store upgrades, should be used for any new modules introduced, new modules deleted, or store names renamed. + StoreUpgrades store.StoreUpgrades +} + +// Returns "uterpx" if the chain is 90u-, else returns the standard uterp token denom. +func GetChainsDenomToken(chainID string) string { + if strings.HasPrefix(chainID, "90u-") { + return "uterpx" + } + return "uterp" +} diff --git a/app/upgrades/v2/constants.go b/app/upgrades/v2/constants.go new file mode 100644 index 0000000..4fffb01 --- /dev/null +++ b/app/upgrades/v2/constants.go @@ -0,0 +1,22 @@ +package v2 + +import ( + store "github.com/cosmos/cosmos-sdk/store/types" + packetforwardtypes "github.com/strangelove-ventures/packet-forward-middleware/v7/router/types" + "github.com/terpnetwork/terp-core/v2/app/upgrades" + ibchookstypes "github.com/terpnetwork/terp-core/v2/x/ibchooks/types" +) + +// UpgradeName defines the on-chain upgrade name for the upgrade. +const UpgradeName = "v2" + +var Upgrade = upgrades.Upgrade{ + UpgradeName: UpgradeName, + CreateUpgradeHandler: CreateV2UpgradeHandler, + StoreUpgrades: store.StoreUpgrades{ + Added: []string{ + ibchookstypes.StoreKey, + packetforwardtypes.StoreKey, + }, + }, +} diff --git a/app/upgrades/v2/upgrades.go b/app/upgrades/v2/upgrades.go new file mode 100644 index 0000000..3440eca --- /dev/null +++ b/app/upgrades/v2/upgrades.go @@ -0,0 +1,40 @@ +package v2 + +import ( + "fmt" + + packetforwardtypes "github.com/strangelove-ventures/packet-forward-middleware/v7/router/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/terpnetwork/terp-core/v2/app" + "github.com/terpnetwork/terp-core/v2/app/upgrades" +) + +func CreateV2UpgradeHandler( + mm *module.Manager, + cfg module.Configurator, + keepers *app.TerpApp, +) upgradetypes.UpgradeHandler { + + return func(ctx sdk.Context, _ upgradetypes.Plan, vm module.VersionMap) (module.VersionMap, error) { + // transfer module consensus version has been bumped to 2 + // the above is https://github.com/cosmos/ibc-go/blob/v5.1.0/docs/migrations/v3-to-v4.md + logger := ctx.Logger().With("upgrade", UpgradeName) + + nativeDenom := upgrades.GetChainsDenomToken(ctx.ChainID()) + logger.Info(fmt.Sprintf("With native denom %s", nativeDenom)) + + // Run migrations + versionMap, err := mm.RunMigrations(ctx, cfg, vm) + + // New modules run AFTER the migrations, so to set the correct params after the default. + + // Packet Forward middleware initial params + keepers.PacketForwardKeeper.SetParams(ctx, packetforwardtypes.DefaultParams()) + + return versionMap, err + } + +} diff --git a/app/wasm.go b/app/wasm.go new file mode 100644 index 0000000..a01074f --- /dev/null +++ b/app/wasm.go @@ -0,0 +1,14 @@ +package app + +// AllCapabilities returns all capabilities available with the current wasmvm +// See https://github.com/CosmWasm/cosmwasm/blob/main/docs/CAPABILITIES-BUILT-IN.md +// This functionality is going to be moved upstream: https://github.com/CosmWasm/wasmvm/issues/425 +func AllCapabilities() []string { + return []string{ + "iterator", + "staking", + "stargate", + "cosmwasm_1_1", + "cosmwasm_1_2", + } +} diff --git a/chains.yaml b/chains.yaml new file mode 100644 index 0000000..22d3aab --- /dev/null +++ b/chains.yaml @@ -0,0 +1,11 @@ +# This file is used to create docker images using the heighliner binary. +# see: https://github.com/strangelove-ventures/heighliner + +- name: terpnetwork + dockerfile: cosmos + build-target: make install + binaries: + - /go/bin/terpd + build-env: + - LEDGER_ENABLED=false + - BUILD_TAGS=muslc \ No newline at end of file diff --git a/cmd/terpd/cmd/balances_from_state_export.go b/cmd/terpd/cmd/balances_from_state_export.go new file mode 100644 index 0000000..2033484 --- /dev/null +++ b/cmd/terpd/cmd/balances_from_state_export.go @@ -0,0 +1,272 @@ +package cmd + +// modified from osmosis + +import ( + "encoding/csv" + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + + "github.com/spf13/cobra" + + tmjson "github.com/cometbft/cometbft/libs/json" + tmtypes "github.com/cometbft/cometbft/types" + + "cosmossdk.io/math" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/server" + sdk "github.com/cosmos/cosmos-sdk/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + + appparams "github.com/terpnetwork/terp-core/v2/app/params" +) + +const ( + FlagMinimumStakeAmount = "minimum-stake-amount" +) + +type DeriveSnapshot struct { + NumberAccounts uint64 `json:"num_accounts"` + Accounts map[string]DerivedAccount `json:"accounts"` +} + +// DerivedAccount provide fields of snapshot per account +// It is the simplified struct we are presenting in this 'balances from state export' snapshot for people. +type DerivedAccount struct { + Address string `json:"address"` + LiquidBalances sdk.Coins `json:"liquid_balance"` + Staked math.Int `json:"staked"` + UnbondingStake math.Int `json:"unbonding_stake"` + Bonded sdk.Coins `json:"bonded"` + TotalBalances sdk.Coins `json:"total_balances"` +} + +// newDerivedAccount returns a new derived account. +func newDerivedAccount(address string) DerivedAccount { + return DerivedAccount{ + Address: address, + LiquidBalances: sdk.Coins{}, + Staked: sdk.ZeroInt(), + UnbondingStake: sdk.ZeroInt(), + Bonded: sdk.Coins{}, + } +} + +// getGenStateFromPath returns a JSON genState message from inputted path. +func getGenStateFromPath(genesisFilePath string) (map[string]json.RawMessage, error) { + genState := make(map[string]json.RawMessage) + + genesisFile, err := os.Open(filepath.Clean(genesisFilePath)) + if err != nil { + return genState, err + } + defer genesisFile.Close() + + byteValue, _ := io.ReadAll(genesisFile) + + var doc tmtypes.GenesisDoc + err = tmjson.Unmarshal(byteValue, &doc) + if err != nil { + return genState, err + } + + err = json.Unmarshal(doc.AppState, &genState) + if err != nil { + panic(err) + } + return genState, nil +} + +// ExportAirdropSnapshotCmd generates a snapshot.json from a provided exported genesis.json. +func ExportDeriveBalancesCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "export-derive-balances [input-genesis-file] [output-snapshot-json]", + Short: "Export a derive balances from a provided genesis export", + Long: `Export a derive balances from a provided genesis export +Example: + terpd export-derive-balances ../genesis.json ../snapshot.json +`, + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + serverCtx := server.GetServerContextFromCmd(cmd) + config := serverCtx.Config + config.SetRoot(clientCtx.HomeDir) + + genesisFile := args[0] + genState, err := getGenStateFromPath(genesisFile) + if err != nil { + return err + } + snapshotOutput := args[1] + + // Produce the map of address to total terp balance, both staked and UnbondingStake + snapshotAccs := make(map[string]DerivedAccount) + + bankGenesis := banktypes.GenesisState{} + if len(genState["bank"]) > 0 { + clientCtx.Codec.MustUnmarshalJSON(genState["bank"], &bankGenesis) + } + for _, balance := range bankGenesis.Balances { + address := balance.Address + acc, ok := snapshotAccs[address] + if !ok { + acc = newDerivedAccount(address) + } + + acc.LiquidBalances = balance.Coins + snapshotAccs[address] = acc + } + + stakingGenesis := stakingtypes.GenesisState{} + if len(genState["staking"]) > 0 { + clientCtx.Codec.MustUnmarshalJSON(genState["staking"], &stakingGenesis) + } + for _, unbonding := range stakingGenesis.UnbondingDelegations { + address := unbonding.DelegatorAddress + acc, ok := snapshotAccs[address] + if !ok { + acc = newDerivedAccount(address) + } + + unbondingTerps := sdk.NewInt(0) + for _, entry := range unbonding.Entries { + unbondingTerps = unbondingTerps.Add(entry.Balance) + } + + acc.UnbondingStake = acc.UnbondingStake.Add(unbondingTerps) + + snapshotAccs[address] = acc + } + + // Make a map from validator operator address to the v036 validator type + validators := make(map[string]stakingtypes.Validator) + for _, validator := range stakingGenesis.Validators { + validators[validator.OperatorAddress] = validator + } + + for _, delegation := range stakingGenesis.Delegations { + address := delegation.DelegatorAddress + + acc, ok := snapshotAccs[address] + if !ok { + acc = newDerivedAccount(address) + } + + val := validators[delegation.ValidatorAddress] + stakedTerps := delegation.Shares.MulInt(val.Tokens).Quo(val.DelegatorShares).RoundInt() + + acc.Staked = acc.Staked.Add(stakedTerps) + + snapshotAccs[address] = acc + } + + // convert balances to underlying coins and sum up balances to total balance + for addr, account := range snapshotAccs { + // account.LiquidBalances = underlyingCoins(account.LiquidBalances) + // account.Bonded = underlyingCoins(account.Bonded) + account.TotalBalances = sdk.NewCoins(). + Add(account.LiquidBalances...). + Add(sdk.NewCoin(appparams.BondDenom, account.Staked)). + Add(sdk.NewCoin(appparams.BondDenom, account.UnbondingStake)). + Add(account.Bonded...) + snapshotAccs[addr] = account + } + + snapshot := DeriveSnapshot{ + NumberAccounts: uint64(len(snapshotAccs)), + Accounts: snapshotAccs, + } + + fmt.Printf("# accounts: %d\n", len(snapshotAccs)) + + // export snapshot json + snapshotJSON, err := json.MarshalIndent(snapshot, "", " ") + if err != nil { + return fmt.Errorf("failed to marshal snapshot: %w", err) + } + + err = os.WriteFile(snapshotOutput, snapshotJSON, 0o600) + return err + }, + } + + return cmd +} + +// StakedToCSVCmd generates a airdrop.csv from a provided exported balances.json. +func StakedToCSVCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "staked-to-csv [input-balances-file] [output-airdrop-csv]", + Short: "Export a airdrop csv from a provided balances export", + Long: `Export a airdrop csv from a provided balances export (from export-derive-balances) +Example: + terpd staked-to-csv ../balances.json ../airdrop.csv +`, + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + serverCtx := server.GetServerContextFromCmd(cmd) + config := serverCtx.Config + config.SetRoot(clientCtx.HomeDir) + + balancesFile := args[0] + + snapshotOutput := args[1] + + minStakeAmount, _ := cmd.Flags().GetInt64(FlagMinimumStakeAmount) + + var deriveSnapshot DeriveSnapshot + + sourceFile, err := os.Open(balancesFile) + if err != nil { + return err + } + // remember to close the file at the end of the function + defer sourceFile.Close() + + // decode the balances json file into the struct array + if err := json.NewDecoder(sourceFile).Decode(&deriveSnapshot); err != nil { + return err + } + + // create a new file to store CSV data + outputFile, err := os.Create(snapshotOutput) + if err != nil { + return err + } + defer outputFile.Close() + + // write the header of the CSV file + writer := csv.NewWriter(outputFile) + defer writer.Flush() + + header := []string{"address", "staked"} + if err := writer.Write(header); err != nil { + return err + } + + // iterate through all accounts, leave out accounts that do not meet the user provided min stake amount + for _, r := range deriveSnapshot.Accounts { + var csvRow []string + if r.Staked.GT(sdk.NewInt(minStakeAmount)) { + csvRow = append(csvRow, r.Address, r.Staked.String()) + if err := writer.Write(csvRow); err != nil { + return err + } + } + } + + return nil + }, + } + + cmd.Flags().Int64(FlagMinimumStakeAmount, 0, "Specify minimum amount (non inclusive) accounts must stake to be included in airdrop (default: 0)") + + return cmd +} diff --git a/cmd/terpd/cmd/config.go b/cmd/terpd/cmd/config.go new file mode 100644 index 0000000..34e5f86 --- /dev/null +++ b/cmd/terpd/cmd/config.go @@ -0,0 +1,235 @@ +package cmd + +import ( + "bytes" + "encoding/json" + "fmt" + "os" + "path/filepath" + "text/template" + + "github.com/spf13/cobra" + viper "github.com/spf13/viper" + + tmcli "github.com/cometbft/cometbft/libs/cli" + + "github.com/cosmos/cosmos-sdk/client" + scconfig "github.com/cosmos/cosmos-sdk/client/config" + "github.com/cosmos/cosmos-sdk/client/flags" +) + +type TerpCustomClient struct { + scconfig.ClientConfig + Gas string `mapstructure:"gas" json:"gas"` + GasPrices string `mapstructure:"gas-prices" json:"gas-prices"` + GasAdjustment string `mapstructure:"gas-adjustment" json:"gas-adjustment"` + + Fees string `mapstructure:"fees" json:"fees"` + FeeGranter string `mapstructure:"fee-granter" json:"fee-granter"` + FeePayer string `mapstructure:"fee-payer" json:"fee-payer"` + + Note string `mapstructure:"note" json:"note"` +} + +// ConfigCmd returns a CLI command to interactively create an application CLI +// config file. +func ConfigCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "config [value]", + Short: "Create or query an application CLI configuration file", + RunE: runConfigCmd, + Args: cobra.RangeArgs(0, 2), + } + return cmd +} + +func runConfigCmd(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + configPath := filepath.Join(clientCtx.HomeDir, "config") + + conf, err := getClientConfig(configPath, clientCtx.Viper) + if err != nil { + return fmt.Errorf("couldn't get client config: %v", err) + } + + tcc := TerpCustomClient{ + *conf, + os.Getenv("TERPD_GAS"), + os.Getenv("TERPD_GAS_PRICES"), + os.Getenv("TERPD_GAS_ADJUSTMENT"), + + os.Getenv("TERPD_FEES"), + os.Getenv("TERPD_FEE_GRANTER"), + os.Getenv("TERPD_FEE_PAYER"), + + os.Getenv("TERPD_NOTE"), + } + + switch len(args) { + case 0: + s, err := json.MarshalIndent(tcc, "", "\t") + if err != nil { + return err + } + + cmd.Println(string(s)) + + case 1: + // it's a get + key := args[0] + + switch key { + case flags.FlagChainID: + cmd.Println(conf.ChainID) + case flags.FlagKeyringBackend: + cmd.Println(conf.KeyringBackend) + case tmcli.OutputFlag: + cmd.Println(conf.Output) + case flags.FlagNode: + cmd.Println(conf.Node) + case flags.FlagBroadcastMode: + cmd.Println(conf.BroadcastMode) + + // Custom flags + case flags.FlagGas: + cmd.Println(tcc.Gas) + case flags.FlagGasPrices: + cmd.Println(tcc.GasPrices) + case flags.FlagGasAdjustment: + cmd.Println(tcc.GasAdjustment) + case flags.FlagFees: + cmd.Println(tcc.Fees) + case flags.FlagFeeGranter: + cmd.Println(tcc.FeeGranter) + case flags.FlagFeePayer: + cmd.Println(tcc.FeePayer) + case flags.FlagNote: + cmd.Println(tcc.Note) + default: + err := errUnknownConfigKey(key) + return fmt.Errorf("couldn't get the value for the key: %v, error: %v", key, err) + } + + case 2: + // it's set + key, value := args[0], args[1] + + switch key { + case flags.FlagChainID: + tcc.ChainID = value + case flags.FlagKeyringBackend: + tcc.KeyringBackend = value + case tmcli.OutputFlag: + tcc.Output = value + case flags.FlagNode: + tcc.Node = value + case flags.FlagBroadcastMode: + tcc.BroadcastMode = value + case flags.FlagGas: + tcc.Gas = value + case flags.FlagGasPrices: + tcc.GasPrices = value + tcc.Fees = "" // resets since we can only use 1 at a time + case flags.FlagGasAdjustment: + tcc.GasAdjustment = value + case flags.FlagFees: + tcc.Fees = value + tcc.GasPrices = "" // resets since we can only use 1 at a time + case flags.FlagFeeGranter: + tcc.FeeGranter = value + case flags.FlagFeePayer: + tcc.FeePayer = value + case flags.FlagNote: + tcc.Note = value + default: + return errUnknownConfigKey(key) + } + + confFile := filepath.Join(configPath, "client.toml") + if err := writeConfigToFile(confFile, &tcc); err != nil { + return fmt.Errorf("could not write client config to the file: %v", err) + } + + default: + panic("cound not execute config command") + } + + return nil +} + +const defaultConfigTemplate = `# This is a TOML config file. +# For more information, see https://github.com/toml-lang/toml + +############################################################################### +### Client Configuration ### +############################################################################### + +# The network chain ID +chain-id = "{{ .ChainID }}" +# The keyring's backend, where the keys are stored (os|file|kwallet|pass|test|memory) +keyring-backend = "{{ .KeyringBackend }}" +# CLI output format (text|json) +output = "{{ .Output }}" +# : to Tendermint RPC interface for this chain +node = "{{ .Node }}" +# Transaction broadcasting mode (sync|async|block) +broadcast-mode = "{{ .BroadcastMode }}" + +############################################################################### +### Terp Tx Configuration ### +############################################################################### + +# Amount of gas per transaction +gas = "{{ .Gas }}" +# Price per unit of gas (ex: 0.005uthiol) +gas-prices = "{{ .GasPrices }}" +gas-adjustment = "{{ .GasAdjustment }}" + +# Fees to use instead of set gas prices +fees = "{{ .Fees }}" +fee-granter = "{{ .FeeGranter }}" +fee-payer = "{{ .FeePayer }}" + +# Memo to include in your Transactions +note = "{{ .Note }}" +` + +// writeConfigToFile parses defaultConfigTemplate, renders config using the template and writes it to +// configFilePath. +func writeConfigToFile(configFilePath string, config *TerpCustomClient) error { + var buffer bytes.Buffer + + tmpl := template.New("clientConfigFileTemplate") + configTemplate, err := tmpl.Parse(defaultConfigTemplate) + if err != nil { + return err + } + + if err := configTemplate.Execute(&buffer, config); err != nil { + return err + } + + return os.WriteFile(configFilePath, buffer.Bytes(), 0o600) +} + +// getClientConfig reads values from client.toml file and unmarshalls them into ClientConfig +func getClientConfig(configPath string, v *viper.Viper) (*scconfig.ClientConfig, error) { + v.AddConfigPath(configPath) + v.SetConfigName("client") + v.SetConfigType("toml") + + if err := v.ReadInConfig(); err != nil { + return nil, err + } + + conf := new(scconfig.ClientConfig) + if err := v.Unmarshal(conf); err != nil { + return nil, err + } + + return conf, nil +} + +func errUnknownConfigKey(key string) error { + return fmt.Errorf("unknown configuration key: %q", key) +} diff --git a/cmd/terpd/cmd/debug.go b/cmd/terpd/cmd/debug.go new file mode 100644 index 0000000..71cc578 --- /dev/null +++ b/cmd/terpd/cmd/debug.go @@ -0,0 +1,175 @@ +package cmd + +import ( + "encoding/hex" + "fmt" + "strconv" + "strings" + + "github.com/spf13/cobra" + + "github.com/cosmos/cosmos-sdk/client" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/bech32" + "github.com/cosmos/cosmos-sdk/version" +) + +// Cmd creates a main CLI command +func DebugCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "debug", + Short: "Tool for helping with debugging your application", + RunE: client.ValidateCmd, + } + + cmd.AddCommand( + PubkeyCmd(), + AddrCmd(), + RawBytesCmd(), + ConvertBech32Cmd(), + ExportDeriveBalancesCmd(), + StakedToCSVCmd(), + ) + + return cmd +} + +var flagBech32Prefix = "prefix" + +// get cmd to convert any bech32 address to a terp prefix. +func ConvertBech32Cmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "bech32-convert [bech32 string]", + Short: "Convert any bech32 string to the terp prefix", + Long: `Convert any bech32 string to the terp prefix +Especially useful for converting cosmos addresses to terp addresses +Example: + terpd bech32-convert terp1ey69r37gfxvxg62sh4r0ktpuc46pzjrm9qvyl8 -p osmo + `, + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + bech32prefix, err := cmd.Flags().GetString(flagBech32Prefix) + if err != nil { + return err + } + + _, bz, err := bech32.DecodeAndConvert(args[0]) + if err != nil { + return err + } + + bech32Addr, err := bech32.ConvertAndEncode(bech32prefix, bz) + if err != nil { + panic(err) + } + + cmd.Println(bech32Addr) + + return nil + }, + } + + cmd.Flags().StringP(flagBech32Prefix, "p", "terp", "Bech32 Prefix to encode to") + + return cmd +} + +// getPubKeyFromString decodes SDK PubKey using JSON marshaler. +func getPubKeyFromString(ctx client.Context, pkstr string) (cryptotypes.PubKey, error) { + var pk cryptotypes.PubKey + err := ctx.Codec.UnmarshalInterfaceJSON([]byte(pkstr), &pk) + return pk, err +} + +func PubkeyCmd() *cobra.Command { + return &cobra.Command{ + Use: "pubkey [pubkey]", + Short: "Decode a pubkey from proto JSON", + Long: fmt.Sprintf(`Decode a pubkey from proto JSON and display it's address. + +Example: +$ %s debug pubkey '{"@type":"/cosmos.crypto.secp256k1.PubKey","key":"AurroA7jvfPd1AadmmOvWM2rJSwipXfRf8yD6pLbA2DJ"}' + `, version.AppName), + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + pk, err := getPubKeyFromString(clientCtx, args[0]) + if err != nil { + return err + } + cmd.Println("Address:", pk.Address()) + cmd.Println("PubKey Hex:", hex.EncodeToString(pk.Bytes())) + return nil + }, + } +} + +func AddrCmd() *cobra.Command { + return &cobra.Command{ + Use: "addr [address]", + Short: "Convert an address between hex and bech32", + Long: fmt.Sprintf(`Convert an address between hex encoding and bech32. + +Example: +$ %s debug addr cosmos1e0jnq2sun3dzjh8p2xq95kk0expwmd7shwjpfg + `, version.AppName), + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + addrString := args[0] + var addr []byte + + // try hex, then bech32 + var err error + addr, err = hex.DecodeString(addrString) + if err != nil { + var err2 error + addr, err2 = sdk.AccAddressFromBech32(addrString) + if err2 != nil { + var err3 error + addr, err3 = sdk.ValAddressFromBech32(addrString) + + if err3 != nil { + return fmt.Errorf("expected hex or bech32. Got errors: hex: %v, bech32 acc: %v, bech32 val: %v", err, err2, err3) + } + } + } + + cmd.Println("Address:", addr) + cmd.Printf("Address (hex): %X\n", addr) + cmd.Printf("Bech32 Acc: %s\n", sdk.AccAddress(addr)) + cmd.Printf("Bech32 Val: %s\n", sdk.ValAddress(addr)) + return nil + }, + } +} + +func RawBytesCmd() *cobra.Command { + return &cobra.Command{ + Use: "raw-bytes [raw-bytes]", + Short: "Convert raw bytes output (eg. [10 21 13 255]) to hex", + Long: fmt.Sprintf(`Convert raw-bytes to hex. + +Example: +$ %s debug raw-bytes [72 101 108 108 111 44 32 112 108 97 121 103 114 111 117 110 100] + `, version.AppName), + Args: cobra.ExactArgs(1), + RunE: func(_ *cobra.Command, args []string) error { + stringBytes := args[0] + stringBytes = strings.Trim(stringBytes, "[") + stringBytes = strings.Trim(stringBytes, "]") + spl := strings.Split(stringBytes, " ") + + byteArray := []byte{} + for _, s := range spl { + b, err := strconv.ParseInt(s, 10, 8) + if err != nil { + return err + } + byteArray = append(byteArray, byte(b)) + } + fmt.Printf("%X\n", byteArray) + return nil + }, + } +} diff --git a/cmd/terpd/cmd/genica.go b/cmd/terpd/cmd/genica.go new file mode 100644 index 0000000..fe60220 --- /dev/null +++ b/cmd/terpd/cmd/genica.go @@ -0,0 +1,77 @@ +package cmd + +import ( + "encoding/json" + "fmt" + + "github.com/spf13/cobra" + + icacontrollertypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/controller/types" + icagenesistypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/genesis/types" + icahosttypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/host/types" + icatypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/types" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/server" + "github.com/cosmos/cosmos-sdk/x/genutil" + genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" +) + +// AddGenesisAccountCmd returns add-genesis-account cobra Command. +func AddGenesisIcaCmd(defaultNodeHome string) *cobra.Command { + cmd := &cobra.Command{ + Use: "add-ica-config", + Short: "Add ICA config to genesis.json", + Long: `Add default ICA configuration to genesis.json`, + Args: cobra.ExactArgs(0), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + serverCtx := server.GetServerContextFromCmd(cmd) + config := serverCtx.Config + + config.SetRoot(clientCtx.HomeDir) + + genFile := config.GenesisFile() + appState, genDoc, err := genutiltypes.GenesisStateFromGenFile(genFile) + if err != nil { + return fmt.Errorf("failed to unmarshal genesis state: %w", err) + } + + controllerGenesisState := icagenesistypes.DefaultControllerGenesis() + // no params set in upgrade handler, no params set here + controllerGenesisState.Params = icacontrollertypes.Params{} + + hostGenesisState := icagenesistypes.DefaultHostGenesis() + // add the messages we want (from old upgrade handler) + hostGenesisState.Params = icahosttypes.Params{ + HostEnabled: true, + AllowMessages: []string{"*"}, + } + + newIcaGenState := icagenesistypes.NewGenesisState(controllerGenesisState, hostGenesisState) + + icaGenStateBz, err := clientCtx.Codec.MarshalJSON(newIcaGenState) + if err != nil { + return fmt.Errorf("failed to marshal auth genesis state: %w", err) + } + + appState[icatypes.ModuleName] = icaGenStateBz + + appStateJSON, err := json.Marshal(appState) + if err != nil { + return fmt.Errorf("failed to marshal application genesis state: %w", err) + } + + genDoc.AppState = appStateJSON + return genutil.ExportGenesisFile(genDoc, genFile) + }, + } + + cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory") + cmd.Flags().String(flags.FlagKeyringBackend, flags.DefaultKeyringBackend, "Select keyring's backend (os|file|kwallet|pass|test)") + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} diff --git a/cmd/terpd/cmd/resets.go b/cmd/terpd/cmd/resets.go new file mode 100644 index 0000000..314f531 --- /dev/null +++ b/cmd/terpd/cmd/resets.go @@ -0,0 +1,94 @@ +package cmd + +import ( + "fmt" + "os" + "path/filepath" + + "github.com/spf13/cobra" + + tmos "github.com/cometbft/cometbft/libs/os" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/server" +) + +// Cmd creates a main CLI command +func ResetCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "reset", + Short: "Reset commands for different parts of application state", + RunE: client.ValidateCmd, + } + + cmd.AddCommand(ResetWasmCmd) + cmd.AddCommand(ResetAppCmd) + + return cmd +} + +// ResetWasmCmd removes the database of the specified Tendermint core instance. +var ResetWasmCmd = &cobra.Command{ + Use: "wasm", + Short: "Reset WASM files", + RunE: func(cmd *cobra.Command, args []string) (err error) { + clientCtx := client.GetClientContextFromCmd(cmd) + serverCtx := server.GetServerContextFromCmd(cmd) + config := serverCtx.Config + + config.SetRoot(clientCtx.HomeDir) + + return resetWasm(config.DBDir()) + }, +} + +// ResetAppCmd removes the database of the specified Tendermint core instance. +var ResetAppCmd = &cobra.Command{ + Use: "app", + Short: "Reset App files", + RunE: func(cmd *cobra.Command, args []string) (err error) { + clientCtx := client.GetClientContextFromCmd(cmd) + serverCtx := server.GetServerContextFromCmd(cmd) + config := serverCtx.Config + + config.SetRoot(clientCtx.HomeDir) + + return resetApp(config.DBDir()) + }, +} + +// resetWasm removes wasm files +func resetWasm(dbDir string) error { + wasmDir := filepath.Join(dbDir, "wasm") + + if tmos.FileExists(wasmDir) { + if err := os.RemoveAll(wasmDir); err == nil { + fmt.Println("Removed wasm", "dir", wasmDir) + } else { + return fmt.Errorf("error removing wasm dir: %s; err: %w", wasmDir, err) + } + } + + if err := tmos.EnsureDir(wasmDir, 0o700); err != nil { + return fmt.Errorf("unable to recreate wasm %w", err) + } + return nil +} + +// resetApp removes application.db files +func resetApp(dbDir string) error { + appDir := filepath.Join(dbDir, "application.db") + + if tmos.FileExists(appDir) { + if err := os.RemoveAll(appDir); err == nil { + fmt.Println("Removed application.db", "dir", appDir) + } else { + return fmt.Errorf("error removing application.db dir: %s; err: %w", appDir, err) + } + } + + if err := tmos.EnsureDir(appDir, 0o700); err != nil { + return fmt.Errorf("unable to recreate application.db %w", err) + } + return nil +} diff --git a/cmd/terpd/root.go b/cmd/terpd/cmd/root.go similarity index 77% rename from cmd/terpd/root.go rename to cmd/terpd/cmd/root.go index 28b88bb..3afc70f 100644 --- a/cmd/terpd/root.go +++ b/cmd/terpd/cmd/root.go @@ -1,17 +1,18 @@ -package main +package cmd import ( "errors" "io" "os" + "path/filepath" rosettaCmd "cosmossdk.io/tools/rosetta/cmd" dbm "github.com/cometbft/cometbft-db" tmcfg "github.com/cometbft/cometbft/config" + tmcli "github.com/cometbft/cometbft/libs/cli" "github.com/cometbft/cometbft/libs/log" "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" @@ -30,11 +31,11 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" - "github.com/terpnetwork/terp-core/app" - "github.com/terpnetwork/terp-core/app/params" - "github.com/terpnetwork/terp-core/x/wasm" - wasmkeeper "github.com/terpnetwork/terp-core/x/wasm/keeper" - wasmtypes "github.com/terpnetwork/terp-core/x/wasm/types" + "github.com/CosmWasm/wasmd/x/wasm" + wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" + wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" + "github.com/terpnetwork/terp-core/v2/app" + "github.com/terpnetwork/terp-core/v2/app/params" ) // NewRootCmd creates a new root command for terpd. It is called once in the @@ -56,12 +57,17 @@ func NewRootCmd() (*cobra.Command, params.EncodingConfig) { WithLegacyAmino(encodingConfig.Amino). WithInput(os.Stdin). WithAccountRetriever(authtypes.AccountRetriever{}). + WithBroadcastMode(flags.FlagBroadcastMode). WithHomeDir(app.DefaultNodeHome). WithViper("") // In terpd, we don't use any prefix for env variables. + // Allows you to add extra params to your client.toml + // gas, gas-price, gas-adjustment, fees, note, etc. + SetCustomEnvVariablesFromClientToml(initClientCtx) + rootCmd := &cobra.Command{ Use: version.AppName, - Short: "Terp Network Daemon (server)", + Short: "Terp Network Community Network", PersistentPreRunE: func(cmd *cobra.Command, _ []string) error { // set the default command outputs cmd.SetOut(cmd.OutOrStdout()) @@ -145,16 +151,62 @@ func initAppConfig() (string, interface{}) { return customAppTemplate, customAppConfig } +// Reads the custom extra values in the config.toml file if set. +// If they are, then use them. +func SetCustomEnvVariablesFromClientToml(ctx client.Context) { + configFilePath := filepath.Join(ctx.HomeDir, "config", "client.toml") + + if _, err := os.Stat(configFilePath); os.IsNotExist(err) { + return + } + + viper := ctx.Viper + viper.SetConfigFile(configFilePath) + + if err := viper.ReadInConfig(); err != nil { + panic(err) + } + + setEnvFromConfig := func(key string, envVar string) { + // if the user sets the env key manually, then we don't want to override it + if os.Getenv(envVar) != "" { + return + } + + // reads from the config file + val := viper.GetString(key) + if val != "" { + // Sets the env for this instance of the app only. + os.Setenv(envVar, val) + } + } + + // gas + setEnvFromConfig("gas", "TERPD_GAS") + setEnvFromConfig("gas-prices", "TERPD_GAS_PRICES") + setEnvFromConfig("gas-adjustment", "TERPD_GAS_ADJUSTMENT") + // fees + setEnvFromConfig("fees", "TERPD_FEES") + setEnvFromConfig("fee-account", "TERPD_FEE_ACCOUNT") + // memo + setEnvFromConfig("note", "TERPD_NOTE") +} + func initRootCmd(rootCmd *cobra.Command, encodingConfig params.EncodingConfig) { + ac := appCreator{ + encCfg: encodingConfig, + } + rootCmd.AddCommand( genutilcli.InitCmd(app.ModuleBasics, app.DefaultNodeHome), - // testnetCmd(app.ModuleBasics, banktypes.GenesisBalancesIterator{}), - debug.Cmd(), - config.Cmd(), - pruning.PruningCmd(newApp), + AddGenesisIcaCmd(app.DefaultNodeHome), + tmcli.NewCompletionCmd(rootCmd, true), + DebugCmd(), + ConfigCmd(), + pruning.PruningCmd(ac.newApp), ) - server.AddCommands(rootCmd, app.DefaultNodeHome, newApp, appExport, addModuleInitFlags) + server.AddCommands(rootCmd, app.DefaultNodeHome, ac.newApp, ac.appExport, addModuleInitFlags) // add keybase, auxiliary RPC, query, and tx child commands rootCmd.AddCommand( @@ -202,6 +254,7 @@ func queryCommand() *cobra.Command { ) app.ModuleBasics.AddQueryCommands(cmd) + cmd.PersistentFlags().String(flags.FlagChainID, "", "The network chain ID") return cmd } @@ -221,6 +274,7 @@ func txCommand() *cobra.Command { authcmd.GetMultiSignCommand(), authcmd.GetMultiSignBatchCmd(), authcmd.GetValidateSignaturesCommand(), + flags.LineBreak, authcmd.GetBroadcastCommand(), authcmd.GetEncodeCommand(), authcmd.GetDecodeCommand(), @@ -228,26 +282,41 @@ func txCommand() *cobra.Command { ) app.ModuleBasics.AddTxCommands(cmd) + cmd.PersistentFlags().String(flags.FlagChainID, "", "The network chain ID") return cmd } +type appCreator struct { + encCfg params.EncodingConfig +} + // newApp creates the application -func newApp( +func (ac appCreator) newApp( logger log.Logger, db dbm.DB, traceStore io.Writer, appOpts servertypes.AppOptions, ) servertypes.Application { - baseappOptions := server.DefaultBaseappOptions(appOpts) + skipUpgradeHeights := make(map[int64]bool) + for _, h := range cast.ToIntSlice(appOpts.Get(server.FlagUnsafeSkipUpgrades)) { + skipUpgradeHeights[int64(h)] = true + } var wasmOpts []wasm.Option if cast.ToBool(appOpts.Get("telemetry.enabled")) { wasmOpts = append(wasmOpts, wasmkeeper.WithVMCacheMetrics(prometheus.DefaultRegisterer)) } + loadLatest := true + + baseappOptions := server.DefaultBaseappOptions(appOpts) + return app.NewTerpApp( - logger, db, traceStore, true, + logger, + db, + traceStore, + loadLatest, app.GetEnabledProposals(), appOpts, wasmOpts, @@ -256,7 +325,7 @@ func newApp( } // appExport creates a new wasm app (optionally at a given height) and exports state. -func appExport( +func (ac appCreator) appExport( logger log.Logger, db dbm.DB, traceStore io.Writer, diff --git a/cmd/terpd/main.go b/cmd/terpd/main.go index 4ecbabd..846d63b 100644 --- a/cmd/terpd/main.go +++ b/cmd/terpd/main.go @@ -3,22 +3,20 @@ package main import ( "os" - "github.com/cosmos/cosmos-sdk/server" + "cosmossdk.io/log" + svrcmd "github.com/cosmos/cosmos-sdk/server/cmd" - "github.com/terpnetwork/terp-core/app" + "github.com/terpnetwork/terp-core/v2/app" + "github.com/terpnetwork/terp-core/v2/cmd/terpd/cmd" ) func main() { - rootCmd, _ := NewRootCmd() - - if err := svrcmd.Execute(rootCmd, "", app.DefaultNodeHome); err != nil { - switch e := err.(type) { - case server.ErrorCode: - os.Exit(e.Code) + app.SetAddressPrefixes() + rootCmd, _ := cmd.NewRootCmd() - default: - os.Exit(1) - } + if err := svrcmd.Execute(rootCmd, "TERPD", app.DefaultNodeHome); err != nil { + log.NewLogger(rootCmd.OutOrStderr()).Error("failure when running app", "err", err) + os.Exit(1) } } diff --git a/contrib/devtools/Dockerfile b/contrib/devtools/Dockerfile new file mode 100644 index 0000000..53592ff --- /dev/null +++ b/contrib/devtools/Dockerfile @@ -0,0 +1,36 @@ +## To test locally: +# docker build --pull --rm -f "contrib/devtools/Dockerfile" -t cosmossdk-proto:latest "contrib/devtools" +# docker run --rm -v $(pwd):/workspace --workdir /workspace cosmossdk-proto sh ./scripts/protocgen.sh + +FROM bufbuild/buf:1.9.0 as BUILDER +FROM golang:1.19-alpine + +RUN apk add --no-cache \ + nodejs \ + npm \ + git \ + make \ + clang-extra-tools + +RUN npm install -g swagger-combine + +ARG UNAME=protobuild +ARG UID=1000 +RUN adduser -u $UID -s /bin/sh $UNAME -D +USER $UNAME + +ENV GOLANG_PROTOBUF_VERSION=1.28.1 \ + GRPC_GATEWAY_VERSION=1.16.0 + +RUN go install github.com/cosmos/cosmos-proto/cmd/protoc-gen-go-pulsar@latest && \ + go install google.golang.org/protobuf/cmd/protoc-gen-go@v${GOLANG_PROTOBUF_VERSION} && \ + go install github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway@v${GRPC_GATEWAY_VERSION} \ + github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger@v${GRPC_GATEWAY_VERSION} + +# install all gogo protobuf binaries +RUN git clone https://github.com/cosmos/gogoproto.git; \ + cd gogoproto; \ + go mod download; \ + make install + +COPY --from=BUILDER /usr/local/bin /usr/local/bin \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..67c566e --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,17 @@ +--- +version: "3" +services: + node: + build: + context: . + args: + - arch=${ARCH:-x86_64} + command: ./setup_and_run.sh terp16g2rahf5846rxzp3fwlswy08fz8ccuwk7furnt + ports: + - 1317:1317 # rest + - 26656:26656 # p2p + - 26657:26657 # rpc + environment: + - GAS_LIMIT=${GAS_LIMIT:-10000000} + - STAKE_TOKEN=${STAKE_TOKEN:-uterpx} + - TIMEOUT_COMMIT=${TIMEOUT_COMMIT:-5s} diff --git a/docs/CODE_OF_CONDUCT.md b/docs/CODE_OF_CONDUCT.md deleted file mode 100644 index c0261e7..0000000 --- a/docs/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,46 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at hello@confio.gmbh. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] - -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ diff --git a/docs/CODING_GUIDELINES.md b/docs/CODING_GUIDELINES.md deleted file mode 100644 index eda2155..0000000 --- a/docs/CODING_GUIDELINES.md +++ /dev/null @@ -1,51 +0,0 @@ -# Coding Guidelines - -This document is an extension to [CONTRIBUTING](./CONTRIBUTING.md) and provides more details about the coding guidelines and requirements. - -## API & Design - -* Code must be well structured: - * packages must have a limited responsibility (different concerns can go to different packages), - * types must be easy to compose, - * think about maintainbility and testability. -* "Depend upon abstractions, [not] concretions". -* Try to limit the number of methods you are exposing. It's easier to expose something later than to hide it. -* Follow agreed-upon design patterns and naming conventions. -* publicly-exposed functions are named logically, have forward-thinking arguments and return types. -* Avoid global variables and global configurators. -* Favor composable and extensible designs. -* Minimize code duplication. -* Limit third-party dependencies. - -Performance: - -* Avoid unnecessary operations or memory allocations. - -Security: - -* Pay proper attention to exploits involving: - * gas usage - * transaction verification and signatures - * malleability - * code must be always deterministic -* Thread safety. If some functionality is not thread-safe, or uses something that is not thread-safe, then clearly indicate the risk on each level. - -## Best practices - -* Use [goimports](https://pkg.go.dev/golang.org/x/tools/cmd/goimports) as your code formatter. - -* Always wrap returned errors. - * Doing `if err != nil { return err }` does not include each callers' context. Pushing errors up the stack without context makes it harder to test and debug. Additionally, a short context description makes it easier for the reader to understand the code. Example: - - ```go - if !coins.IsZero() { - if err := k.bank.TransferCoins(ctx, caller, contractAddress, coins); err != nil { - return nil, err - } - } - ``` - - * It would be an improvement to return `return nil, sdkerror.Wrap(err, "lock contract coins")` - * Please notice that fmt.Errorf is not used, because the error handling predates fmt.Errorf and errors.Is - -* Limit the use of aliases, when not used during the refactoring process. \ No newline at end of file diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md deleted file mode 100644 index 05cb53b..0000000 --- a/docs/CONTRIBUTING.md +++ /dev/null @@ -1,110 +0,0 @@ -# Contributing - -Thank you for considering making contributions to Wasmd! - -Contributing to this repo can mean many things, such as participating in -discussion or proposing code changes. To ensure a smooth workflow for all -contributors, the general procedure for contributing has been established: - -1. Start by browsing [new issues](https://github.com/terpnetwork/terp-core/issues). - * Looking for a good place to start contributing? How about checking out some [good first issues](https://github.com/terpnetwork/terp-core/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) or [bugs](https://github.com/terpnetwork/terp-core/issues?q=is%3Aopen+is%3Aissue+label%3Abug)? -2. Determine whether a GitHub issue or discussion is more appropriate for your needs: - 1. If the issue you want addressed is a specific proposal or a bug, then open a [new issue](https://github.com/terpnetwork/terp-core/issues/new). - 2. Review existing [issues](https://github.com/terpnetwork/terp-core/issues) to find an issue you'd like to help with. -3. Participate in thoughtful discussion on that issue. -4. If you would like to contribute: - 1. Ensure that the proposal has been accepted. - 2. Ensure that nobody else has already begun working on this issue. If they have, - make sure to contact them to collaborate. - 3. If nobody has been assigned for the issue and you would like to work on it, - make a comment on the issue to inform the community of your intentions - to begin work. -5. To submit your work as a contribution to the repository follow standard GitHub best practices. See [pull request guideline](#pull-requests) below. - -**Note:** For very small or blatantly obvious problems such as typos, you are -not required to an open issue to submit a PR, but be aware that for more complex -problems/features, if a PR is opened before an adequate design discussion has -taken place in a GitHub issue, that PR runs a high likelihood of being rejected. - -## Development Procedure - -* The latest state of development is on `main`. -* `main` must never fail `make lint test test-race`. -* No `--force` onto `main` (except when reverting a broken commit, which should seldom happen). -* Create a branch to start work: - * Fork the repo (core developers must create a branch directly in the Wasmd repo), - branch from the HEAD of `main`, make some commits, and submit a PR to `main`. - * For core developers working within the `wasmd` repo, follow branch name conventions to ensure a clear - ownership of branches: `{issue#}-branch-name`. - * See [Branching Model](#branching-model-and-release) for more details. -* Be sure to run `make format` before every commit. The easiest way - to do this is have your editor run it for you upon saving a file (most of the editors - will do it anyway using a pre-configured setup of the programming language mode). -* Follow the [CODING GUIDELINES](CODING_GUIDELINES.md), which defines criteria for designing and coding a software. - -Code is merged into main through pull request procedure. - -### Testing - -Tests can be executed by running `make test` at the top level of the wasmd repository. - -### Pull Requests - -Before submitting a pull request: - -* merge the latest main `git merge origin/main`, -* run `make lint test` to ensure that all checks and tests pass. - -Then: - -1. If you have something to show, **start with a `Draft` PR**. It's good to have early validation of your work and we highly recommend this practice. A Draft PR also indicates to the community that the work is in progress. - Draft PRs also helps the core team provide early feedback and ensure the work is in the right direction. -2. When the code is complete, change your PR from `Draft` to `Ready for Review`. -3. Be sure to include a relevant changelog entry in the `Unreleased` section of `CHANGELOG.md` (see file for log format). The entry should be on top of all others changes in the section. - -PRs name should start upper case. -Additionally, each PR should only address a single issue. - -NOTE: when merging, GitHub will squash commits and rebase on top of the main. - -## Protobuf - -We use [Protocol Buffers](https://developers.google.com/protocol-buffers) along with [gogoproto](https://github.com/cosmos/gogoproto) to generate code for use in Wasmd. - -For deterministic behavior around Protobuf tooling, everything is containerized using Docker. Make sure to have Docker installed on your machine, or head to [Docker's website](https://docs.docker.com/get-docker/) to install it. - -For formatting code in `.proto` files, you can run `make proto-format` command. - -For linting we use [buf](https://buf.build/). You can use the commands `make proto-lint` to lint your proto files. - -To generate the protobuf stubs, you can run `make proto-gen`. - -We also added the `make proto-all` command to run all the above commands sequentially. - -In order for imports to properly compile in your IDE, you may need to manually set your protobuf path in your IDE's workspace settings/config. - -For example, in vscode your `.vscode/settings.json` should look like: - -```json -{ - "protoc": { - "options": [ - "--proto_path=${workspaceRoot}/proto", - ] - } -} -``` - -## Branching Model and Release - -User-facing repos should adhere to the trunk based development branching model: https://trunkbaseddevelopment.com. User branches should start with a user name, example: `{moniker}/{issue#}-branch-name`. - -Wasmd utilizes [semantic versioning](https://semver.org/). - -### PR Targeting - -Ensure that you base and target your PR on the `main` branch. - -All feature additions and all bug fixes must be targeted against `main`. Exception is for bug fixes which are only related to a released version. In that case, the related bug fix PRs must target against the release branch. - -If needed, we backport a commit from `main` to a release branch (excluding consensus breaking feature, API breaking and similar). \ No newline at end of file diff --git a/docs/EVENTS.md b/docs/EVENTS.md deleted file mode 100644 index 2407b3b..0000000 --- a/docs/EVENTS.md +++ /dev/null @@ -1,420 +0,0 @@ -# Event System - -## Usage in the SDK - -Events are an essential part of the Cosmos SDK. They are similar to "logs" in Ethereum and allow a blockchain -app to attach key-value pairs to a transaction that can later be used to search for it or extract some information -in human readable form. Events are not written to the application state, nor do they form part of the AppHash, -but mainly intended for client use (and become an essential API for any reactive app or app that searches for txs). - -In contrast, transactions also have a binary "data" field that is part of the AppHash (provable with light client proofs, -part of consensus). This data is not searchable, but given a tx hash, you can be guaranteed what the data returned is. -This is often empty, but sometimes custom protobuf formats to return essential information from an execution. - -Every message in the SDK may add events to the EventManager and these are then added to the final ABCI result that is returned -to Tendermint. Events are exposed in 3 different ways over the Tendermint API (which is the only way a client can query). -First of all is the `events` field on the transaction result (when you query a transaction by hash, you can see all event emitted -by it). Secondly is the `log` field on the same transaction result. And third is the query interface to search or subscribe for -transactions. - -The `log` field actually has the best data. It contains an array of array of events. The first array is one entry per incoming message. -Transactions in the Cosmos SDK may consist of multiple messages that are executed atomically. Maybe we send tokens, then issue a swap -on a DEX. Each action would return it's own list of Events and in the logs, these are separated. For each message, it maintains a list -of Events, exactly in the order returned by the application. This is JSON encoded and can be parsed by a client. In fact this is -how [CosmJS](https://github.com/cosmos/cosmjs) gets the events it shows to the client. - -In Tendermint 0.35, the `events` field will be one flattened list of events over all messages. Just as if we concatenated all -the per-message arrays contained in the `log` field. This fix was made as -[part of an event system refactoring](https://github.com/cometbft/cometbft/pull/6634). This refactoring is also giving us -[pluggable event indexing engines](https://github.com/cometbft/cometbft/pull/6411), so we can use eg. PostgreSQL to -store and query the events with more powerful indexes. - -However, currently (until Tendermint 0.34 used in Cosmos SDK 0.40-0.43), all events of one transaction are "flat-mapped" on type. -Meaning all events with type `wasm` get merged into one. This makes the API not very useful to understanding more complex events -currently. There are also a number of limitations of the power of queries in the search interface. - -Given the state of affairs, and given that we seek to provide a stable API for contracts looking into the future, we consider the -`log` output and the Tendermint 0.35 event handling to be the standard that clients should adhere to. And we will expose a similar -API to the smart contracts internally (all events from the message appended, unmerged). -### Data Format - -The event has a string type, and a list of attributes. Each of them being a key value pair. All of these maintain a -consistent order (and avoid dictionaries/hashes). Here is a simple Event in JSON: - -```json -{ - "type": "wasm", - "attributes": [ - {"key": "_contract_address", "value": "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6"}, - {"key": "transfered", "value": "777000"} - ] -} -``` - -And here is a sample log output for a transaction with one message, which emitted 2 events: - -```json -[ - [ - { - "type": "message", - "attributes": [ - {"key": "module", "value": "bank"}, - {"key": "action", "value": "send"} - ] - }, - { - "type": "transfer", - "attributes": [ - {"key": "recipient", "value": "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6"}, - {"key": "amount", "value": "777000uatom"} - ] - } - ] -] -``` - -### Default Events in the SDK - -There are two places events that are emitted in every transaction regardless of the module which is executed. -[The first is `{"type": "message"}`](https://github.com/cosmos/cosmos-sdk/blob/6888de1d86026c25197c1227dae3d7da4d41a441/baseapp/baseapp.go#L746-L748) -defining an `action` attribute. This is emitted for each top-level (user-signed) message, but the action names have changed between -0.42 and 0.43. - -The other place is in the [signature verification AnteHandler](https://github.com/cosmos/cosmos-sdk/blob/v0.42.9/x/auth/ante/sigverify.go#L103-L120), where it emits information on the account sequences and signatures on the transaction. - -These are all handled in BaseApp and the middleware *before* any module is called and thus not exposed to CosmWasm contracts at all. - -### Standard Events in the SDK - -The events that will actually make it to the contracts are the events that are emitted by the other modules / keepers. Let's look -at some good examples of what they look like: - -The most basic one is `bank`, which emits two events on every send, a [custom "transfer" event](https://github.com/cosmos/cosmos-sdk/blob/v0.42.9/x/bank/keeper/send.go#L142-L147) as well as "sender" information under the [standard "message" type](https://github.com/cosmos/cosmos-sdk/blob/v0.42.9/x/bank/keeper/send.go#L148-L151). Replacing variables with string literals, they look like this: - -```go -sdk.NewEvent( - "transfer" - sdk.NewAttribute("recipient", toAddr.String()), - sdk.NewAttribute("sender", fromAddr.String()), - sdk.NewAttribute("amount", amt.String()), // eg 12456uatom -), -sdk.NewEvent( - "message", - sdk.NewAttribute("sender", fromAddr.String()), -), -``` - -The delegation module seems a bit more refined, emitting a generic "message" type event in [`msg_server.go`](https://github.com/cosmos/cosmos-sdk/blob/v0.42.9/x/distribution/keeper/msg_server.go#L42-L46) including the module name, **before** -emitting some custom event types closer to the actual code logic in -[`keeper.go`](https://github.com/cosmos/cosmos-sdk/blob/v0.42.9/x/distribution/keeper/keeper.go#L74-L77). - -This looks something like: - -```go -sdk.NewEvent( - "message", - sdk.NewAttribute("module", "distribution"), - sdk.NewAttribute("sender", msg.DelegatorAddress), -), -sdk.NewEvent( - "set_withdraw_address", - sdk.NewAttribute("withdraw_address", withdrawAddr.String()), -), -``` - -## Usage in wasmd - -In `x/wasm` we also use Events system. On one hand, the Go implementation of `x/wasm` emits standard events for each -message it processes, using the `distribution` module as an example. Furthermore, it allows contracts to -emit custom events based on their execution state, so they can for example say "dex swap, BTC-ATOM, in 0.23, out 512" -which require internal knowledge of the contract and is very useful for custom dApp UIs. - -`x/wasm` is also a consumer of events, since when a smart contract executes a SubMsg and processes the reply, it receives -not only the `data` response from the message execution, but also the list of events. This makes it even more important for -us to document a standard event processing format. - -### Standard Events in x/wasm - -Following the model of `distribution`, we will split the emitted events into two parts. All calls to the message server, will receive -the following event: - -```go -sdk.NewEvent( - "message", - sdk.NewAttribute("module", "wasm"), - // Note: this was "signer" before 0.18 - sdk.NewAttribute("sender", msg.Sender), -), -``` - -No further information will be added to the generic "message" type, but rather be contained in a more context-specific event type. -Here are some examples: - -```go -// Store Code -sdk.NewEvent( - "store_code", - sdk.NewAttribute("code_id", fmt.Sprintf("%d", codeID)), - // features required by the contract (new in 0.18) - // see https://github.com/CosmWasm/wasmd/issues/574 - sdk.NewAttribute("feature", "stargate"), - sdk.NewAttribute("feature", "staking"), -) - -// Instantiate Contract -sdk.NewEvent( - "instantiate", - sdk.NewAttribute("code_id", fmt.Sprintf("%d", msg.CodeID)), - sdk.NewAttribute("_contract_address", contractAddr.String()), -) - -// Execute Contract -sdk.NewEvent( - "execute", - sdk.NewAttribute("_contract_address", contractAddr.String()), -) - -// Migrate Contract -sdk.NewEvent( - "migrate", - // Note: this is the new code id that is being migrated to - sdk.NewAttribute("code_id", fmt.Sprintf("%d", msg.CodeID)), - sdk.NewAttribute("_contract_address", contractAddr.String()), -) - -// Set new admin -sdk.NewEvent( - "update_admin", - sdk.NewAttribute("_contract_address", contractAddr.String()), - sdk.NewAttribute("admin", msg.NewAdmin), -) - -// Clear admin -sdk.NewEvent( - "clear_admin", - sdk.NewAttribute("_contract_address", contractAddr.String()), -) - -// Pin Code -sdk.NewEvent( - "pin_code", - sdk.NewAttribute("code_id", strconv.FormatUint(msg.CodeID, 10)), -) - -// Unpin Code -sdk.NewEvent( - "unpin_code", - sdk.NewAttribute("code_id", strconv.FormatUint(msg.CodeID, 10)), -) - -// Emitted when processing a submessage reply -sdk.NewEvent( - "reply", - sdk.NewAttribute("_contract_address", contractAddr.String()), - // If the submessage was successful, and reply is processing the success case - sdk.NewAttribute("mode", "handle_success"), - // If the submessage returned an error that was "caught" by the reply block - sdk.NewAttribute("mode", "handle_failure"), -) - -// Emitted when handling sudo -sdk.NewEvent( - "sudo", - sdk.NewAttribute("_contract_address", contractAddr.String()), -) -``` - -Note that every event that affects a contract (not store code, pin or unpin) will return the contract_address as -`_contract_address`. The events that are related to a particular wasm code (store code, instantiate, pin, unpin, and migrate) -will emit that as `code_id`. All attributes prefixed with `_` are reserved and may not be emitted by a smart contract, -so we use the underscore prefix consistently with attributes that may be injected into custom events. - -### Emitted Custom Events from a Contract - -When a CosmWasm contract returns a `Response` from one of the calls, it may return a list of attributes as well as a list -of events (in addition to data and a list of messages to dispatch). These are then processed in `x/wasm` to create events that -are emitted to the blockchain. - -If the response contains a non-empty list of `attributes`, `x/wasm` will emit a `wasm` type event. This event will -always be tagged with `_contract_address` by the Go module, so this is trust-worthy. The contract itself cannot overwrite -this field. Beyond this, the `attributes` returned by the contract, these are appended to the same event. - -A contact may also return custom `events`. These are multiple events, each with their own type as well as attributes. -When they are received, `x/wasm` prepends `wasm-` to the event type returned by the contact to avoid them trying to fake -an eg. `transfer` event from the bank module. The output here may look like: - -```go -sdk.NewEvent( - "wasm-promote" - sdk.NewAttribute("_contract_address", contractAddr.String()), - sdk.NewAttribute("batch_id", "6"), - sdk.NewAttribute("address", "cosmos1234567"), - sdk.NewAttribute("address", "cosmos1765432"), -), -sdk.NewEvent( - "wasm-promote" - sdk.NewAttribute("_contract_address", contractAddr.String()), - sdk.NewAttribute("batch_id", "7"), - sdk.NewAttribute("address", "cosmos19875632"), -) -``` - -Note that these custom events also have the `_contract_address` attribute automatically injected for easier attribution in the clients. -The multiple event API was designed to allow the contract to make logical groupings that are persisted in the event system, -more than flattening them all into one event like: - -```go -sdk.NewEvent( - "wasm" - sdk.NewAttribute("_contract_address", contractAddr.String()), - sdk.NewAttribute("action", "promote"), - sdk.NewAttribute("batch_id", "6"), - sdk.NewAttribute("address", "cosmos1234567"), - sdk.NewAttribute("address", "cosmos1765432"), - sdk.NewAttribute("batch_id", "7"), - sdk.NewAttribute("address", "cosmos19875632"), -) -``` - -If the Response contains neither `event` nor `attributes`, not `wasm*` events will be emitted, just the standard `message` -type as well as the action-dependent event (like `execute` or `migrate`). This is a significant change from pre-0.18 versions -where one could count on the `wasm` event to always be emitted. Now it is recommended to search for `execute._contract_address="foo"` -to find all transactions related to the contract. - -### Validation Rules - -While the `wasm` and `wasm-*` namespacing does sandbox the smart contract events and limits malicious activity they could -undertake, we also perform a number of further validation checks on the contracts: - -* No attribute key may start with `_`. This is currently used for `_contract_address` and is reserved for a - namespace for injecting more *trusted* attributes from the `x/wasm` module as opposed to the contract itself -* Event types are trimmed of whitespace, and must have at least two characters prior to prepending `wasm-`. If the contract returns - " hello\n", the event type will look like `wasm-hello`. If it emits " a ", this will be rejected with an error (aborting execution!) -* Attribute keys and values (both in `attributes` and under `events`) are trimmed of leading/trailing whitespace. If they are empty after - trimming, they are rejected as above (aborting the execution). Otherwise, they are passed verbatim. - -## Event Details for wasmd - -Beyond the basic Event system and emitted events, we must handle more advanced cases in `x/wasm` -and thus add some more logic to the event processing. Remember that CosmWasm contracts dispatch other -messages themselves, so far from the flattened event structure, or even a list of list (separated -by message index in the tx), we actually have a tree of messages, each with their own events. And we must -flatten that in a meaningful way to feed it into the event system. - -Furthermore, with the sub-message reply handlers, we end up with eg. "Contract A execute", "Contract B execute", -"Contract A reply". If we return all events by all of these, we may end up with many repeated event types and -a confusing results. However, we may use the standard "message" events to separate the sub-messages as it marks -where the next one starts. With careful analysis of the "sender" field on these "message" markers, we may be able -to reconstruct much of the tree execution path. We should ensure all this information is exposed in the most -consistent way possible. - -### Combining Events from Sub-Messages - -Each time a contract is executed, it not only returns the `message` event from its call, the `execute` event for the -contact and the `wasm` event with any custom fields from the contract itself. It will also return the same set of information -for all messages that it returned, which were later dispatched. The event system was really designed for one main -action emitting events, so we define a structure to flatten this event tree: - -* We only emit one event of type `message`. This is the top-level call, just like the standard Go modules. For all - dispatched submessages, we filter out this event type. -* All events are returned in execution order as [defined by CosmWasm docs](https://github.com/CosmWasm/cosmwasm/blob/main/SEMANTICS.md#dispatching-messages) -* `x/wasm` keeper emits a custom event for each call to a contract entry point. Not just `execute`, `instantiate`, - and `migrate`, but also `reply`, `sudo` and all ibc entry points. -* This means all `wasm*` events are preceeded by the cosmwasm entry point that returned them. - -To make this more clear, I will provide an example of executing a contract, which returns two messages, one to instantiate a new -contract and the other to set the withdrawl address, while also using `ReplyOnSuccess` for the instantiation (to get the -address). It will emit a series of events that looks something like this: - -```go -/// original execution (top-level message is the only one that gets the message tag) -sdk.NewEvent( - "message", - sdk.NewAttribute("module", "wasm"), - sdk.NewAttribute("sender", msg.Sender), -), - -// top-level exection call -sdk.NewEvent( - "execute", - sdk.NewAttribute("_contract_address", contractAddr.String()), -), -sdk.NewEvent( - "wasm", - sdk.NewAttribute("_contract_address", contractAddr.String()), - sdk.NewAttribute("custom", "from contract"), -), - -// instantiating contract (first dipatched message) -sdk.NewEvent( - "instantiate", - sdk.NewAttribute("code_id", fmt.Sprintf("%d", msg.CodeID)), - sdk.NewAttribute("_contract_address", newContract.String()), -) -// didn't emit any attributes, but one event -sdk.NewEvent( - "wasm-custom", - sdk.NewAttribute("_contract_address", newContract.String()), - sdk.NewAttribute("foobar", "baz"), -), - -// handling the reply (this doesn't emit a message event as it never goes through the message server) -sdk.NewEvent( - "reply", - sdk.NewAttribute("_contract_address", contractAddr.String()), - sdk.NewAttribute("mode", "handle_success"), -), -sdk.NewEvent( - "wasm", - sdk.NewAttribute("_contract_address", contractAddr.String()), - sdk.NewAttribute("custom", "from contract"), -), - -// calling the distribution module (second dispatched message) -sdk.NewEvent( - "set_withdraw_address", - sdk.NewAttribute("withdraw_address", withdrawAddr.String()), -), -``` - -### Exposing Events to Reply - -When the `reply` clause in a contract is called, it will receive the data returned from the message it -applies to, as well as all events from that message. In the above case, when the `reply` function was called -on `contractAddr` in response to initializing a contact, it would get the binary-encoded `initData` in the `data` -field, and the following in the `events` field: - -```go -sdk.NewEvent( - "instantiate", - sdk.NewAttribute("code_id", fmt.Sprintf("%d", msg.CodeID)), - sdk.NewAttribute("_contract_address", newContract.String()), -) -sdk.NewEvent( - "wasm-custom", - sdk.NewAttribute("_contract_address", newContract.String()), - sdk.NewAttribute("foobar", "baz"), -), -``` - -If the original contract execution example above was actually the result of a message returned by an eg. factory contract, -and it registered a ReplyOn clause, the `reply` function on that contract would receive the entire 11 events in the example -above, and would need to use the `message` markers to locate the segment of interest. - -## Governance Events -The governance process is handled by the cosmos-sdk `gov` module. We do not emit any events of type "message" anymore in v0.18+. -Context-specific events are emitted as described above. `Execution` and `Migration` return some contract result though that are -emitted as: -```go -sdk.NewEvent( - "gov_contract_result", - sdk.NewAttribute("result", hex.EncodeToString(data)), -) -``` - -## IBC Events - -All IBC entry points are only called by external accounts and not from contracts. They need to contain proofs of state of other blockchains and cannot be called by other contracts on the same chain. Therefore, the event emitted are not essential for cross-contract calls, and `x/wasm` does not emit custom events for these actions. - -There are well-defined events emitted by the IBC base layer and are required for the relayer functionality. If you wish to subscribe to these, you can find them [defined in the `ibc-go` codebase](https://github.com/cosmos/ibc-go/blob/main/modules/core/04-channel/keeper/events.go). diff --git a/docs/INTEGRATION.md b/docs/INTEGRATION.md deleted file mode 100644 index 177af46..0000000 --- a/docs/INTEGRATION.md +++ /dev/null @@ -1,198 +0,0 @@ - - -# Integration - -If you want to use Wasm in your own app, here is how you can get this working -quickly and easily. -First start with This [article](https://medium.com/cosmwasm/cosmwasm-for-ctos-iv-native-integrations-713140bf75fc) -in the "CosmWasm for CTOs" series that gives you a high level view. -Then check to make sure you fit the pre-requisites, -then integrate the `x/wasm` module as described below, and finally, you -can add custom messages and queries to your custom Go/SDK modules, exposing -them to any chain-specific contract. - -## Prerequisites - -The pre-requisites of integrating `x/wasm` into your custom app is to be using -a compatible version of the Cosmos SDK, and to accept some limits to the -hardware it runs on. - -| wasmd | Cosmos SDK | -|:-----:|:----------:| -| 1.0.0 | v0.47.1 | -| v0.5 | v0.45.14 | -| v0.4.0 | v0.45.9 | - - -We currently only support Intel/AMD64 CPUs and OSX or Linux. For Linux, the standard build -commands work for `glibc` systems (Ubuntu, Debian, CentOS, etc). If you wish to compile -for a `muslc` based system (like alpine), you need to compile a static library wasmvm locally -and compile go with the `muslc` build tag. Or just use the [Dockerfile](./Dockerfile), -which builds a static go binary in an alpine system. - -This limit comes from the Rust dll we use to run the wasm code, which comes -from [`wasmvm`](https://github.com/CosmWasm/wasmvm). There are open issues -for adding [ARM support](https://github.com/CosmWasm/wasmvm/issues/53), and -adding [Windows support](https://github.com/CosmWasm/wasmvm/issues/28). -However, these issues are not high on the roadmap and unless you are championing -them, please count on the current limits for the near future. - -## Quick Trial - -The simplest way to try out CosmWasm is simply to run `wasmd` out of the box, -and focus on writing, uploading, and using your custom contracts. There is -plenty that can be done there, and lots to learn. - -Once you are happy with it and want to use a custom Cosmos SDK app, -you may consider simply forking `wasmd`. *I highly advise against this*. -You should try one of the methods below. - -## Integrating wasmd - -### As external module - -The simplest way to use `wasmd` is just to import `x/wasm` and wire it up -in `app.go`. You now have access to the whole module and you custom modules -running side by side. (But the CosmWasm contracts will only have access -to `bank` and `staking`... more below on [customization](#Adding-Custom-Hooks)). - -The requirement here is that you have imported the standard sdk modules -from the Cosmos SDK, and enabled them in `app.go`. If so, you can just look -at [`wasmd/app/app.go`](https://github.com/terpnetwork/terp-core/blob/master/app/app.go#) -for how to do so (just search there for lines with `wasm`). - -`wasmd` also comes with 2 custom `ante handlers`: -* `CountTXDecorator` adds the TX position in the block into the context and passes it to the contracts -* `LimitSimulationGasDecorator` prevents an "infinite gas" query - -In order to support these features you would need to add our custom -ante handlers into the `ante handler chain` as in: [`app/ante.go`](https://github.com/terpnetwork/terp-core/blob/master/app/ante.go) - -### Copied into your app - -Sometimes, however, you will need to copy `x/wasm` into your app. This should -be in limited cases, and makes upgrading more difficult, so please take the -above path if possible. This is required if you have either disabled some key -SDK modules in your app (eg. using PoA not staking and need to disable those -callbacks and feature support), or if you have copied in the core `x/*` modules -from the Cosmos SDK into your application and customized them somehow. - -In either case, your best approach is to copy the `x/wasm` module from the -latest release into your application. Your goal is to make **minimal changes** -in this module, and rather add your customizations in a separate module. -This is due to the fact that you will have to copy and customize `x/wasm` -from upstream on all future `wasmd` releases, and this should be as simple -as possible. - -If, for example, you have forked the standard SDK libs, you just want to -change the imports (from eg. `github.com/cosmos/cosmos-sdk/x/bank` to -`github.com/YOUR/APP/x/bank`), and adjust any calls if there are compiler -errors due to differing APIs (maybe you use Decimals not Ints for currencies?). - -By the end of this, you should be able to run the standard CosmWasm contracts -in your application, alongside all your custom logic. - -## Adding custom hooks - -Once you have gotten this integration working and are happy with the -flexibility it offers you, you will probably start wishing for deeper -integration with your custom SDK modules. "It sure is nice to have custom -tokens with a bonding curve from my native token, but I would love -to trade them on the exchange I wrote as a Go module. Or maybe use them -to add options to the exchange." - -At this point, you need to dig down deeper and see how you can add this -power without forking either CosmWasm or `wasmd`. - -### Calling contracts from native code - -This is perhaps the easiest part. Let's say your native exchange module -wants to call into a token that lives as a CosmWasm module. You need to -pass the `wasm.Keeper` into your `exchange.Keeper`. If you know the format -for sending messages and querying the contract (exported as json schema -from each contract), and have a way of configuring addresses of supported -token contracts, your exchange code can simply call `wasm.Keeper.Execute` -with a properly formatted message to move funds, or `wasm.Keeper.SmartQuery` -to check balances. - -If you look at the unit tests in [`x/wasm/internal/keeper`](https://github.com/terpnetwork/terp-core/tree/master/x/wasm/internal/keeper), -it should be pretty straight forward. - -### Extending the Contract Interface - -If you want to let the contracts access your native modules, the first -step is to define a set of Messages and Queries that you want to expose, -and then add them as `CosmosMsg::Custom` and `QueryRequest::Custom` -variants. You can see an example of the [bindings for Terra](https://github.com/CosmWasm/terra-contracts/tree/master/packages/bindings). - -Once you have those bindings, use them to build a -[simple contact using much of the API](https://github.com/CosmWasm/terra-contracts/tree/master/contracts/maker). -Don't worry too much about the details, this should be usable, but mainly -you will want to upload it to your chain and use for integration tests -with your native Cosmos SDK modules. Once that is solid, then add more -and more complex contracts. - -You will then likely want to add a `mocks` package so you can provide -mocks for the functionality of your native modules when unit testing -the contracts (provide static data for exchange rates when your contracts -query it). You can see an example of [mocks for Terra contracts](https://github.com/CosmWasm/terra-contracts/tree/master/packages/mocks). - -What these three steps provide is basically a chain-specific extension to the CosmWasm contract SDK. -Any CosmWasm contract can import you library (bindings and mocks) and easily get started using -your custom, chain-specific extensions just as easily as using the standard CosmWasm interfaces. -What is left is actually wiring them up in your chain so they work as desired. - -Note, in order to ensure that no one tries to run the contracts on an unsupported chain, -you will want to include a `requires_XYZ` directive in your `bindings` library, this will -mean that only blockchain apps that explicitly declare their support for the `XYZ` extensions -(please rename XYZ to your project name) will allow the contract to be uploaded, and others -get error messages upon upload, not while running a critical feature later on. -You just need to add [a line like this](https://github.com/CosmWasm/terra-contracts/blob/master/packages/bindings/src/lib.rs#L13-L16) -to your binding library to add the requirement to any contract that imports your `bindings` lib. - -### Calling into the SDK - -Before I show how this works, I want to remind you, if you have copied `x/wasm`, -please **do not make these changes to `x/wasm`**. - -We will add a new module, eg. `x/contracts`, that will contain custom -bindings between CosmWasm contracts and your native modules. There are two entry points -for you to use. The first is -[`CustomQuerier`](https://github.com/terpnetwork/terp-core/blob/v0.8.0-rc1/x/wasm/internal/keeper/query_plugins.go#L35), -which allows you to handle your custom queries. The second is -[`CustomEncoder`](https://github.com/terpnetwork/terp-core/blob/v0.8.0-rc1/x/wasm/internal/keeper/handler_plugin.go#L30) -which allows you to convert the `CosmosMsg::Custom(YourMessage)` types to `[]sdk.Msg` to be dispatched. - -Writing stubs for these is rather simple. You can look at the `reflect_test.go` file to see this in action. -In particular, here [we define a `CustomQuerier`](https://github.com/terpnetwork/terp-core/blob/v0.8.0-rc1/x/wasm/internal/keeper/reflect_test.go#L355-L385), -and here [we define a `CustomHandler`](https://github.com/terpnetwork/terp-core/blob/v0.8.0-rc1/x/wasm/internal/keeper/reflect_test.go#L303-L353). -This code is responsible to take `json.RawMessage` from the raw bytes serialized from your custom types in rust and parse it into -Go structs. Then take these go structs and properly convert them for your custom SDK modules. - -You can look at the implementations for the `staking` module to see how to build these for non-trivial -cases, including passing in the `Keeper` via a closure. Here we -[encode staking messages](https://github.com/terpnetwork/terp-core/blob/v0.8.0-rc1/x/wasm/internal/keeper/handler_plugin.go#L114-L192). -Note that withdraw returns 2 messages, which is an option you can use if needed to translate into native messages. -When we [handle staking queries](https://github.com/terpnetwork/terp-core/blob/v0.8.0-rc1/x/wasm/internal/keeper/query_plugins.go#L109-L172) -we take in a `Keeper in the closure` and dispatch the custom `QueryRequest` from the contract to the native `Keeper` interface, -then encodes a response. When defining the return types, note that for proper parsing in the Rust contract, you -should properly name the JSON fields and use the `omitempty` keyword if Rust expects `Option`. You must also use -`omitempty` and pointers for all fields that correspond to a Rust `enum`, so exactly one field is serialized. - -### Wiring it all together - -Once you have writen and tested these custom callbacks for your module, you need to enable it in your application. -The first step is to write an integration test with a contract compiled with your custom SDK to ensure it works properly, -then you need to configure this in `app.go`. - -For the test cases, you must -[define the supported feature set](https://github.com/CosmWasm/wasmd/blob/ade03a1d39a9b8882e9a1ce80572d39d57bb9bc3/x/wasm/internal/keeper/reflect_test.go#L52) -to include your custom name (remember `requires_XYZ` above?). Then, when creating `TestInput`, -you can [pass in your custom encoder and querier](https://github.com/CosmWasm/wasmd/blob/ade03a1d39a9b8882e9a1ce80572d39d57bb9bc3/x/wasm/internal/keeper/reflect_test.go#L52). -Run a few tests with your compiled contract, ideally exercising the majority of the interfaces to ensure that all parsing between the contract and -the SDK is implemented properly. - -Once you have tested this and are happy with the results, you can wire it up in `app.go`. -Just edit [the default `NewKeeper` constructor](https://github.com/CosmWasm/wasmd/blob/v0.8.0-rc1/app/app.go#L257-L258) -to have the proper `availableCapabilities` and pass in the `CustomEncoder` and `CustomQuerier` as the last two arguments to `NewKeeper`. -Now you can compile your chain and upload your custom contracts on it. \ No newline at end of file diff --git a/docs/ISSUE_TEMPLATES/bug_report.md b/docs/ISSUE_TEMPLATES/bug_report.md deleted file mode 100644 index bbdf677..0000000 --- a/docs/ISSUE_TEMPLATES/bug_report.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -name: Bug report -about: Create a report to help us improve - ---- - - - -### Prerequisites - -* [Ask questions in the RocketChat](https://chat.terp.network) -* [Look through recent posts on the forum](https://forum.scrt.network) -* [Check issues that have already been filed](https://github.com/issues?utf8=✓&q=is%3Aissue+user%3Aenigmampc) - -### Description - - - -### Steps to Reproduce - -1. -2. -3. - -**Expected behavior:** - - - -**Actual behavior:** - - - -**Reproduces how often:** - - - -### Additional Information - - \ No newline at end of file diff --git a/docs/ISSUE_TEMPLATES/features_request.md b/docs/ISSUE_TEMPLATES/features_request.md deleted file mode 100644 index 9e15a3f..0000000 --- a/docs/ISSUE_TEMPLATES/features_request.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -name: Feature request -about: Suggest an idea for this project - ---- - - - -## Summary - - - -## Motivation - - - -## Describe alternatives you've considered - - - -## Additional context - - \ No newline at end of file diff --git a/docs/PULL_REQUEST_TEMPLATE/PR_TEMPLATE.md b/docs/PULL_REQUEST_TEMPLATE/PR_TEMPLATE.md deleted file mode 100644 index 95553a0..0000000 --- a/docs/PULL_REQUEST_TEMPLATE/PR_TEMPLATE.md +++ /dev/null @@ -1,10 +0,0 @@ -👋 Hello there! Welcome. Please follow the steps below to tell us about your contribution. - -1. Use the correct template for your contribution: - - 🐛 [Fixing a Bug](bug_fix.md) - - 📈 [Improving Performance](improve_performance.md) - - 📝 [Updating Documentation](update_docs.md) - - 💻 [Changing Functionality](change_functionality.md) -2. Replace text with the contents of the template -3. Fill in all sections of the template -4. Click "Create pull request" \ No newline at end of file diff --git a/docs/PULL_REQUEST_TEMPLATE/bug_fix.md b/docs/PULL_REQUEST_TEMPLATE/bug_fix.md deleted file mode 100644 index d178815..0000000 --- a/docs/PULL_REQUEST_TEMPLATE/bug_fix.md +++ /dev/null @@ -1,49 +0,0 @@ -### Requirements for Contributing a Bug Fix - -* Fill out the template below. Any pull request that does not include enough information to be reviewed in a timely manner may be closed at the maintainers' discretion. -* The pull request must only fix an existing bug. To contribute other changes, you must use a different template. You can see all templates [here](PULL_REQUEST_TEMPLATE.md). - -### Identify the Bug - - - -### Description of the Change - - - -### Alternate Designs - - - -### Possible Drawbacks - - - -### Verification Process - - - -### Release Notes - - \ No newline at end of file diff --git a/docs/PULL_REQUEST_TEMPLATE/change_functionality.md b/docs/PULL_REQUEST_TEMPLATE/change_functionality.md deleted file mode 100644 index c9d08aa..0000000 --- a/docs/PULL_REQUEST_TEMPLATE/change_functionality.md +++ /dev/null @@ -1,44 +0,0 @@ -### Requirements for Adding, Changing, or Removing a Feature - -* Fill out the template below. Any pull request that does not include enough information to be reviewed in a timely manner may be closed at the maintainers' discretion. All templates [here](PULL_REQUEST_TEMPLATE.md). -* After you create the pull request, all status checks must pass before a maintainer reviews your contribution. - -### Description of the Change - - - -### Alternate Designs - - - -### Possible Drawbacks - - - -### Verification Process - - - -### Release Notes - - \ No newline at end of file diff --git a/docs/PULL_REQUEST_TEMPLATE/improve_performance.md b/docs/PULL_REQUEST_TEMPLATE/improve_performance.md deleted file mode 100644 index 136a696..0000000 --- a/docs/PULL_REQUEST_TEMPLATE/improve_performance.md +++ /dev/null @@ -1,46 +0,0 @@ -### Requirements for Contributing a Performance Improvement - -* Fill out the template below. Any pull request that does not include enough information to be reviewed in a timely manner may be closed at the maintainers' discretion. -* The pull request must only affect performance of existing functionality. To contribute other changes, you must use a different template. You can see all templates [here](PULL_REQUEST_TEMPLATE.md). - -### Description of the Change - - - -### Quantitative Performance Benefits - - - -### Possible Drawbacks - - - -### Verification Process - - - -### Applicable Issues - - - -### Release Notes - - \ No newline at end of file diff --git a/docs/PULL_REQUEST_TEMPLATE/update_docs.md b/docs/PULL_REQUEST_TEMPLATE/update_docs.md deleted file mode 100644 index 696706e..0000000 --- a/docs/PULL_REQUEST_TEMPLATE/update_docs.md +++ /dev/null @@ -1,5 +0,0 @@ -### Requirements for Contributing Documentation -* Fill out the template below. Any pull request that does not include enough information to be reviewed in a timely manner may be closed at the maintainers' discretion. -* The pull request must only contribute documentation (for example, markdown files or API docs). To contribute other changes, you must use a different template. You can see all templates [here](./PR_TEMPLATE.md). - -### Description of the Change Release Notes diff --git a/docs/UPGRADING.md b/docs/UPGRADING.md deleted file mode 100644 index 827d7d8..0000000 --- a/docs/UPGRADING.md +++ /dev/null @@ -1,277 +0,0 @@ -# Upgrading - -With stargate, we have access to the `x/upgrade` module, which we can use to perform -inline upgrades. Please first read both the basic -[x/upgrade spec](https://github.com/cosmos/cosmos-sdk/blob/master/x/upgrade/spec/01_concepts.md) -and [go docs](https://godoc.org/github.com/cosmos/cosmos-sdk/x/upgrade#hdr-Performing_Upgrades) -for the background on the module. - -In this case, we will demo an update with no state migration. This is for cases when -there is a state-machine-breaking (but not state-breaking) bugfix or enhancement. -There are some -[open issues running some state migrations](https://github.com/cosmos/cosmos-sdk/issues/8265) -and we will wait for that to be fixed before trying those. - -The following will lead through running an upgrade on a local node, but the same process -would work on a real network (with more ops and governance coordination). - -## Setup - -We need to have two different versions of `wasmd` which depend on state-compatible -versions of the Cosmos SDK. We only focus on upgrade starting with stargate. You will -have to use the "dump state and restart" approach to move from launchpad to stargate. - -For this demo, we will show an upgrade from `v0.14.0` to musselnet branch. - -### Handler - -You will need to register a handler for the upgrade. This is specific to a particular -testnet and upgrade path, and the default `wasmd` will never have a registered handler -on master. In this case, we make a `musselnet` branch off of `v0.14.0` just -registering one handler with a given name. - -Look at [PR 351](https://github.com/CosmWasm/wasmd/pull/351/files) for an example -of a minimal handler. We do not make any state migrations, but rather use this -as a flag to coordinate all validators to stop the old version at one height, and -start the specified v2 version on the next block. - -### Prepare binaries - -Let's get the two binaries we want to test, the pre-upgrade and the post-upgrade -binaries. In this case the pre-release is already a published to docker hub and -can be downloaded simply via: - -`docker pull cosmwasm/wasmd:v0.14.0` - -(If this is not yet released, build it from the tip of master) - -The post-release is not published, so we can build it ourselves. Check out this -`wasmd` repo, and the proper `musselnet` branch: - -``` -# use musselnet-v2 tag once that exists -git checkout musselnet -docker build . -t wasmd:musselnet-v2 -``` - -Verify they are both working for you locally: - -``` -docker run cosmwasm/wasmd:v0.14.0 wasmd version -docker run wasmd:musselnet-v2 wasmd version -``` - -## Start the pre-release chain - -Follow the normal setup stage, but in this case we will want to have super short -governance voting period, 5 minutes rather than 2 days (or 2 weeks!). - -**Setup a client with private key** - -```sh -## TODO: I think we need to do this locally??? -docker volume rm -f musselnet_client - -docker run --rm -it \ - -e PASSWORD=1234567890 \ - --mount type=volume,source=musselnet_client,target=/root \ - cosmwasm/wasmd:v0.14.0 /opt/setup_wasmd.sh - -# enter "1234567890" when prompted -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - cosmwasm/wasmd:v0.14.0 wasmd keys show -a validator -# use the address returned above here -CLIENT=wasm1anavj4eyxkdljp27sedrdlt9dm26c8a7a8p44l -``` - -**Setup the blockchain node** - -```sh -docker volume rm -f musselnet - -# add your testing address here, so you can do something with the client -docker run --rm -it \ - --mount type=volume,source=musselnet,target=/root \ - cosmwasm/wasmd:v0.14.0 /opt/setup_wasmd.sh $CLIENT - -# Update the voting times in the genesis file -docker run --rm -it \ - --mount type=volume,source=musselnet,target=/root \ - cosmwasm/wasmd:v0.14.0 sed -ie 's/172800s/300s/' /root/.terp/config/genesis.json - -# start up the blockchain and all embedded servers as one process -docker run --rm -it -p 26657:26657 -p 26656:26656 -p 1317:1317 \ - --mount type=volume,source=musselnet,target=/root \ - cosmwasm/wasmd:v0.14.0 /opt/run_wasmd.sh -``` - -## Sanity checks - -Let's use our client node to query the current state and send some tokens to a -random address: - -```sh -RCPT=wasm1pypadqklna33nv3gl063rd8z9q8nvauaalz820 - -# note --network=host so it can connect to the other docker image -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - query bank balances $CLIENT - -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - query bank balances $RCPT - -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - tx send validator $RCPT 500000ucosm,600000ustake --chain-id testing - -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - query bank balances $RCPT -``` - -## Take majority control of the chain - -In genesis we have a valiator with 250 million `ustake` bonded. We want to be easily -able to pass a proposal with our client. Let us bond 700 million `ustake` to ensure -we have > 67% of the voting power and will pass with the validator not voting. - -```sh -# get the "operator_address" (wasmvaloper...) from here -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - query staking validators -VALIDATOR=...... - -# and stake here -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - tx staking delegate $VALIDATOR 750000000ustake \ - --from validator --chain-id testing -``` - -## Vote on the upgrade - -Now that we see the chain is running and producing blocks, and our client has -enough token to control the netwrok, let's create a governance -upgrade proposal for the new chain to move to `musselnet-v2` (this must be the -same name as we use in the handler we created above, change this to match what -you put in your handler): - -```sh -# create the proposal -# check the current height and add 100-200 or so for the upgrade time -# (the voting period is ~60 blocks) -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - tx gov submit-proposal software-upgrade musselnet-v2 \ - --upgrade-height=500 --deposit=10000000ustake \ - --title="Upgrade" --description="Upgrade to musselnet-v2" \ - --from validator --chain-id testing - -# make sure it looks good -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - query gov proposal 1 - -# vote for it -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - tx gov vote 1 yes \ - --from validator --chain-id testing - -# ensure vote was counted -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - query gov votes 1 -``` - -## Swap out binaries - -Now, we just wait about 5 minutes for the vote to pass, and ensure it is passed: - -```sh -# make sure it looks good -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - query gov proposal 1 -``` - -After this, we just let the chain run and open the terminal so you can see the log files. -It should keep producing blocks until it hits height 500 (or whatever you set there), -when the process will print a huge stacktrace and hang. Immediately before the stack trace, you -should see a line like this (burried under tons of tendermint logs): - -`8:50PM ERR UPGRADE "musselnet-v2" NEEDED at height: 100:` - -Kill it with Ctrl-C, and then try to restart with the pre-upgrade version and it should -immediately fail on startup, with the same error message as above. - -```sh -docker run --rm -it -p 26657:26657 -p 26656:26656 -p 1317:1317 \ - --mount type=volume,source=musselnet,target=/root \ - cosmwasm/wasmd:v0.14.0 /opt/run_wasmd.sh -``` - -Then, we start with the post-upgrade version and see it properly update: - -```sh -docker run --rm -it -p 26657:26657 -p 26656:26656 -p 1317:1317 \ - --mount type=volume,source=musselnet,target=/root \ - wasmd:musselnet-v2 /opt/run_wasmd.sh -``` - -On a real network, operators will have to be awake when the upgrade plan is activated -and manually perform this switch, or use some automated tooling like -[cosmosvisor](https://github.com/cosmos/cosmos-sdk/blob/master/cosmovisor/README.md). - -## Check final state - -Now that we have upgraded, we can use the new client version. Let's do a brief -sanity check to ensure our balances are proper, and our stake remains -delegated. That and continued block production should be a good sign the upgrade -was successful: - -```sh -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - wasmd:musselnet-v2 wasmd \ - query bank balances $CLIENT - -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - wasmd:musselnet-v2 wasmd \ - query bank balances $RCPT - -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - wasmd:musselnet-v2 wasmd \ - query staking delegations $CLIENT -``` diff --git a/docs/api_migration.md b/docs/api_migration.md deleted file mode 100644 index 734099e..0000000 --- a/docs/api_migration.md +++ /dev/null @@ -1,36 +0,0 @@ -# Changes to the api - -## [\#196](https://github.com/CosmWasm/wasmd/issues/196) - Move history of contract code migrations to their own prefix store - -The `ContractDetails.initMsg` used in cosmJs was moved into a new entity `ContractCodeHistoryEntry`. They contain code updates to a contract. - -### Route -This data is available via a new route `/wasm/contract/{contractAddr}/history` - -### Response -A list of ContractCodeHistoryEntries with following fields: -* `operation` can be any of `"Init", "Migrate", "Genesis"` -* `code_id` uint64 -* `msg` as raw json - -### Errors -* 404 - for an unknown contract - -### CLI -`terpd query wasm contract-history [bech32_address] to print all the code changes.` -Example: -`terpd query wasm contract-history cosmos18r5szma8hm93pvx6lwpjwyxruw27e0k5uw835c` -```json -[ - { - "operation": "Init", - "code_id": 1, - "msg": "\"init-msg\"" - }, - { - "operation": "Migrate", - "code_id": 2, - "msg": "\"migrate-msg\"" - } -] -``` diff --git a/docs/docs.go b/docs/docs.go index 92b90ac..1167d56 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -2,5 +2,5 @@ package docs import "embed" -//go:embed * +//go:embed static var Docs embed.FS diff --git a/docs/proto/proto-docs.md b/docs/proto/proto-docs.md deleted file mode 100644 index 5faaa61..0000000 --- a/docs/proto/proto-docs.md +++ /dev/null @@ -1,478 +0,0 @@ - -# Protobuf Documentation - - -## Table of Contents - -- [cosmwasm/tokenfactory/v1beta1/authority_metadata.proto](#cosmwasm/tokenfactory/v1beta1/authority_metadata.proto) - - [DenomAuthorityMetadata](#osmosis.tokenfactory.v1beta1.DenomAuthorityMetadata) - -- [cosmwasm/tokenfactory/v1beta1/params.proto](#cosmwasm/tokenfactory/v1beta1/params.proto) - - [Params](#osmosis.tokenfactory.v1beta1.Params) - -- [cosmwasm/tokenfactory/v1beta1/genesis.proto](#cosmwasm/tokenfactory/v1beta1/genesis.proto) - - [GenesisDenom](#osmosis.tokenfactory.v1beta1.GenesisDenom) - - [GenesisState](#osmosis.tokenfactory.v1beta1.GenesisState) - -- [cosmwasm/tokenfactory/v1beta1/query.proto](#cosmwasm/tokenfactory/v1beta1/query.proto) - - [QueryDenomAuthorityMetadataRequest](#osmosis.tokenfactory.v1beta1.QueryDenomAuthorityMetadataRequest) - - [QueryDenomAuthorityMetadataResponse](#osmosis.tokenfactory.v1beta1.QueryDenomAuthorityMetadataResponse) - - [QueryDenomsFromCreatorRequest](#osmosis.tokenfactory.v1beta1.QueryDenomsFromCreatorRequest) - - [QueryDenomsFromCreatorResponse](#osmosis.tokenfactory.v1beta1.QueryDenomsFromCreatorResponse) - - [QueryParamsRequest](#osmosis.tokenfactory.v1beta1.QueryParamsRequest) - - [QueryParamsResponse](#osmosis.tokenfactory.v1beta1.QueryParamsResponse) - - - [Query](#osmosis.tokenfactory.v1beta1.Query) - -- [cosmwasm/tokenfactory/v1beta1/tx.proto](#cosmwasm/tokenfactory/v1beta1/tx.proto) - - [MsgBurn](#osmosis.tokenfactory.v1beta1.MsgBurn) - - [MsgBurnResponse](#osmosis.tokenfactory.v1beta1.MsgBurnResponse) - - [MsgChangeAdmin](#osmosis.tokenfactory.v1beta1.MsgChangeAdmin) - - [MsgChangeAdminResponse](#osmosis.tokenfactory.v1beta1.MsgChangeAdminResponse) - - [MsgCreateDenom](#osmosis.tokenfactory.v1beta1.MsgCreateDenom) - - [MsgCreateDenomResponse](#osmosis.tokenfactory.v1beta1.MsgCreateDenomResponse) - - [MsgMint](#osmosis.tokenfactory.v1beta1.MsgMint) - - [MsgMintResponse](#osmosis.tokenfactory.v1beta1.MsgMintResponse) - - [MsgSetDenomMetadata](#osmosis.tokenfactory.v1beta1.MsgSetDenomMetadata) - - [MsgSetDenomMetadataResponse](#osmosis.tokenfactory.v1beta1.MsgSetDenomMetadataResponse) - - - [Msg](#osmosis.tokenfactory.v1beta1.Msg) - -- [Scalar Value Types](#scalar-value-types) - - - - -

Top

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

Top

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

Top

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

Top

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

Top

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

Top

- -## {{.Name}} -{{.Description}} - -{{range .Messages}} - - -### {{.LongName}} -{{.Description}} - -{{if .HasFields}} -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -{{range .Fields -}} - | `{{.Name}}` | [{{.LongType}}](#{{.FullType}}) | {{.Label}} | {{if (index .Options "deprecated"|default false)}}**Deprecated.** {{end}}{{nobr .Description}}{{if .DefaultValue}} Default: {{.DefaultValue}}{{end}} | -{{end}} -{{end}} - -{{if .HasExtensions}} -| Extension | Type | Base | Number | Description | -| --------- | ---- | ---- | ------ | ----------- | -{{range .Extensions -}} - | `{{.Name}}` | {{.LongType}} | {{.ContainingLongType}} | {{.Number}} | {{nobr .Description}}{{if .DefaultValue}} Default: {{.DefaultValue}}{{end}} | -{{end}} -{{end}} - -{{end}} - -{{range .Enums}} - - -### {{.LongName}} -{{.Description}} - -| Name | Number | Description | -| ---- | ------ | ----------- | -{{range .Values -}} - | {{.Name}} | {{.Number}} | {{nobr .Description}} | -{{end}} - -{{end}} - -{{if .HasExtensions}} - - -### File-level Extensions -| Extension | Type | Base | Number | Description | -| --------- | ---- | ---- | ------ | ----------- | -{{range .Extensions -}} - | `{{.Name}}` | {{.LongType}} | {{.ContainingLongType}} | {{.Number}} | {{nobr .Description}}{{if .DefaultValue}} Default: `{{.DefaultValue}}`{{end}} | -{{end}} -{{end}} - -{{range .Services}} - - -### {{.Name}} -{{.Description}} - -| Method Name | Request Type | Response Type | Description | HTTP Verb | Endpoint | -| ----------- | ------------ | ------------- | ------------| ------- | -------- | -{{range .Methods -}} - | `{{.Name}}` | [{{.RequestLongType}}](#{{.RequestFullType}}){{if .RequestStreaming}} stream{{end}} | [{{.ResponseLongType}}](#{{.ResponseFullType}}){{if .ResponseStreaming}} stream{{end}} | {{nobr .Description}} | {{with (index .Options "google.api.http")}}{{range .Rules}}{{.Method}}|{{.Pattern}}{{end}}{{end}}| -{{end}} -{{end}} - -{{end}} - -## Scalar Value Types - -| .proto Type | Notes | C++ | Java | Python | Go | C# | PHP | Ruby | -| ----------- | ----- | --- | ---- | ------ | -- | -- | --- | ---- | -{{range .Scalars -}} - | {{.ProtoType}} | {{.Notes}} | {{.CppType}} | {{.JavaType}} | {{.PythonType}} | {{.GoType}} | {{.CSharp}} | {{.PhpType}} | {{.RubyType}} | -{{end}} diff --git a/docs/static/openapi.yml b/docs/static/openapi.yml new file mode 100644 index 0000000..24e0779 --- /dev/null +++ b/docs/static/openapi.yml @@ -0,0 +1,25664 @@ +openapi: 3.0.0 +info: + title: Juno network + version: v15 +paths: + /cosmos/auth/v1beta1/accounts: + get: + summary: Accounts returns all the existing accounts + description: "Since: cosmos-sdk 0.43" + operationId: Accounts_3VRJG + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + accounts: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: accounts are the existing accounts + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryAccountsResponse is the response type for the + Query/Accounts RPC method. + + + Since: cosmos-sdk 0.43 + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + schema: + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + in: query + required: false + schema: + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + schema: + type: boolean + tags: + - gRPC Gateway API + "/cosmos/auth/v1beta1/accounts/{address}": + get: + summary: Account returns account details based on address. + operationId: Account_4751S + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + account: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: account defines the account of the corresponding address. + description: QueryAccountResponse is the response type for the Query/Account RPC + method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: address + description: address defines the address to query for. + in: path + required: true + schema: + type: string + tags: + - gRPC Gateway API + "/cosmos/auth/v1beta1/module_accounts/{name}": + get: + summary: ModuleAccountByName returns the module account info by module name + operationId: ModuleAccountByName_GQLMA + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + account: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: QueryModuleAccountByNameResponse is the response type for the + Query/ModuleAccountByName RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: name + in: path + required: true + schema: + type: string + tags: + - gRPC Gateway API + /cosmos/auth/v1beta1/params: + get: + summary: Params queries all parameters. + operationId: Params_ZQGZI + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + params: + description: params defines the parameters of the module. + type: object + properties: + max_memo_characters: + type: string + format: uint64 + tx_sig_limit: + type: string + format: uint64 + tx_size_cost_per_byte: + type: string + format: uint64 + sig_verify_cost_ed25519: + type: string + format: uint64 + sig_verify_cost_secp256k1: + type: string + format: uint64 + description: QueryParamsResponse is the response type for the Query/Params RPC + method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + "/cosmos/bank/v1beta1/balances/{address}": + get: + summary: AllBalances queries the balance of all coins for a single account. + operationId: AllBalances_TCIFU + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + balances: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + description: balances is the balances of all the coins. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryAllBalancesResponse is the response type for the + Query/AllBalances RPC + + method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: address + description: address is the address to query balances for. + in: path + required: true + schema: + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + schema: + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + in: query + required: false + schema: + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + schema: + type: boolean + tags: + - gRPC Gateway API + "/cosmos/bank/v1beta1/balances/{address}/by_denom": + get: + summary: Balance queries the balance of a single coin for a single account. + operationId: Balance_HBAVH + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + balance: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + description: QueryBalanceResponse is the response type for the Query/Balance RPC + method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: address + description: address is the address to query balances for. + in: path + required: true + schema: + type: string + - name: denom + description: denom is the coin denom to query balances for. + in: query + required: false + schema: + type: string + tags: + - gRPC Gateway API + /cosmos/bank/v1beta1/denoms_metadata: + get: + summary: DenomsMetadata queries the client metadata for all registered coin + denominations. + operationId: DenomsMetadata_TKG35 + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + metadatas: + type: array + items: + type: object + properties: + description: + type: string + denom_units: + type: array + items: + type: object + properties: + denom: + type: string + description: denom represents the string name of the given denom unit (e.g + uatom). + exponent: + type: integer + format: int64 + description: >- + 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). + aliases: + type: array + items: + type: string + title: aliases is a list of string aliases for the given denom + description: >- + DenomUnit represents a struct that describes a + given + + denomination unit of the basic token. + title: denom_units represents the list of DenomUnit's for a given coin + base: + type: string + description: base represents the base denom (should be the DenomUnit with + exponent = 0). + display: + type: string + description: |- + display indicates the suggested denom that should be + displayed in clients. + name: + type: string + description: "Since: cosmos-sdk 0.43" + title: "name defines the name of the token (eg: Cosmos Atom)" + symbol: + type: string + description: >- + symbol is the token symbol usually shown on + exchanges (eg: ATOM). This can + + be the same as the display. + + + Since: cosmos-sdk 0.43 + description: |- + Metadata represents a struct that describes + a basic token. + description: metadata provides the client information for all the registered + tokens. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryDenomsMetadataResponse is the response type for the + Query/DenomsMetadata RPC + + method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + schema: + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + in: query + required: false + schema: + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + schema: + type: boolean + tags: + - gRPC Gateway API + "/cosmos/bank/v1beta1/denoms_metadata/{denom}": + get: + summary: DenomsMetadata queries the client metadata of a given coin denomination. + operationId: DenomMetadata_4OBWZ + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + metadata: + type: object + properties: + description: + type: string + denom_units: + type: array + items: + type: object + properties: + denom: + type: string + description: denom represents the string name of the given denom unit (e.g + uatom). + exponent: + type: integer + format: int64 + description: >- + 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). + aliases: + type: array + items: + type: string + title: aliases is a list of string aliases for the given denom + description: |- + DenomUnit represents a struct that describes a given + denomination unit of the basic token. + title: denom_units represents the list of DenomUnit's for a given coin + base: + type: string + description: base represents the base denom (should be the DenomUnit with + exponent = 0). + display: + type: string + description: |- + display indicates the suggested denom that should be + displayed in clients. + name: + type: string + description: "Since: cosmos-sdk 0.43" + title: "name defines the name of the token (eg: Cosmos Atom)" + symbol: + type: string + description: >- + symbol is the token symbol usually shown on exchanges + (eg: ATOM). This can + + be the same as the display. + + + Since: cosmos-sdk 0.43 + description: |- + Metadata represents a struct that describes + a basic token. + description: >- + QueryDenomMetadataResponse is the response type for the + Query/DenomMetadata RPC + + method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: denom + description: denom is the coin denom to query the metadata for. + in: path + required: true + schema: + type: string + tags: + - gRPC Gateway API + /cosmos/bank/v1beta1/params: + get: + summary: Params queries the parameters of x/bank module. + operationId: Params_BLVD9 + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + params: + type: object + properties: + send_enabled: + type: array + items: + type: object + properties: + denom: + type: string + enabled: + type: boolean + description: >- + SendEnabled maps coin denom to a send_enabled status + (whether a denom is + + sendable). + default_send_enabled: + type: boolean + description: Params defines the parameters for the bank module. + description: QueryParamsResponse defines the response type for querying x/bank + parameters. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + "/cosmos/bank/v1beta1/spendable_balances/{address}": + get: + summary: |- + SpendableBalances queries the spenable balance of all coins for a single + account. + operationId: SpendableBalances_5RIPQ + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + balances: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + description: balances is the spendable balances of all the coins. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QuerySpendableBalancesResponse defines the gRPC response + structure for querying + + an account's spendable balances. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: address + description: address is the address to query spendable balances for. + in: path + required: true + schema: + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + schema: + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + in: query + required: false + schema: + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + schema: + type: boolean + tags: + - gRPC Gateway API + /cosmos/bank/v1beta1/supply: + get: + summary: TotalSupply queries the total supply of all coins. + operationId: TotalSupply_E1EZ0 + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + supply: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + title: supply is the supply of the coins + pagination: + description: |- + pagination defines the pagination in the response. + + Since: cosmos-sdk 0.43 + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + title: >- + QueryTotalSupplyResponse is the response type for the + Query/TotalSupply RPC + + method + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + schema: + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + in: query + required: false + schema: + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + schema: + type: boolean + tags: + - gRPC Gateway API + "/cosmos/bank/v1beta1/supply/{denom}": + get: + summary: SupplyOf queries the supply of a single coin. + operationId: SupplyOf_PWKWO + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + amount: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + description: QuerySupplyOfResponse is the response type for the Query/SupplyOf + RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: denom + description: denom is the coin denom to query balances for. + in: path + required: true + schema: + type: string + tags: + - gRPC Gateway API + "/cosmos/staking/v1beta1/delegations/{delegator_addr}": + get: + summary: DelegatorDelegations queries all delegations of a given delegator + address. + operationId: DelegatorDelegations_JOZMT + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + delegation_responses: + type: array + items: + type: object + properties: + delegation: + type: object + properties: + delegator_address: + type: string + description: delegator_address is the bech32-encoded address of the delegator. + validator_address: + type: string + description: validator_address is the bech32-encoded address of the validator. + shares: + type: string + description: shares define the delegation shares received. + description: >- + Delegation represents the bond with tokens held by + an account. It is + + owned by one delegator, and is associated with the voting power of one + + validator. + balance: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an + amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + description: >- + DelegationResponse is equivalent to Delegation except + that it contains a + + balance in addition to shares which is more suitable for client responses. + description: delegation_responses defines all the delegations' info of a + delegator. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + QueryDelegatorDelegationsResponse is response type for the + Query/DelegatorDelegations RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: delegator_addr + description: delegator_addr defines the delegator address to query for. + in: path + required: true + schema: + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + schema: + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + in: query + required: false + schema: + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + schema: + type: boolean + tags: + - gRPC Gateway API + "/cosmos/staking/v1beta1/delegators/{delegator_addr}/redelegations": + get: + summary: Redelegations queries redelegations of given address. + operationId: Redelegations_14VGU + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + redelegation_responses: + type: array + items: + type: object + properties: + redelegation: + type: object + properties: + delegator_address: + type: string + description: delegator_address is the bech32-encoded address of the delegator. + validator_src_address: + type: string + description: validator_src_address is the validator redelegation source operator + address. + validator_dst_address: + type: string + description: validator_dst_address is the validator redelegation destination + operator address. + entries: + type: array + items: + type: object + properties: + creation_height: + type: string + format: int64 + description: creation_height defines the height which the redelegation took + place. + completion_time: + type: string + format: date-time + description: completion_time defines the unix time for redelegation completion. + initial_balance: + type: string + description: initial_balance defines the initial balance when redelegation + started. + shares_dst: + type: string + description: shares_dst is the amount of destination-validator shares created by + redelegation. + description: RedelegationEntry defines a redelegation object with relevant + metadata. + description: entries are the redelegation entries. + description: >- + Redelegation contains the list of a particular + delegator's redelegating bonds + + from a particular source validator to a particular destination validator. + entries: + type: array + items: + type: object + properties: + redelegation_entry: + type: object + properties: + creation_height: + type: string + format: int64 + description: creation_height defines the height which the redelegation took + place. + completion_time: + type: string + format: date-time + description: completion_time defines the unix time for redelegation completion. + initial_balance: + type: string + description: initial_balance defines the initial balance when redelegation + started. + shares_dst: + type: string + description: shares_dst is the amount of destination-validator shares created by + redelegation. + description: RedelegationEntry defines a redelegation object with relevant + metadata. + balance: + type: string + description: >- + RedelegationEntryResponse is equivalent to a + RedelegationEntry except that it + + contains a balance in addition to shares which is more suitable for client + + responses. + description: >- + RedelegationResponse is equivalent to a Redelegation + except that its entries + + contain a balance in addition to shares which is more suitable for client + + responses. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryRedelegationsResponse is response type for the + Query/Redelegations RPC + + method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: delegator_addr + description: delegator_addr defines the delegator address to query for. + in: path + required: true + schema: + type: string + - name: src_validator_addr + description: src_validator_addr defines the validator address to redelegate from. + in: query + required: false + schema: + type: string + - name: dst_validator_addr + description: dst_validator_addr defines the validator address to redelegate to. + in: query + required: false + schema: + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + schema: + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + in: query + required: false + schema: + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + schema: + type: boolean + tags: + - gRPC Gateway API + "/cosmos/staking/v1beta1/delegators/{delegator_addr}/unbonding_delegations": + get: + summary: >- + DelegatorUnbondingDelegations queries all unbonding delegations of a + given + + delegator address. + operationId: DelegatorUnbondingDelegations_E3804 + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + unbonding_responses: + type: array + items: + type: object + properties: + delegator_address: + type: string + description: delegator_address is the bech32-encoded address of the delegator. + validator_address: + type: string + description: validator_address is the bech32-encoded address of the validator. + entries: + type: array + items: + type: object + properties: + creation_height: + type: string + format: int64 + description: creation_height is the height which the unbonding took place. + completion_time: + type: string + format: date-time + description: completion_time is the unix time for unbonding completion. + initial_balance: + type: string + description: initial_balance defines the tokens initially scheduled to receive + at completion. + balance: + type: string + description: balance defines the tokens to receive at completion. + description: UnbondingDelegationEntry defines an unbonding object with relevant + metadata. + description: entries are the unbonding delegation entries. + description: >- + UnbondingDelegation stores all of a single delegator's + unbonding bonds + + for a single validator in an time-ordered list. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryUnbondingDelegatorDelegationsResponse is response type + for the + + Query/UnbondingDelegatorDelegations RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: delegator_addr + description: delegator_addr defines the delegator address to query for. + in: path + required: true + schema: + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + schema: + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + in: query + required: false + schema: + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + schema: + type: boolean + tags: + - gRPC Gateway API + "/cosmos/staking/v1beta1/delegators/{delegator_addr}/validators": + get: + summary: |- + DelegatorValidators queries all validators info for given delegator + address. + operationId: DelegatorValidators_FFS5U + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + validators: + type: array + items: + type: object + properties: + operator_address: + type: string + description: operator_address defines the address of the validator's operator; + bech encoded in JSON. + consensus_pubkey: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: consensus_pubkey is the consensus public key of the validator, as a + Protobuf Any. + jailed: + type: boolean + description: jailed defined whether the validator has been jailed from bonded + status or not. + status: + description: status is the validator status (bonded/unbonding/unbonded). + type: string + enum: + - BOND_STATUS_UNSPECIFIED + - BOND_STATUS_UNBONDED + - BOND_STATUS_UNBONDING + - BOND_STATUS_BONDED + default: BOND_STATUS_UNSPECIFIED + tokens: + type: string + description: tokens define the delegated tokens (incl. self-delegation). + delegator_shares: + type: string + description: delegator_shares defines total shares issued to a validator's + delegators. + description: + description: description defines the description terms for the validator. + type: object + properties: + moniker: + type: string + description: moniker defines a human-readable name for the validator. + identity: + type: string + description: identity defines an optional identity signature (ex. UPort or + Keybase). + website: + type: string + description: website defines an optional website link. + security_contact: + type: string + description: security_contact defines an optional email for security contact. + details: + type: string + description: details define other optional details. + unbonding_height: + type: string + format: int64 + description: unbonding_height defines, if unbonding, the height at which this + validator has begun unbonding. + unbonding_time: + type: string + format: date-time + description: unbonding_time defines, if unbonding, the min time for the + validator to complete unbonding. + commission: + description: commission defines the commission parameters. + type: object + properties: + commission_rates: + description: commission_rates defines the initial commission rates to be used + for creating a validator. + type: object + properties: + rate: + type: string + description: rate is the commission rate charged to delegators, as a fraction. + max_rate: + type: string + description: max_rate defines the maximum commission rate which validator can + ever charge, as a fraction. + max_change_rate: + type: string + description: max_change_rate defines the maximum daily increase of the validator + commission, as a fraction. + update_time: + type: string + format: date-time + description: update_time is the last time the commission rate was changed. + min_self_delegation: + type: string + description: min_self_delegation is the validator's self declared minimum self + delegation. + description: >- + Validator defines a validator, together with the total + amount of the + + Validator's bond shares and their exchange rate to coins. Slashing results in + + a decrease in the exchange rate, allowing correct calculation of future + + undelegations without iterating over delegators. When coins are delegated to + + this validator, the validator is credited with a delegation whose number of + + bond shares is based on the amount of coins delegated divided by the current + + exchange rate. Voting power can be calculated as total bonded shares + + multiplied by exchange rate. + description: validators defines the the validators' info of a delegator. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + QueryDelegatorValidatorsResponse is response type for the + Query/DelegatorValidators RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: delegator_addr + description: delegator_addr defines the delegator address to query for. + in: path + required: true + schema: + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + schema: + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + in: query + required: false + schema: + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + schema: + type: boolean + tags: + - gRPC Gateway API + "/cosmos/staking/v1beta1/delegators/{delegator_addr}/validators/{validator_addr}": + get: + summary: |- + DelegatorValidator queries validator info for given delegator validator + pair. + operationId: DelegatorValidator_0SMKH + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + validator: + type: object + properties: + operator_address: + type: string + description: operator_address defines the address of the validator's operator; + bech encoded in JSON. + consensus_pubkey: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: consensus_pubkey is the consensus public key of the validator, as a + Protobuf Any. + jailed: + type: boolean + description: jailed defined whether the validator has been jailed from bonded + status or not. + status: + description: status is the validator status (bonded/unbonding/unbonded). + type: string + enum: + - BOND_STATUS_UNSPECIFIED + - BOND_STATUS_UNBONDED + - BOND_STATUS_UNBONDING + - BOND_STATUS_BONDED + default: BOND_STATUS_UNSPECIFIED + tokens: + type: string + description: tokens define the delegated tokens (incl. self-delegation). + delegator_shares: + type: string + description: delegator_shares defines total shares issued to a validator's + delegators. + description: + description: description defines the description terms for the validator. + type: object + properties: + moniker: + type: string + description: moniker defines a human-readable name for the validator. + identity: + type: string + description: identity defines an optional identity signature (ex. UPort or + Keybase). + website: + type: string + description: website defines an optional website link. + security_contact: + type: string + description: security_contact defines an optional email for security contact. + details: + type: string + description: details define other optional details. + unbonding_height: + type: string + format: int64 + description: unbonding_height defines, if unbonding, the height at which this + validator has begun unbonding. + unbonding_time: + type: string + format: date-time + description: unbonding_time defines, if unbonding, the min time for the + validator to complete unbonding. + commission: + description: commission defines the commission parameters. + type: object + properties: + commission_rates: + description: commission_rates defines the initial commission rates to be used + for creating a validator. + type: object + properties: + rate: + type: string + description: rate is the commission rate charged to delegators, as a fraction. + max_rate: + type: string + description: max_rate defines the maximum commission rate which validator can + ever charge, as a fraction. + max_change_rate: + type: string + description: max_change_rate defines the maximum daily increase of the validator + commission, as a fraction. + update_time: + type: string + format: date-time + description: update_time is the last time the commission rate was changed. + min_self_delegation: + type: string + description: min_self_delegation is the validator's self declared minimum self + delegation. + description: >- + Validator defines a validator, together with the total + amount of the + + Validator's bond shares and their exchange rate to coins. Slashing results in + + a decrease in the exchange rate, allowing correct calculation of future + + undelegations without iterating over delegators. When coins are delegated to + + this validator, the validator is credited with a delegation whose number of + + bond shares is based on the amount of coins delegated divided by the current + + exchange rate. Voting power can be calculated as total bonded shares + + multiplied by exchange rate. + description: |- + QueryDelegatorValidatorResponse response type for the + Query/DelegatorValidator RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: delegator_addr + description: delegator_addr defines the delegator address to query for. + in: path + required: true + schema: + type: string + - name: validator_addr + description: validator_addr defines the validator address to query for. + in: path + required: true + schema: + type: string + tags: + - gRPC Gateway API + "/cosmos/staking/v1beta1/historical_info/{height}": + get: + summary: HistoricalInfo queries the historical info for given height. + operationId: HistoricalInfo_O3FQL + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + hist: + description: hist defines the historical info at the given height. + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for + processing a block in the blockchain, + + including all blockchain data structures and the rules of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + valset: + type: array + items: + type: object + properties: + operator_address: + type: string + description: operator_address defines the address of the validator's operator; + bech encoded in JSON. + consensus_pubkey: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: consensus_pubkey is the consensus public key of the validator, as a + Protobuf Any. + jailed: + type: boolean + description: jailed defined whether the validator has been jailed from bonded + status or not. + status: + description: status is the validator status (bonded/unbonding/unbonded). + type: string + enum: + - BOND_STATUS_UNSPECIFIED + - BOND_STATUS_UNBONDED + - BOND_STATUS_UNBONDING + - BOND_STATUS_BONDED + default: BOND_STATUS_UNSPECIFIED + tokens: + type: string + description: tokens define the delegated tokens (incl. self-delegation). + delegator_shares: + type: string + description: delegator_shares defines total shares issued to a validator's + delegators. + description: + description: description defines the description terms for the validator. + type: object + properties: + moniker: + type: string + description: moniker defines a human-readable name for the validator. + identity: + type: string + description: identity defines an optional identity signature (ex. UPort or + Keybase). + website: + type: string + description: website defines an optional website link. + security_contact: + type: string + description: security_contact defines an optional email for security contact. + details: + type: string + description: details define other optional details. + unbonding_height: + type: string + format: int64 + description: unbonding_height defines, if unbonding, the height at which this + validator has begun unbonding. + unbonding_time: + type: string + format: date-time + description: unbonding_time defines, if unbonding, the min time for the + validator to complete unbonding. + commission: + description: commission defines the commission parameters. + type: object + properties: + commission_rates: + description: commission_rates defines the initial commission rates to be used + for creating a validator. + type: object + properties: + rate: + type: string + description: rate is the commission rate charged to delegators, as a fraction. + max_rate: + type: string + description: max_rate defines the maximum commission rate which validator can + ever charge, as a fraction. + max_change_rate: + type: string + description: max_change_rate defines the maximum daily increase of the validator + commission, as a fraction. + update_time: + type: string + format: date-time + description: update_time is the last time the commission rate was changed. + min_self_delegation: + type: string + description: min_self_delegation is the validator's self declared minimum self + delegation. + description: >- + Validator defines a validator, together with the + total amount of the + + Validator's bond shares and their exchange rate to coins. Slashing results in + + a decrease in the exchange rate, allowing correct calculation of future + + undelegations without iterating over delegators. When coins are delegated to + + this validator, the validator is credited with a delegation whose number of + + bond shares is based on the amount of coins delegated divided by the current + + exchange rate. Voting power can be calculated as total bonded shares + + multiplied by exchange rate. + description: >- + QueryHistoricalInfoResponse is response type for the + Query/HistoricalInfo RPC + + method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: height + description: height defines at which height to query the historical info. + in: path + required: true + schema: + type: string + format: int64 + tags: + - gRPC Gateway API + /cosmos/staking/v1beta1/params: + get: + summary: Parameters queries the staking parameters. + operationId: Params_TU2U5 + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + params: + description: params holds all the parameters of this module. + type: object + properties: + unbonding_time: + type: string + description: unbonding_time is the time duration of unbonding. + max_validators: + type: integer + format: int64 + description: max_validators is the maximum number of validators. + max_entries: + type: integer + format: int64 + description: max_entries is the max entries for either unbonding delegation or + redelegation (per pair/trio). + historical_entries: + type: integer + format: int64 + description: historical_entries is the number of historical entries to persist. + bond_denom: + type: string + description: bond_denom defines the bondable coin denomination. + description: QueryParamsResponse is response type for the Query/Params RPC + method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + /cosmos/staking/v1beta1/pool: + get: + summary: Pool queries the pool info. + operationId: Pool_FDYA0 + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + pool: + description: pool defines the pool info. + type: object + properties: + not_bonded_tokens: + type: string + bonded_tokens: + type: string + description: QueryPoolResponse is response type for the Query/Pool RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + /cosmos/staking/v1beta1/validators: + get: + summary: Validators queries all validators that match the given status. + operationId: Validators_O6IYI + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + validators: + type: array + items: + type: object + properties: + operator_address: + type: string + description: operator_address defines the address of the validator's operator; + bech encoded in JSON. + consensus_pubkey: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: consensus_pubkey is the consensus public key of the validator, as a + Protobuf Any. + jailed: + type: boolean + description: jailed defined whether the validator has been jailed from bonded + status or not. + status: + description: status is the validator status (bonded/unbonding/unbonded). + type: string + enum: + - BOND_STATUS_UNSPECIFIED + - BOND_STATUS_UNBONDED + - BOND_STATUS_UNBONDING + - BOND_STATUS_BONDED + default: BOND_STATUS_UNSPECIFIED + tokens: + type: string + description: tokens define the delegated tokens (incl. self-delegation). + delegator_shares: + type: string + description: delegator_shares defines total shares issued to a validator's + delegators. + description: + description: description defines the description terms for the validator. + type: object + properties: + moniker: + type: string + description: moniker defines a human-readable name for the validator. + identity: + type: string + description: identity defines an optional identity signature (ex. UPort or + Keybase). + website: + type: string + description: website defines an optional website link. + security_contact: + type: string + description: security_contact defines an optional email for security contact. + details: + type: string + description: details define other optional details. + unbonding_height: + type: string + format: int64 + description: unbonding_height defines, if unbonding, the height at which this + validator has begun unbonding. + unbonding_time: + type: string + format: date-time + description: unbonding_time defines, if unbonding, the min time for the + validator to complete unbonding. + commission: + description: commission defines the commission parameters. + type: object + properties: + commission_rates: + description: commission_rates defines the initial commission rates to be used + for creating a validator. + type: object + properties: + rate: + type: string + description: rate is the commission rate charged to delegators, as a fraction. + max_rate: + type: string + description: max_rate defines the maximum commission rate which validator can + ever charge, as a fraction. + max_change_rate: + type: string + description: max_change_rate defines the maximum daily increase of the validator + commission, as a fraction. + update_time: + type: string + format: date-time + description: update_time is the last time the commission rate was changed. + min_self_delegation: + type: string + description: min_self_delegation is the validator's self declared minimum self + delegation. + description: >- + Validator defines a validator, together with the total + amount of the + + Validator's bond shares and their exchange rate to coins. Slashing results in + + a decrease in the exchange rate, allowing correct calculation of future + + undelegations without iterating over delegators. When coins are delegated to + + this validator, the validator is credited with a delegation whose number of + + bond shares is based on the amount of coins delegated divided by the current + + exchange rate. Voting power can be calculated as total bonded shares + + multiplied by exchange rate. + description: validators contains all the queried validators. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + title: QueryValidatorsResponse is response type for the Query/Validators RPC + method + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: status + description: status enables to query for validators matching a given status. + in: query + required: false + schema: + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + schema: + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + in: query + required: false + schema: + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + schema: + type: boolean + tags: + - gRPC Gateway API + "/cosmos/staking/v1beta1/validators/{validator_addr}": + get: + summary: Validator queries validator info for given validator address. + operationId: Validator_R6NYA + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + validator: + type: object + properties: + operator_address: + type: string + description: operator_address defines the address of the validator's operator; + bech encoded in JSON. + consensus_pubkey: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: consensus_pubkey is the consensus public key of the validator, as a + Protobuf Any. + jailed: + type: boolean + description: jailed defined whether the validator has been jailed from bonded + status or not. + status: + description: status is the validator status (bonded/unbonding/unbonded). + type: string + enum: + - BOND_STATUS_UNSPECIFIED + - BOND_STATUS_UNBONDED + - BOND_STATUS_UNBONDING + - BOND_STATUS_BONDED + default: BOND_STATUS_UNSPECIFIED + tokens: + type: string + description: tokens define the delegated tokens (incl. self-delegation). + delegator_shares: + type: string + description: delegator_shares defines total shares issued to a validator's + delegators. + description: + description: description defines the description terms for the validator. + type: object + properties: + moniker: + type: string + description: moniker defines a human-readable name for the validator. + identity: + type: string + description: identity defines an optional identity signature (ex. UPort or + Keybase). + website: + type: string + description: website defines an optional website link. + security_contact: + type: string + description: security_contact defines an optional email for security contact. + details: + type: string + description: details define other optional details. + unbonding_height: + type: string + format: int64 + description: unbonding_height defines, if unbonding, the height at which this + validator has begun unbonding. + unbonding_time: + type: string + format: date-time + description: unbonding_time defines, if unbonding, the min time for the + validator to complete unbonding. + commission: + description: commission defines the commission parameters. + type: object + properties: + commission_rates: + description: commission_rates defines the initial commission rates to be used + for creating a validator. + type: object + properties: + rate: + type: string + description: rate is the commission rate charged to delegators, as a fraction. + max_rate: + type: string + description: max_rate defines the maximum commission rate which validator can + ever charge, as a fraction. + max_change_rate: + type: string + description: max_change_rate defines the maximum daily increase of the validator + commission, as a fraction. + update_time: + type: string + format: date-time + description: update_time is the last time the commission rate was changed. + min_self_delegation: + type: string + description: min_self_delegation is the validator's self declared minimum self + delegation. + description: >- + Validator defines a validator, together with the total + amount of the + + Validator's bond shares and their exchange rate to coins. Slashing results in + + a decrease in the exchange rate, allowing correct calculation of future + + undelegations without iterating over delegators. When coins are delegated to + + this validator, the validator is credited with a delegation whose number of + + bond shares is based on the amount of coins delegated divided by the current + + exchange rate. Voting power can be calculated as total bonded shares + + multiplied by exchange rate. + title: QueryValidatorResponse is response type for the Query/Validator RPC + method + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: validator_addr + description: validator_addr defines the validator address to query for. + in: path + required: true + schema: + type: string + tags: + - gRPC Gateway API + "/cosmos/staking/v1beta1/validators/{validator_addr}/delegations": + get: + summary: ValidatorDelegations queries delegate info for given validator. + operationId: ValidatorDelegations_I8DQT + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + delegation_responses: + type: array + items: + type: object + properties: + delegation: + type: object + properties: + delegator_address: + type: string + description: delegator_address is the bech32-encoded address of the delegator. + validator_address: + type: string + description: validator_address is the bech32-encoded address of the validator. + shares: + type: string + description: shares define the delegation shares received. + description: >- + Delegation represents the bond with tokens held by + an account. It is + + owned by one delegator, and is associated with the voting power of one + + validator. + balance: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an + amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + description: >- + DelegationResponse is equivalent to Delegation except + that it contains a + + balance in addition to shares which is more suitable for client responses. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + title: |- + QueryValidatorDelegationsResponse is response type for the + Query/ValidatorDelegations RPC method + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: validator_addr + description: validator_addr defines the validator address to query for. + in: path + required: true + schema: + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + schema: + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + in: query + required: false + schema: + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + schema: + type: boolean + tags: + - gRPC Gateway API + "/cosmos/staking/v1beta1/validators/{validator_addr}/delegations/{delegator_addr}": + get: + summary: Delegation queries delegate info for given validator delegator pair. + operationId: Delegation_SRG3Q + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + delegation_response: + type: object + properties: + delegation: + type: object + properties: + delegator_address: + type: string + description: delegator_address is the bech32-encoded address of the delegator. + validator_address: + type: string + description: validator_address is the bech32-encoded address of the validator. + shares: + type: string + description: shares define the delegation shares received. + description: >- + Delegation represents the bond with tokens held by an + account. It is + + owned by one delegator, and is associated with the voting power of one + + validator. + balance: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an + amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + description: >- + DelegationResponse is equivalent to Delegation except that + it contains a + + balance in addition to shares which is more suitable for client responses. + description: QueryDelegationResponse is response type for the Query/Delegation + RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: validator_addr + description: validator_addr defines the validator address to query for. + in: path + required: true + schema: + type: string + - name: delegator_addr + description: delegator_addr defines the delegator address to query for. + in: path + required: true + schema: + type: string + tags: + - gRPC Gateway API + "/cosmos/staking/v1beta1/validators/{validator_addr}/delegations/{delegator_addr}/unbonding_delegation": + get: + summary: |- + UnbondingDelegation queries unbonding info for given validator delegator + pair. + operationId: UnbondingDelegation_TWCOS + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + unbond: + type: object + properties: + delegator_address: + type: string + description: delegator_address is the bech32-encoded address of the delegator. + validator_address: + type: string + description: validator_address is the bech32-encoded address of the validator. + entries: + type: array + items: + type: object + properties: + creation_height: + type: string + format: int64 + description: creation_height is the height which the unbonding took place. + completion_time: + type: string + format: date-time + description: completion_time is the unix time for unbonding completion. + initial_balance: + type: string + description: initial_balance defines the tokens initially scheduled to receive + at completion. + balance: + type: string + description: balance defines the tokens to receive at completion. + description: UnbondingDelegationEntry defines an unbonding object with relevant + metadata. + description: entries are the unbonding delegation entries. + description: >- + UnbondingDelegation stores all of a single delegator's + unbonding bonds + + for a single validator in an time-ordered list. + description: >- + QueryDelegationResponse is response type for the + Query/UnbondingDelegation + + RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: validator_addr + description: validator_addr defines the validator address to query for. + in: path + required: true + schema: + type: string + - name: delegator_addr + description: delegator_addr defines the delegator address to query for. + in: path + required: true + schema: + type: string + tags: + - gRPC Gateway API + "/cosmos/staking/v1beta1/validators/{validator_addr}/unbonding_delegations": + get: + summary: ValidatorUnbondingDelegations queries unbonding delegations of a + validator. + operationId: ValidatorUnbondingDelegations_94HKV + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + unbonding_responses: + type: array + items: + type: object + properties: + delegator_address: + type: string + description: delegator_address is the bech32-encoded address of the delegator. + validator_address: + type: string + description: validator_address is the bech32-encoded address of the validator. + entries: + type: array + items: + type: object + properties: + creation_height: + type: string + format: int64 + description: creation_height is the height which the unbonding took place. + completion_time: + type: string + format: date-time + description: completion_time is the unix time for unbonding completion. + initial_balance: + type: string + description: initial_balance defines the tokens initially scheduled to receive + at completion. + balance: + type: string + description: balance defines the tokens to receive at completion. + description: UnbondingDelegationEntry defines an unbonding object with relevant + metadata. + description: entries are the unbonding delegation entries. + description: >- + UnbondingDelegation stores all of a single delegator's + unbonding bonds + + for a single validator in an time-ordered list. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryValidatorUnbondingDelegationsResponse is response type + for the + + Query/ValidatorUnbondingDelegations RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: validator_addr + description: validator_addr defines the validator address to query for. + in: path + required: true + schema: + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + schema: + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + in: query + required: false + schema: + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + schema: + type: boolean + tags: + - gRPC Gateway API + /cosmos/base/tendermint/v1beta1/blocks/latest: + get: + summary: GetLatestBlock returns the latest block. + operationId: GetLatestBlock_4NXGP + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + block: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for + processing a block in the blockchain, + + including all blockchain data structures and the rules of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + data: + type: object + properties: + txs: + type: array + items: + type: string + format: byte + description: >- + Txs that will be applied by state @ + block.Height+1. + + NOTE: not all txs here are valid. We're just agreeing on the order first. + + This means that block.AppHash does not include these txs. + title: Data contains the set of transactions included in the block + evidence: + type: object + properties: + evidence: + type: array + items: + type: object + properties: + duplicate_vote_evidence: + type: object + properties: + vote_a: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: >- + SignedMsgType is a type of signed + message in the consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or + commit vote from validators for + + consensus. + vote_b: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: >- + SignedMsgType is a type of signed + message in the consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or + commit vote from validators for + + consensus. + total_voting_power: + type: string + format: int64 + validator_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: DuplicateVoteEvidence contains evidence of a validator signed two + conflicting votes. + light_client_attack_evidence: + type: object + properties: + conflicting_block: + type: object + properties: + signed_header: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the + consensus rules for + processing a block in the + blockchain, + + including all blockchain data structures and the rules of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: BlockIdFlag indicates which BlcokID the signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: CommitSig is a part of the Vote included in a Commit. + description: Commit contains the evidence that a block was committed by a set of + validators. + validator_set: + type: object + properties: + validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + proposer: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + common_height: + type: string + format: int64 + byzantine_validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: LightClientAttackEvidence contains evidence of a set of validators + attempting to mislead a light client. + last_commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: BlockIdFlag indicates which BlcokID the signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: CommitSig is a part of the Vote included in a Commit. + description: Commit contains the evidence that a block was committed by a set of + validators. + description: GetLatestBlockResponse is the response type for the + Query/GetLatestBlock RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + "/cosmos/base/tendermint/v1beta1/blocks/{height}": + get: + summary: GetBlockByHeight queries block for given height. + operationId: GetBlockByHeight_HXFY4 + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + block: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for + processing a block in the blockchain, + + including all blockchain data structures and the rules of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + data: + type: object + properties: + txs: + type: array + items: + type: string + format: byte + description: >- + Txs that will be applied by state @ + block.Height+1. + + NOTE: not all txs here are valid. We're just agreeing on the order first. + + This means that block.AppHash does not include these txs. + title: Data contains the set of transactions included in the block + evidence: + type: object + properties: + evidence: + type: array + items: + type: object + properties: + duplicate_vote_evidence: + type: object + properties: + vote_a: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: >- + SignedMsgType is a type of signed + message in the consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or + commit vote from validators for + + consensus. + vote_b: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: >- + SignedMsgType is a type of signed + message in the consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or + commit vote from validators for + + consensus. + total_voting_power: + type: string + format: int64 + validator_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: DuplicateVoteEvidence contains evidence of a validator signed two + conflicting votes. + light_client_attack_evidence: + type: object + properties: + conflicting_block: + type: object + properties: + signed_header: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the + consensus rules for + processing a block in the + blockchain, + + including all blockchain data structures and the rules of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: BlockIdFlag indicates which BlcokID the signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: CommitSig is a part of the Vote included in a Commit. + description: Commit contains the evidence that a block was committed by a set of + validators. + validator_set: + type: object + properties: + validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + proposer: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + common_height: + type: string + format: int64 + byzantine_validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: LightClientAttackEvidence contains evidence of a set of validators + attempting to mislead a light client. + last_commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: BlockIdFlag indicates which BlcokID the signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: CommitSig is a part of the Vote included in a Commit. + description: Commit contains the evidence that a block was committed by a set of + validators. + description: GetBlockByHeightResponse is the response type for the + Query/GetBlockByHeight RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: height + in: path + required: true + schema: + type: string + format: int64 + tags: + - gRPC Gateway API + /cosmos/base/tendermint/v1beta1/node_info: + get: + summary: GetNodeInfo queries the current node info. + operationId: GetNodeInfo_39H2U + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + default_node_info: + type: object + properties: + protocol_version: + type: object + properties: + p2p: + type: string + format: uint64 + block: + type: string + format: uint64 + app: + type: string + format: uint64 + default_node_id: + type: string + listen_addr: + type: string + network: + type: string + version: + type: string + channels: + type: string + format: byte + moniker: + type: string + other: + type: object + properties: + tx_index: + type: string + rpc_address: + type: string + application_version: + type: object + properties: + name: + type: string + app_name: + type: string + version: + type: string + git_commit: + type: string + build_tags: + type: string + go_version: + type: string + build_deps: + type: array + items: + type: object + properties: + path: + type: string + title: module path + version: + type: string + title: module version + sum: + type: string + title: checksum + title: Module is the type for VersionInfo + cosmos_sdk_version: + type: string + title: "Since: cosmos-sdk 0.43" + description: VersionInfo is the type for the GetNodeInfoResponse message. + description: GetNodeInfoResponse is the request type for the Query/GetNodeInfo + RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + /cosmos/base/tendermint/v1beta1/syncing: + get: + summary: GetSyncing queries node syncing. + operationId: GetSyncing_55ZJD + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + syncing: + type: boolean + description: GetSyncingResponse is the response type for the Query/GetSyncing + RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + /cosmos/base/tendermint/v1beta1/validatorsets/latest: + get: + summary: GetLatestValidatorSet queries latest validator-set. + operationId: GetLatestValidatorSet_WCLGL + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + block_height: + type: string + format: int64 + validators: + type: array + items: + type: object + properties: + address: + type: string + pub_key: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + description: Validator is the type for the validator-set. + pagination: + description: pagination defines an pagination for the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: GetLatestValidatorSetResponse is the response type for the + Query/GetValidatorSetByHeight RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + schema: + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + in: query + required: false + schema: + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + schema: + type: boolean + tags: + - gRPC Gateway API + "/cosmos/base/tendermint/v1beta1/validatorsets/{height}": + get: + summary: GetValidatorSetByHeight queries validator-set at a given height. + operationId: GetValidatorSetByHeight_ODLV8 + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + block_height: + type: string + format: int64 + validators: + type: array + items: + type: object + properties: + address: + type: string + pub_key: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + description: Validator is the type for the validator-set. + pagination: + description: pagination defines an pagination for the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: GetValidatorSetByHeightResponse is the response type for the + Query/GetValidatorSetByHeight RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: height + in: path + required: true + schema: + type: string + format: int64 + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + schema: + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + in: query + required: false + schema: + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + schema: + type: boolean + tags: + - gRPC Gateway API + /ibc/apps/router/v1/params: + get: + summary: Params queries all parameters of the router module. + operationId: Params_TM71K + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + params: + description: params defines the parameters of the module. + type: object + properties: + fee_percentage: + type: string + description: QueryParamsResponse is the response type for the Query/Params RPC + method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + get: + summary: >- + Params defines a gRPC query method that returns the tokenfactory + module's + + parameters. + operationId: Params_QYV5K + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + params: + description: params defines the parameters of the module. + type: object + properties: + denom_creation_fee: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an + amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + denom_creation_gas_consume: + type: string + format: uint64 + title: >- + if denom_creation_fee is an empty array, then this + field is used to add more gas consumption + + to the base cost. + + https://github.com/CosmWasm/token-factory/issues/11 + description: QueryParamsResponse is the response type for the Query/Params RPC + method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + /cosmos/distribution/v1beta1/community_pool: + get: + summary: CommunityPool queries the community pool coins. + operationId: CommunityPool_YZRL4 + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + pool: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + DecCoin defines a token with a denomination and a + decimal amount. + + + NOTE: The amount field is an Dec which implements the custom method + + signatures required by gogoproto. + description: pool defines community pool's coins. + description: >- + QueryCommunityPoolResponse is the response type for the + Query/CommunityPool + + RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + "/cosmos/distribution/v1beta1/delegators/{delegator_address}/rewards": + get: + summary: |- + DelegationTotalRewards queries the total rewards accrued by a each + validator. + operationId: DelegationTotalRewards_YOCPA + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + rewards: + type: array + items: + type: object + properties: + validator_address: + type: string + reward: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + DecCoin defines a token with a denomination and a + decimal amount. + + + NOTE: The amount field is an Dec which implements the custom method + + signatures required by gogoproto. + description: |- + DelegationDelegatorReward represents the properties + of a delegator's delegation reward. + description: rewards defines all the rewards accrued by a delegator. + total: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + DecCoin defines a token with a denomination and a + decimal amount. + + + NOTE: The amount field is an Dec which implements the custom method + + signatures required by gogoproto. + description: total defines the sum of all the rewards. + description: >- + QueryDelegationTotalRewardsResponse is the response type for + the + + Query/DelegationTotalRewards RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: delegator_address + description: delegator_address defines the delegator address to query for. + in: path + required: true + schema: + type: string + tags: + - gRPC Gateway API + "/cosmos/distribution/v1beta1/delegators/{delegator_address}/rewards/{validator_address}": + get: + summary: DelegationRewards queries the total rewards accrued by a delegation. + operationId: DelegationRewards_I3GH0 + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + rewards: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + DecCoin defines a token with a denomination and a + decimal amount. + + + NOTE: The amount field is an Dec which implements the custom method + + signatures required by gogoproto. + description: rewards defines the rewards accrued by a delegation. + description: |- + QueryDelegationRewardsResponse is the response type for the + Query/DelegationRewards RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: delegator_address + description: delegator_address defines the delegator address to query for. + in: path + required: true + schema: + type: string + - name: validator_address + description: validator_address defines the validator address to query for. + in: path + required: true + schema: + type: string + tags: + - gRPC Gateway API + "/cosmos/distribution/v1beta1/delegators/{delegator_address}/validators": + get: + summary: DelegatorValidators queries the validators of a delegator. + operationId: DelegatorValidators_07SCO + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + validators: + type: array + items: + type: string + description: validators defines the validators a delegator is delegating for. + description: |- + QueryDelegatorValidatorsResponse is the response type for the + Query/DelegatorValidators RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: delegator_address + description: delegator_address defines the delegator address to query for. + in: path + required: true + schema: + type: string + tags: + - gRPC Gateway API + "/cosmos/distribution/v1beta1/delegators/{delegator_address}/withdraw_address": + get: + summary: DelegatorWithdrawAddress queries withdraw address of a delegator. + operationId: DelegatorWithdrawAddress_BFZZ2 + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + withdraw_address: + type: string + description: withdraw_address defines the delegator address to query for. + description: >- + QueryDelegatorWithdrawAddressResponse is the response type for + the + + Query/DelegatorWithdrawAddress RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: delegator_address + description: delegator_address defines the delegator address to query for. + in: path + required: true + schema: + type: string + tags: + - gRPC Gateway API + /cosmos/distribution/v1beta1/params: + get: + summary: Params queries params of the distribution module. + operationId: Params_KNUQO + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + params: + description: params defines the parameters of the module. + type: object + properties: + community_tax: + type: string + base_proposer_reward: + type: string + bonus_proposer_reward: + type: string + withdraw_addr_enabled: + type: boolean + description: QueryParamsResponse is the response type for the Query/Params RPC + method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + "/cosmos/distribution/v1beta1/validators/{validator_address}/commission": + get: + summary: ValidatorCommission queries accumulated commission for a validator. + operationId: ValidatorCommission_YRRRF + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + commission: + description: commission defines the commision the validator received. + type: object + properties: + commission: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + DecCoin defines a token with a denomination and a + decimal amount. + + + NOTE: The amount field is an Dec which implements the custom method + + signatures required by gogoproto. + title: |- + QueryValidatorCommissionResponse is the response type for the + Query/ValidatorCommission RPC method + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: validator_address + description: validator_address defines the validator address to query for. + in: path + required: true + schema: + type: string + tags: + - gRPC Gateway API + "/cosmos/distribution/v1beta1/validators/{validator_address}/outstanding_rewards": + get: + summary: ValidatorOutstandingRewards queries rewards of a validator address. + operationId: ValidatorOutstandingRewards_JG6R4 + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + rewards: + type: object + properties: + rewards: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + DecCoin defines a token with a denomination and a + decimal amount. + + + NOTE: The amount field is an Dec which implements the custom method + + signatures required by gogoproto. + description: >- + ValidatorOutstandingRewards represents outstanding + (un-withdrawn) rewards + + for a validator inexpensive to track, allows simple sanity checks. + description: >- + QueryValidatorOutstandingRewardsResponse is the response type + for the + + Query/ValidatorOutstandingRewards RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: validator_address + description: validator_address defines the validator address to query for. + in: path + required: true + schema: + type: string + tags: + - gRPC Gateway API + "/cosmos/distribution/v1beta1/validators/{validator_address}/slashes": + get: + summary: ValidatorSlashes queries slash events of a validator. + operationId: ValidatorSlashes_O4Z2G + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + slashes: + type: array + items: + type: object + properties: + validator_period: + type: string + format: uint64 + fraction: + type: string + description: >- + ValidatorSlashEvent represents a validator slash event. + + Height is implicit within the store key. + + This is needed to calculate appropriate amount of staking tokens + + for delegations which are withdrawn after a slash has occurred. + description: slashes defines the slashes the validator received. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + QueryValidatorSlashesResponse is the response type for the + Query/ValidatorSlashes RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: validator_address + description: validator_address defines the validator address to query for. + in: path + required: true + schema: + type: string + - name: starting_height + description: starting_height defines the optional starting height to query the + slashes. + in: query + required: false + schema: + type: string + format: uint64 + - name: ending_height + description: starting_height defines the optional ending height to query the + slashes. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + schema: + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + in: query + required: false + schema: + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + schema: + type: boolean + tags: + - gRPC Gateway API + /cosmos/tx/v1beta1/simulate: + post: + summary: Simulate simulates executing a transaction for estimating gas usage. + operationId: Simulate_OQQOZ + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + gas_info: + description: gas_info is the information about gas used in the simulation. + type: object + properties: + gas_wanted: + type: string + format: uint64 + description: GasWanted is the maximum units of work we allow this tx to perform. + gas_used: + type: string + format: uint64 + description: GasUsed is the amount of gas actually consumed. + result: + description: result is the result of the simulation. + type: object + properties: + data: + type: string + format: byte + description: >- + Data is any data returned from message or handler + execution. It MUST be + + length prefixed in order to separate data from multiple message executions. + log: + type: string + description: Log contains the log information from message or handler execution. + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + format: byte + value: + type: string + format: byte + index: + type: boolean + description: EventAttribute is a single key-value pair, associated with an + event. + description: >- + Event allows application developers to attach + additional information to + + ResponseBeginBlock, ResponseEndBlock, ResponseCheckTx and ResponseDeliverTx. + + Later, transactions may be queried using these events. + description: >- + Events contains a slice of Event objects that were + emitted during message + + or handler execution. + description: |- + SimulateResponse is the response type for the + Service.SimulateRPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + requestBody: + content: + application/json: + schema: + type: object + properties: + tx: + description: |- + tx is the transaction to simulate. + Deprecated. Send raw tx bytes instead. + type: object + properties: + body: + title: body is the processable content of the transaction + type: object + properties: + messages: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + messages is a list of messages to be executed. The + required signers of + + those messages define the number and order of elements in AuthInfo's + + signer_infos and Tx's signatures. Each required signer address is added to + + the list only the first time it occurs. + + By convention, the first required signer (usually from the first message) + + is referred to as the primary signer and pays the fee for the whole + + transaction. + memo: + type: string + description: >- + memo is any arbitrary note/comment to be added to + the transaction. + + WARNING: in clients, any publicly exposed text should not be called memo, + + but should be called `note` instead (see https://github.com/cosmos/cosmos-sdk/issues/9122). + timeout_height: + type: string + format: uint64 + title: >- + timeout is the block height after which this + transaction will not + + be processed by the chain + extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be + added by chains + + when the default options are not sufficient. If any of these are present + + and can't be handled, the transaction will be rejected + non_critical_extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be + added by chains + + when the default options are not sufficient. If any of these are present + + and can't be handled, they will be ignored + description: TxBody is the body of a transaction that all signers sign over. + auth_info: + title: >- + auth_info is the authorization related content of the + transaction, + + specifically signers, signer modes and fee + type: object + properties: + signer_infos: + type: array + items: + type: object + properties: + public_key: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + public_key is the public key of the signer. It + is optional for accounts + + that already exist in state. If unset, the verifier can use the required \ + + signer address for this position and lookup the public key. + mode_info: + title: >- + mode_info describes the signing mode of the + signer and is a nested + + structure to support nested multisig pubkey's + type: object + properties: + single: + title: single represents a single signer + type: object + properties: + mode: + title: mode is the signing mode of the single signer + type: string + enum: + - SIGN_MODE_UNSPECIFIED + - SIGN_MODE_DIRECT + - SIGN_MODE_TEXTUAL + - SIGN_MODE_LEGACY_AMINO_JSON + - SIGN_MODE_EIP_191 + default: SIGN_MODE_UNSPECIFIED + description: >- + SignMode represents a signing mode + with its own security guarantees. + + - SIGN_MODE_UNSPECIFIED: SIGN_MODE_UNSPECIFIED specifies an unknown signing mode and will be + rejected + - SIGN_MODE_DIRECT: SIGN_MODE_DIRECT specifies a signing mode which uses SignDoc and is + verified with raw bytes from Tx + - SIGN_MODE_TEXTUAL: SIGN_MODE_TEXTUAL is a future signing mode that will verify some + human-readable textual representation on top of the binary representation + + from SIGN_MODE_DIRECT + - SIGN_MODE_LEGACY_AMINO_JSON: SIGN_MODE_LEGACY_AMINO_JSON is a backwards compatibility mode which uses + Amino JSON and will be removed in the future + - SIGN_MODE_EIP_191: SIGN_MODE_EIP_191 specifies the sign mode for EIP 191 signing on the Cosmos + SDK. Ref: https://eips.ethereum.org/EIPS/eip-191 + + + Currently, SIGN_MODE_EIP_191 is registered as a SignMode enum variant, + + but is not implemented on the SDK by default. To enable EIP-191, you need + + to pass a custom `TxConfig` that has an implementation of + + `SignModeHandler` for EIP-191. The SDK may decide to fully support + + EIP-191 in the future. + + + Since: cosmos-sdk 0.45.2 + multi: + title: multi represents a nested multisig signer + type: object + properties: + bitarray: + title: bitarray specifies which keys within the multisig are signing + type: object + properties: + extra_bits_stored: + type: integer + format: int64 + elems: + type: string + format: byte + description: >- + CompactBitArray is an implementation + of a space efficient bit array. + + This is used to ensure that the encoded data takes up a minimal amount of + + space after proto encoding. + + This is not thread safe, and is not intended for concurrent usage. + mode_infos: + type: array + items: {} + title: >- + mode_infos is the corresponding modes + of the signers of the multisig + + which could include nested multisig public keys + description: ModeInfo describes the signing mode of a single or nested multisig + signer. + sequence: + type: string + format: uint64 + description: >- + sequence is the sequence of the account, which + describes the + + number of committed transactions signed by a given address. It is used to + + prevent replay attacks. + description: >- + SignerInfo describes the public key and signing + mode of a single top-level + + signer. + description: >- + signer_infos defines the signing modes for the + required signers. The number + + and order of elements must match the required signers from TxBody's + + messages. The first element is the primary signer and the one which pays + + the fee. + fee: + description: >- + Fee is the fee and gas limit for the transaction. + The first signer is the + + primary signer and the one which pays the fee. The fee can be calculated + + based on the cost of evaluating the body and doing signature verification + + of the signers. This can be estimated via simulation. + type: object + properties: + amount: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and + an amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + title: amount is the amount of coins to be paid as a fee + gas_limit: + type: string + format: uint64 + title: >- + gas_limit is the maximum gas that can be used in + transaction processing + + before an out of gas error occurs + payer: + type: string + description: >- + if unset, the first signer is responsible for + paying the fees. If set, the specified account + must pay the fees. + + the payer must be a tx signer (and thus have signed this field in AuthInfo). + + setting this field does *not* change the ordering of required signers for the transaction. + granter: + type: string + title: >- + if set, the fee payer (either the first signer + or the value of the payer field) requests that a + fee grant be used + + to pay fees instead of the fee payer's own balance. If an appropriate fee grant does not exist or the chain does + + not support fee grants, this will fail + description: >- + AuthInfo describes the fee and signer modes that are + used to sign a + + transaction. + signatures: + type: array + items: + type: string + format: byte + description: >- + signatures is a list of signatures that matches the + length and order of + + AuthInfo's signer_infos to allow connecting signature meta information like + + public key and signing mode by position. + tx_bytes: + type: string + format: byte + description: |- + tx_bytes is the raw transaction. + + Since: cosmos-sdk 0.43 + description: |- + SimulateRequest is the request type for the Service.Simulate + RPC method. + required: true + tags: + - gRPC Gateway API + /cosmos/tx/v1beta1/txs: + get: + summary: GetTxsEvent fetches txs by event. + operationId: GetTxsEvent_PUNXQ + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + txs: + type: array + items: + type: object + properties: + body: + title: body is the processable content of the transaction + type: object + properties: + messages: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + messages is a list of messages to be executed. + The required signers of + + those messages define the number and order of elements in AuthInfo's + + signer_infos and Tx's signatures. Each required signer address is added to + + the list only the first time it occurs. + + By convention, the first required signer (usually from the first message) + + is referred to as the primary signer and pays the fee for the whole + + transaction. + memo: + type: string + description: >- + memo is any arbitrary note/comment to be added + to the transaction. + + WARNING: in clients, any publicly exposed text should not be called memo, + + but should be called `note` instead (see https://github.com/cosmos/cosmos-sdk/issues/9122). + timeout_height: + type: string + format: uint64 + title: >- + timeout is the block height after which this + transaction will not + + be processed by the chain + extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can + be added by chains + + when the default options are not sufficient. If any of these are present + + and can't be handled, the transaction will be rejected + non_critical_extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can + be added by chains + + when the default options are not sufficient. If any of these are present + + and can't be handled, they will be ignored + description: TxBody is the body of a transaction that all signers sign over. + auth_info: + title: >- + auth_info is the authorization related content of + the transaction, + + specifically signers, signer modes and fee + type: object + properties: + signer_infos: + type: array + items: + type: object + properties: + public_key: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + public_key is the public key of the + signer. It is optional for accounts + + that already exist in state. If unset, the verifier can use the required \ + + signer address for this position and lookup the public key. + mode_info: + title: >- + mode_info describes the signing mode of + the signer and is a nested + + structure to support nested multisig pubkey's + type: object + properties: + single: + title: single represents a single signer + type: object + properties: + mode: + title: mode is the signing mode of the single signer + type: string + enum: + - SIGN_MODE_UNSPECIFIED + - SIGN_MODE_DIRECT + - SIGN_MODE_TEXTUAL + - SIGN_MODE_LEGACY_AMINO_JSON + - SIGN_MODE_EIP_191 + default: SIGN_MODE_UNSPECIFIED + description: >- + SignMode represents a signing mode + with its own security guarantees. + + - SIGN_MODE_UNSPECIFIED: SIGN_MODE_UNSPECIFIED specifies an unknown signing mode and will be + rejected + - SIGN_MODE_DIRECT: SIGN_MODE_DIRECT specifies a signing mode which uses SignDoc and is + verified with raw bytes from Tx + - SIGN_MODE_TEXTUAL: SIGN_MODE_TEXTUAL is a future signing mode that will verify some + human-readable textual representation on top of the binary representation + + from SIGN_MODE_DIRECT + - SIGN_MODE_LEGACY_AMINO_JSON: SIGN_MODE_LEGACY_AMINO_JSON is a backwards compatibility mode which uses + Amino JSON and will be removed in the future + - SIGN_MODE_EIP_191: SIGN_MODE_EIP_191 specifies the sign mode for EIP 191 signing on the Cosmos + SDK. Ref: https://eips.ethereum.org/EIPS/eip-191 + + + Currently, SIGN_MODE_EIP_191 is registered as a SignMode enum variant, + + but is not implemented on the SDK by default. To enable EIP-191, you need + + to pass a custom `TxConfig` that has an implementation of + + `SignModeHandler` for EIP-191. The SDK may decide to fully support + + EIP-191 in the future. + + + Since: cosmos-sdk 0.45.2 + multi: + title: multi represents a nested multisig signer + type: object + properties: + bitarray: + title: bitarray specifies which keys within the multisig are signing + type: object + properties: + extra_bits_stored: + type: integer + format: int64 + elems: + type: string + format: byte + description: >- + CompactBitArray is an + implementation of a space + efficient bit array. + + This is used to ensure that the encoded data takes up a minimal amount of + + space after proto encoding. + + This is not thread safe, and is not intended for concurrent usage. + mode_infos: + type: array + items: {} + title: >- + mode_infos is the corresponding + modes of the signers of the + multisig + + which could include nested multisig public keys + description: ModeInfo describes the signing mode of a single or nested multisig + signer. + sequence: + type: string + format: uint64 + description: >- + sequence is the sequence of the account, + which describes the + + number of committed transactions signed by a given address. It is used to + + prevent replay attacks. + description: >- + SignerInfo describes the public key and + signing mode of a single top-level + + signer. + description: >- + signer_infos defines the signing modes for the + required signers. The number + + and order of elements must match the required signers from TxBody's + + messages. The first element is the primary signer and the one which pays + + the fee. + fee: + description: >- + Fee is the fee and gas limit for the + transaction. The first signer is the + + primary signer and the one which pays the fee. The fee can be calculated + + based on the cost of evaluating the body and doing signature verification + + of the signers. This can be estimated via simulation. + type: object + properties: + amount: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination + and an amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + title: amount is the amount of coins to be paid as a fee + gas_limit: + type: string + format: uint64 + title: >- + gas_limit is the maximum gas that can be + used in transaction processing + + before an out of gas error occurs + payer: + type: string + description: >- + if unset, the first signer is responsible + for paying the fees. If set, the specified + account must pay the fees. + + the payer must be a tx signer (and thus have signed this field in AuthInfo). + + setting this field does *not* change the ordering of required signers for the transaction. + granter: + type: string + title: >- + if set, the fee payer (either the first + signer or the value of the payer field) + requests that a fee grant be used + + to pay fees instead of the fee payer's own balance. If an appropriate fee grant does not exist or the chain does + + not support fee grants, this will fail + description: >- + AuthInfo describes the fee and signer modes that are + used to sign a + + transaction. + signatures: + type: array + items: + type: string + format: byte + description: >- + signatures is a list of signatures that matches the + length and order of + + AuthInfo's signer_infos to allow connecting signature meta information like + + public key and signing mode by position. + description: Tx is the standard type used for broadcasting transactions. + description: txs is the list of queried transactions. + tx_responses: + type: array + items: + type: object + properties: + height: + type: string + format: int64 + title: The block height + txhash: + type: string + description: The transaction hash. + codespace: + type: string + title: Namespace for the Code + code: + type: integer + format: int64 + description: Response code. + data: + type: string + description: Result bytes, if any. + raw_log: + type: string + description: >- + The output of the application's logger (raw string). + May be + + non-deterministic. + logs: + type: array + items: + type: object + properties: + msg_index: + type: integer + format: int64 + log: + type: string + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + value: + type: string + description: >- + Attribute defines an attribute wrapper + where the key and value are + + strings instead of raw bytes. + description: >- + StringEvent defines en Event object wrapper + where all the attributes + + contain key/value pairs that are strings instead of raw bytes. + description: >- + Events contains a slice of Event objects that + were emitted during some + + execution. + description: ABCIMessageLog defines a structure containing an indexed tx ABCI + message log. + description: The output of the application's logger (typed). May be + non-deterministic. + info: + type: string + description: Additional information. May be non-deterministic. + gas_wanted: + type: string + format: int64 + description: Amount of gas requested for transaction. + gas_used: + type: string + format: int64 + description: Amount of gas consumed by transaction. + tx: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: The request transaction bytes. + timestamp: + type: string + description: >- + Time of the previous block. For heights > 1, it's + the weighted median of + + the timestamps of the valid votes in the block.LastCommit. For height == 1, + + it's genesis time. + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + format: byte + value: + type: string + format: byte + index: + type: boolean + description: EventAttribute is a single key-value pair, associated with an + event. + description: >- + Event allows application developers to attach + additional information to + + ResponseBeginBlock, ResponseEndBlock, ResponseCheckTx and ResponseDeliverTx. + + Later, transactions may be queried using these events. + description: >- + Events defines all the events emitted by processing + a transaction. Note, + + these events include those emitted by processing all the messages and those + + emitted from the ante handler. Whereas Logs contains the events, with + + additional metadata, emitted only by processing the messages. + + + Since: cosmos-sdk 0.42.11, 0.44.5, 0.45 + description: >- + TxResponse defines a structure containing relevant tx + data and metadata. The + + tags are stringified and the log is JSON decoded. + description: tx_responses is the list of queried TxResponses. + pagination: + description: pagination defines a pagination for the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + GetTxsEventResponse is the response type for the + Service.TxsByEvents + + RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: events + description: events is the list of transaction event type. + in: query + required: false + explode: true + schema: + type: array + items: + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + schema: + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + in: query + required: false + schema: + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + schema: + type: boolean + - name: order_by + description: >-2 + - ORDER_BY_UNSPECIFIED: ORDER_BY_UNSPECIFIED specifies an unknown sorting order. OrderBy defaults to ASC in this case. + - ORDER_BY_ASC: ORDER_BY_ASC defines ascending order + - ORDER_BY_DESC: ORDER_BY_DESC defines descending order + in: query + required: false + schema: + type: string + enum: + - ORDER_BY_UNSPECIFIED + - ORDER_BY_ASC + - ORDER_BY_DESC + default: ORDER_BY_UNSPECIFIED + tags: + - gRPC Gateway API + post: + summary: BroadcastTx broadcast transaction. + operationId: BroadcastTx_2H2YD + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + tx_response: + type: object + properties: + height: + type: string + format: int64 + title: The block height + txhash: + type: string + description: The transaction hash. + codespace: + type: string + title: Namespace for the Code + code: + type: integer + format: int64 + description: Response code. + data: + type: string + description: Result bytes, if any. + raw_log: + type: string + description: >- + The output of the application's logger (raw string). + May be + + non-deterministic. + logs: + type: array + items: + type: object + properties: + msg_index: + type: integer + format: int64 + log: + type: string + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + value: + type: string + description: >- + Attribute defines an attribute wrapper + where the key and value are + + strings instead of raw bytes. + description: >- + StringEvent defines en Event object wrapper + where all the attributes + + contain key/value pairs that are strings instead of raw bytes. + description: >- + Events contains a slice of Event objects that + were emitted during some + + execution. + description: ABCIMessageLog defines a structure containing an indexed tx ABCI + message log. + description: The output of the application's logger (typed). May be + non-deterministic. + info: + type: string + description: Additional information. May be non-deterministic. + gas_wanted: + type: string + format: int64 + description: Amount of gas requested for transaction. + gas_used: + type: string + format: int64 + description: Amount of gas consumed by transaction. + tx: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: The request transaction bytes. + timestamp: + type: string + description: >- + Time of the previous block. For heights > 1, it's the + weighted median of + + the timestamps of the valid votes in the block.LastCommit. For height == 1, + + it's genesis time. + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + format: byte + value: + type: string + format: byte + index: + type: boolean + description: EventAttribute is a single key-value pair, associated with an + event. + description: >- + Event allows application developers to attach + additional information to + + ResponseBeginBlock, ResponseEndBlock, ResponseCheckTx and ResponseDeliverTx. + + Later, transactions may be queried using these events. + description: >- + Events defines all the events emitted by processing a + transaction. Note, + + these events include those emitted by processing all the messages and those + + emitted from the ante handler. Whereas Logs contains the events, with + + additional metadata, emitted only by processing the messages. + + + Since: cosmos-sdk 0.42.11, 0.44.5, 0.45 + description: >- + TxResponse defines a structure containing relevant tx data + and metadata. The + + tags are stringified and the log is JSON decoded. + description: |- + BroadcastTxResponse is the response type for the + Service.BroadcastTx method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + requestBody: + content: + application/json: + schema: + type: object + properties: + tx_bytes: + type: string + format: byte + description: tx_bytes is the raw transaction. + mode: + type: string + enum: + - BROADCAST_MODE_UNSPECIFIED + - BROADCAST_MODE_BLOCK + - BROADCAST_MODE_SYNC + - BROADCAST_MODE_ASYNC + default: BROADCAST_MODE_UNSPECIFIED + description: >- + BroadcastMode specifies the broadcast mode for the + TxService.Broadcast RPC method. + + - BROADCAST_MODE_UNSPECIFIED: zero-value for mode ordering + - BROADCAST_MODE_BLOCK: BROADCAST_MODE_BLOCK defines a tx broadcasting mode where the client waits for + the tx to be committed in a block. + - BROADCAST_MODE_SYNC: BROADCAST_MODE_SYNC defines a tx broadcasting mode where the client waits for + a CheckTx execution response only. + - BROADCAST_MODE_ASYNC: BROADCAST_MODE_ASYNC defines a tx broadcasting mode where the client returns + immediately. + description: >- + BroadcastTxRequest is the request type for the + Service.BroadcastTxRequest + + RPC method. + required: true + tags: + - gRPC Gateway API + "/cosmos/tx/v1beta1/txs/block/{height}": + get: + summary: GetBlockWithTxs fetches a block with decoded txs. + description: "Since: cosmos-sdk 0.45.2" + operationId: GetBlockWithTxs_YQI6M + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + txs: + type: array + items: + type: object + properties: + body: + title: body is the processable content of the transaction + type: object + properties: + messages: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + messages is a list of messages to be executed. + The required signers of + + those messages define the number and order of elements in AuthInfo's + + signer_infos and Tx's signatures. Each required signer address is added to + + the list only the first time it occurs. + + By convention, the first required signer (usually from the first message) + + is referred to as the primary signer and pays the fee for the whole + + transaction. + memo: + type: string + description: >- + memo is any arbitrary note/comment to be added + to the transaction. + + WARNING: in clients, any publicly exposed text should not be called memo, + + but should be called `note` instead (see https://github.com/cosmos/cosmos-sdk/issues/9122). + timeout_height: + type: string + format: uint64 + title: >- + timeout is the block height after which this + transaction will not + + be processed by the chain + extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can + be added by chains + + when the default options are not sufficient. If any of these are present + + and can't be handled, the transaction will be rejected + non_critical_extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can + be added by chains + + when the default options are not sufficient. If any of these are present + + and can't be handled, they will be ignored + description: TxBody is the body of a transaction that all signers sign over. + auth_info: + title: >- + auth_info is the authorization related content of + the transaction, + + specifically signers, signer modes and fee + type: object + properties: + signer_infos: + type: array + items: + type: object + properties: + public_key: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + public_key is the public key of the + signer. It is optional for accounts + + that already exist in state. If unset, the verifier can use the required \ + + signer address for this position and lookup the public key. + mode_info: + title: >- + mode_info describes the signing mode of + the signer and is a nested + + structure to support nested multisig pubkey's + type: object + properties: + single: + title: single represents a single signer + type: object + properties: + mode: + title: mode is the signing mode of the single signer + type: string + enum: + - SIGN_MODE_UNSPECIFIED + - SIGN_MODE_DIRECT + - SIGN_MODE_TEXTUAL + - SIGN_MODE_LEGACY_AMINO_JSON + - SIGN_MODE_EIP_191 + default: SIGN_MODE_UNSPECIFIED + description: >- + SignMode represents a signing mode + with its own security guarantees. + + - SIGN_MODE_UNSPECIFIED: SIGN_MODE_UNSPECIFIED specifies an unknown signing mode and will be + rejected + - SIGN_MODE_DIRECT: SIGN_MODE_DIRECT specifies a signing mode which uses SignDoc and is + verified with raw bytes from Tx + - SIGN_MODE_TEXTUAL: SIGN_MODE_TEXTUAL is a future signing mode that will verify some + human-readable textual representation on top of the binary representation + + from SIGN_MODE_DIRECT + - SIGN_MODE_LEGACY_AMINO_JSON: SIGN_MODE_LEGACY_AMINO_JSON is a backwards compatibility mode which uses + Amino JSON and will be removed in the future + - SIGN_MODE_EIP_191: SIGN_MODE_EIP_191 specifies the sign mode for EIP 191 signing on the Cosmos + SDK. Ref: https://eips.ethereum.org/EIPS/eip-191 + + + Currently, SIGN_MODE_EIP_191 is registered as a SignMode enum variant, + + but is not implemented on the SDK by default. To enable EIP-191, you need + + to pass a custom `TxConfig` that has an implementation of + + `SignModeHandler` for EIP-191. The SDK may decide to fully support + + EIP-191 in the future. + + + Since: cosmos-sdk 0.45.2 + multi: + title: multi represents a nested multisig signer + type: object + properties: + bitarray: + title: bitarray specifies which keys within the multisig are signing + type: object + properties: + extra_bits_stored: + type: integer + format: int64 + elems: + type: string + format: byte + description: >- + CompactBitArray is an + implementation of a space + efficient bit array. + + This is used to ensure that the encoded data takes up a minimal amount of + + space after proto encoding. + + This is not thread safe, and is not intended for concurrent usage. + mode_infos: + type: array + items: {} + title: >- + mode_infos is the corresponding + modes of the signers of the + multisig + + which could include nested multisig public keys + description: ModeInfo describes the signing mode of a single or nested multisig + signer. + sequence: + type: string + format: uint64 + description: >- + sequence is the sequence of the account, + which describes the + + number of committed transactions signed by a given address. It is used to + + prevent replay attacks. + description: >- + SignerInfo describes the public key and + signing mode of a single top-level + + signer. + description: >- + signer_infos defines the signing modes for the + required signers. The number + + and order of elements must match the required signers from TxBody's + + messages. The first element is the primary signer and the one which pays + + the fee. + fee: + description: >- + Fee is the fee and gas limit for the + transaction. The first signer is the + + primary signer and the one which pays the fee. The fee can be calculated + + based on the cost of evaluating the body and doing signature verification + + of the signers. This can be estimated via simulation. + type: object + properties: + amount: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination + and an amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + title: amount is the amount of coins to be paid as a fee + gas_limit: + type: string + format: uint64 + title: >- + gas_limit is the maximum gas that can be + used in transaction processing + + before an out of gas error occurs + payer: + type: string + description: >- + if unset, the first signer is responsible + for paying the fees. If set, the specified + account must pay the fees. + + the payer must be a tx signer (and thus have signed this field in AuthInfo). + + setting this field does *not* change the ordering of required signers for the transaction. + granter: + type: string + title: >- + if set, the fee payer (either the first + signer or the value of the payer field) + requests that a fee grant be used + + to pay fees instead of the fee payer's own balance. If an appropriate fee grant does not exist or the chain does + + not support fee grants, this will fail + description: >- + AuthInfo describes the fee and signer modes that are + used to sign a + + transaction. + signatures: + type: array + items: + type: string + format: byte + description: >- + signatures is a list of signatures that matches the + length and order of + + AuthInfo's signer_infos to allow connecting signature meta information like + + public key and signing mode by position. + description: Tx is the standard type used for broadcasting transactions. + description: txs are the transactions in the block. + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + block: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for + processing a block in the blockchain, + + including all blockchain data structures and the rules of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + data: + type: object + properties: + txs: + type: array + items: + type: string + format: byte + description: >- + Txs that will be applied by state @ + block.Height+1. + + NOTE: not all txs here are valid. We're just agreeing on the order first. + + This means that block.AppHash does not include these txs. + title: Data contains the set of transactions included in the block + evidence: + type: object + properties: + evidence: + type: array + items: + type: object + properties: + duplicate_vote_evidence: + type: object + properties: + vote_a: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: >- + SignedMsgType is a type of signed + message in the consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or + commit vote from validators for + + consensus. + vote_b: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: >- + SignedMsgType is a type of signed + message in the consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or + commit vote from validators for + + consensus. + total_voting_power: + type: string + format: int64 + validator_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: DuplicateVoteEvidence contains evidence of a validator signed two + conflicting votes. + light_client_attack_evidence: + type: object + properties: + conflicting_block: + type: object + properties: + signed_header: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the + consensus rules for + processing a block in the + blockchain, + + including all blockchain data structures and the rules of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: BlockIdFlag indicates which BlcokID the signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: CommitSig is a part of the Vote included in a Commit. + description: Commit contains the evidence that a block was committed by a set of + validators. + validator_set: + type: object + properties: + validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + proposer: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + common_height: + type: string + format: int64 + byzantine_validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: LightClientAttackEvidence contains evidence of a set of validators + attempting to mislead a light client. + last_commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: BlockIdFlag indicates which BlcokID the signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: CommitSig is a part of the Vote included in a Commit. + description: Commit contains the evidence that a block was committed by a set of + validators. + pagination: + description: pagination defines a pagination for the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + GetBlockWithTxsResponse is the response type for the + Service.GetBlockWithTxs method. + + + Since: cosmos-sdk 0.45.2 + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: height + description: height is the height of the block to query. + in: path + required: true + schema: + type: string + format: int64 + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + schema: + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + in: query + required: false + schema: + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + schema: + type: boolean + tags: + - gRPC Gateway API + "/cosmos/tx/v1beta1/txs/{hash}": + get: + summary: GetTx fetches a tx by hash. + operationId: GetTx_M9HVX + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + tx: + type: object + properties: + body: + title: body is the processable content of the transaction + type: object + properties: + messages: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + messages is a list of messages to be executed. The + required signers of + + those messages define the number and order of elements in AuthInfo's + + signer_infos and Tx's signatures. Each required signer address is added to + + the list only the first time it occurs. + + By convention, the first required signer (usually from the first message) + + is referred to as the primary signer and pays the fee for the whole + + transaction. + memo: + type: string + description: >- + memo is any arbitrary note/comment to be added to + the transaction. + + WARNING: in clients, any publicly exposed text should not be called memo, + + but should be called `note` instead (see https://github.com/cosmos/cosmos-sdk/issues/9122). + timeout_height: + type: string + format: uint64 + title: >- + timeout is the block height after which this + transaction will not + + be processed by the chain + extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can + be added by chains + + when the default options are not sufficient. If any of these are present + + and can't be handled, the transaction will be rejected + non_critical_extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can + be added by chains + + when the default options are not sufficient. If any of these are present + + and can't be handled, they will be ignored + description: TxBody is the body of a transaction that all signers sign over. + auth_info: + title: >- + auth_info is the authorization related content of the + transaction, + + specifically signers, signer modes and fee + type: object + properties: + signer_infos: + type: array + items: + type: object + properties: + public_key: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + public_key is the public key of the signer. + It is optional for accounts + + that already exist in state. If unset, the verifier can use the required \ + + signer address for this position and lookup the public key. + mode_info: + title: >- + mode_info describes the signing mode of the + signer and is a nested + + structure to support nested multisig pubkey's + type: object + properties: + single: + title: single represents a single signer + type: object + properties: + mode: + title: mode is the signing mode of the single signer + type: string + enum: + - SIGN_MODE_UNSPECIFIED + - SIGN_MODE_DIRECT + - SIGN_MODE_TEXTUAL + - SIGN_MODE_LEGACY_AMINO_JSON + - SIGN_MODE_EIP_191 + default: SIGN_MODE_UNSPECIFIED + description: >- + SignMode represents a signing mode + with its own security guarantees. + + - SIGN_MODE_UNSPECIFIED: SIGN_MODE_UNSPECIFIED specifies an unknown signing mode and will be + rejected + - SIGN_MODE_DIRECT: SIGN_MODE_DIRECT specifies a signing mode which uses SignDoc and is + verified with raw bytes from Tx + - SIGN_MODE_TEXTUAL: SIGN_MODE_TEXTUAL is a future signing mode that will verify some + human-readable textual representation on top of the binary representation + + from SIGN_MODE_DIRECT + - SIGN_MODE_LEGACY_AMINO_JSON: SIGN_MODE_LEGACY_AMINO_JSON is a backwards compatibility mode which uses + Amino JSON and will be removed in the future + - SIGN_MODE_EIP_191: SIGN_MODE_EIP_191 specifies the sign mode for EIP 191 signing on the Cosmos + SDK. Ref: https://eips.ethereum.org/EIPS/eip-191 + + + Currently, SIGN_MODE_EIP_191 is registered as a SignMode enum variant, + + but is not implemented on the SDK by default. To enable EIP-191, you need + + to pass a custom `TxConfig` that has an implementation of + + `SignModeHandler` for EIP-191. The SDK may decide to fully support + + EIP-191 in the future. + + + Since: cosmos-sdk 0.45.2 + multi: + title: multi represents a nested multisig signer + type: object + properties: + bitarray: + title: bitarray specifies which keys within the multisig are signing + type: object + properties: + extra_bits_stored: + type: integer + format: int64 + elems: + type: string + format: byte + description: >- + CompactBitArray is an implementation + of a space efficient bit array. + + This is used to ensure that the encoded data takes up a minimal amount of + + space after proto encoding. + + This is not thread safe, and is not intended for concurrent usage. + mode_infos: + type: array + items: {} + title: >- + mode_infos is the corresponding + modes of the signers of the multisig + + which could include nested multisig public keys + description: ModeInfo describes the signing mode of a single or nested multisig + signer. + sequence: + type: string + format: uint64 + description: >- + sequence is the sequence of the account, + which describes the + + number of committed transactions signed by a given address. It is used to + + prevent replay attacks. + description: >- + SignerInfo describes the public key and signing + mode of a single top-level + + signer. + description: >- + signer_infos defines the signing modes for the + required signers. The number + + and order of elements must match the required signers from TxBody's + + messages. The first element is the primary signer and the one which pays + + the fee. + fee: + description: >- + Fee is the fee and gas limit for the transaction. + The first signer is the + + primary signer and the one which pays the fee. The fee can be calculated + + based on the cost of evaluating the body and doing signature verification + + of the signers. This can be estimated via simulation. + type: object + properties: + amount: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and + an amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + title: amount is the amount of coins to be paid as a fee + gas_limit: + type: string + format: uint64 + title: >- + gas_limit is the maximum gas that can be used + in transaction processing + + before an out of gas error occurs + payer: + type: string + description: >- + if unset, the first signer is responsible for + paying the fees. If set, the specified account + must pay the fees. + + the payer must be a tx signer (and thus have signed this field in AuthInfo). + + setting this field does *not* change the ordering of required signers for the transaction. + granter: + type: string + title: >- + if set, the fee payer (either the first signer + or the value of the payer field) requests that + a fee grant be used + + to pay fees instead of the fee payer's own balance. If an appropriate fee grant does not exist or the chain does + + not support fee grants, this will fail + description: >- + AuthInfo describes the fee and signer modes that are + used to sign a + + transaction. + signatures: + type: array + items: + type: string + format: byte + description: >- + signatures is a list of signatures that matches the + length and order of + + AuthInfo's signer_infos to allow connecting signature meta information like + + public key and signing mode by position. + description: Tx is the standard type used for broadcasting transactions. + tx_response: + type: object + properties: + height: + type: string + format: int64 + title: The block height + txhash: + type: string + description: The transaction hash. + codespace: + type: string + title: Namespace for the Code + code: + type: integer + format: int64 + description: Response code. + data: + type: string + description: Result bytes, if any. + raw_log: + type: string + description: >- + The output of the application's logger (raw string). + May be + + non-deterministic. + logs: + type: array + items: + type: object + properties: + msg_index: + type: integer + format: int64 + log: + type: string + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + value: + type: string + description: >- + Attribute defines an attribute wrapper + where the key and value are + + strings instead of raw bytes. + description: >- + StringEvent defines en Event object wrapper + where all the attributes + + contain key/value pairs that are strings instead of raw bytes. + description: >- + Events contains a slice of Event objects that + were emitted during some + + execution. + description: ABCIMessageLog defines a structure containing an indexed tx ABCI + message log. + description: The output of the application's logger (typed). May be + non-deterministic. + info: + type: string + description: Additional information. May be non-deterministic. + gas_wanted: + type: string + format: int64 + description: Amount of gas requested for transaction. + gas_used: + type: string + format: int64 + description: Amount of gas consumed by transaction. + tx: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: The request transaction bytes. + timestamp: + type: string + description: >- + Time of the previous block. For heights > 1, it's the + weighted median of + + the timestamps of the valid votes in the block.LastCommit. For height == 1, + + it's genesis time. + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + format: byte + value: + type: string + format: byte + index: + type: boolean + description: EventAttribute is a single key-value pair, associated with an + event. + description: >- + Event allows application developers to attach + additional information to + + ResponseBeginBlock, ResponseEndBlock, ResponseCheckTx and ResponseDeliverTx. + + Later, transactions may be queried using these events. + description: >- + Events defines all the events emitted by processing a + transaction. Note, + + these events include those emitted by processing all the messages and those + + emitted from the ante handler. Whereas Logs contains the events, with + + additional metadata, emitted only by processing the messages. + + + Since: cosmos-sdk 0.42.11, 0.44.5, 0.45 + description: >- + TxResponse defines a structure containing relevant tx data + and metadata. The + + tags are stringified and the log is JSON decoded. + description: GetTxResponse is the response type for the Service.GetTx method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: hash + description: hash is the tx hash to query, encoded as a hex string. + in: path + required: true + schema: + type: string + tags: + - gRPC Gateway API + "/inter-tx/interchain_account/owner/{owner}/connection/{connection_id}": + get: + summary: QueryInterchainAccount returns the interchain account for given owner + address on a given connection pair + operationId: InterchainAccount_FCQUO + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + interchain_account_address: + type: string + title: QueryInterchainAccountResponse the response type for the + Query/InterchainAccountAddress RPC + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: owner + in: path + required: true + schema: + type: string + - name: connection_id + in: path + required: true + schema: + type: string + tags: + - gRPC Gateway API + /cosmwasm/wasm/v1/code: + get: + summary: Codes gets the metadata for all stored wasm codes + operationId: Codes_USGTR + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + code_infos: + type: array + items: + type: object + properties: + code_id: + type: string + format: uint64 + creator: + type: string + data_hash: + type: string + format: byte + instantiate_permission: + type: object + properties: + permission: + type: string + enum: + - ACCESS_TYPE_UNSPECIFIED + - ACCESS_TYPE_NOBODY + - ACCESS_TYPE_ONLY_ADDRESS + - ACCESS_TYPE_EVERYBODY + - ACCESS_TYPE_ANY_OF_ADDRESSES + default: ACCESS_TYPE_UNSPECIFIED + description: >- + - ACCESS_TYPE_UNSPECIFIED: AccessTypeUnspecified + placeholder for empty value + - ACCESS_TYPE_NOBODY: AccessTypeNobody forbidden + - ACCESS_TYPE_ONLY_ADDRESS: AccessTypeOnlyAddress restricted to a single address + Deprecated: use AccessTypeAnyOfAddresses instead + - ACCESS_TYPE_EVERYBODY: AccessTypeEverybody unrestricted + - ACCESS_TYPE_ANY_OF_ADDRESSES: AccessTypeAnyOfAddresses allow any of the addresses + title: AccessType permission types + address: + type: string + title: |- + Address + Deprecated: replaced by addresses + addresses: + type: array + items: + type: string + description: AccessConfig access control type. + title: CodeInfoResponse contains code meta data from CodeInfo + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + title: QueryCodesResponse is the response type for the Query/Codes RPC method + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + schema: + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + in: query + required: false + schema: + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + schema: + type: boolean + tags: + - gRPC Gateway API + "/cosmwasm/wasm/v1/code/{code_id}": + get: + summary: Code gets the binary code and metadata for a singe wasm code + operationId: Code_45RS6 + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + code_info: + type: object + properties: + code_id: + type: string + format: uint64 + creator: + type: string + data_hash: + type: string + format: byte + instantiate_permission: + type: object + properties: + permission: + type: string + enum: + - ACCESS_TYPE_UNSPECIFIED + - ACCESS_TYPE_NOBODY + - ACCESS_TYPE_ONLY_ADDRESS + - ACCESS_TYPE_EVERYBODY + - ACCESS_TYPE_ANY_OF_ADDRESSES + default: ACCESS_TYPE_UNSPECIFIED + description: >- + - ACCESS_TYPE_UNSPECIFIED: AccessTypeUnspecified + placeholder for empty value + - ACCESS_TYPE_NOBODY: AccessTypeNobody forbidden + - ACCESS_TYPE_ONLY_ADDRESS: AccessTypeOnlyAddress restricted to a single address + Deprecated: use AccessTypeAnyOfAddresses instead + - ACCESS_TYPE_EVERYBODY: AccessTypeEverybody unrestricted + - ACCESS_TYPE_ANY_OF_ADDRESSES: AccessTypeAnyOfAddresses allow any of the addresses + title: AccessType permission types + address: + type: string + title: |- + Address + Deprecated: replaced by addresses + addresses: + type: array + items: + type: string + description: AccessConfig access control type. + title: CodeInfoResponse contains code meta data from CodeInfo + data: + type: string + format: byte + title: QueryCodeResponse is the response type for the Query/Code RPC method + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: code_id + in: path + required: true + schema: + type: string + format: uint64 + tags: + - gRPC Gateway API + "/cosmwasm/wasm/v1/code/{code_id}/contracts": + get: + summary: ContractsByCode lists all smart contracts for a code id + operationId: ContractsByCode_DI5NT + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + contracts: + type: array + items: + type: string + title: contracts are a set of contract addresses + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + title: |- + QueryContractsByCodeResponse is the response type for the + Query/ContractsByCode RPC method + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: code_id + in: path + required: true + schema: + type: string + format: uint64 + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + schema: + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + in: query + required: false + schema: + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + schema: + type: boolean + tags: + - gRPC Gateway API + /cosmwasm/wasm/v1/codes/params: + get: + summary: Params gets the module params + operationId: Params_LUDIW + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + params: + description: params defines the parameters of the module. + type: object + properties: + code_upload_access: + type: object + properties: + permission: + type: string + enum: + - ACCESS_TYPE_UNSPECIFIED + - ACCESS_TYPE_NOBODY + - ACCESS_TYPE_ONLY_ADDRESS + - ACCESS_TYPE_EVERYBODY + - ACCESS_TYPE_ANY_OF_ADDRESSES + default: ACCESS_TYPE_UNSPECIFIED + description: >- + - ACCESS_TYPE_UNSPECIFIED: AccessTypeUnspecified + placeholder for empty value + - ACCESS_TYPE_NOBODY: AccessTypeNobody forbidden + - ACCESS_TYPE_ONLY_ADDRESS: AccessTypeOnlyAddress restricted to a single address + Deprecated: use AccessTypeAnyOfAddresses instead + - ACCESS_TYPE_EVERYBODY: AccessTypeEverybody unrestricted + - ACCESS_TYPE_ANY_OF_ADDRESSES: AccessTypeAnyOfAddresses allow any of the addresses + title: AccessType permission types + address: + type: string + title: |- + Address + Deprecated: replaced by addresses + addresses: + type: array + items: + type: string + description: AccessConfig access control type. + instantiate_default_permission: + type: string + enum: + - ACCESS_TYPE_UNSPECIFIED + - ACCESS_TYPE_NOBODY + - ACCESS_TYPE_ONLY_ADDRESS + - ACCESS_TYPE_EVERYBODY + - ACCESS_TYPE_ANY_OF_ADDRESSES + default: ACCESS_TYPE_UNSPECIFIED + description: >- + - ACCESS_TYPE_UNSPECIFIED: AccessTypeUnspecified + placeholder for empty value + - ACCESS_TYPE_NOBODY: AccessTypeNobody forbidden + - ACCESS_TYPE_ONLY_ADDRESS: AccessTypeOnlyAddress restricted to a single address + Deprecated: use AccessTypeAnyOfAddresses instead + - ACCESS_TYPE_EVERYBODY: AccessTypeEverybody unrestricted + - ACCESS_TYPE_ANY_OF_ADDRESSES: AccessTypeAnyOfAddresses allow any of the addresses + title: AccessType permission types + description: QueryParamsResponse is the response type for the Query/Params RPC + method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + /cosmwasm/wasm/v1/codes/pinned: + get: + summary: PinnedCodes gets the pinned code ids + operationId: PinnedCodes_38LCO + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + code_ids: + type: array + items: + type: string + format: uint64 + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + title: |- + QueryPinnedCodesResponse is the response type for the + Query/PinnedCodes RPC method + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + schema: + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + in: query + required: false + schema: + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + schema: + type: boolean + tags: + - gRPC Gateway API + "/cosmwasm/wasm/v1/contract/{address}": + get: + summary: ContractInfo gets the contract meta data + operationId: ContractInfo_NYK65 + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + address: + type: string + title: address is the address of the contract + contract_info: + type: object + properties: + code_id: + type: string + format: uint64 + title: CodeID is the reference to the stored Wasm code + creator: + type: string + title: Creator address who initially instantiated the contract + admin: + type: string + title: Admin is an optional address that can execute migrations + label: + type: string + description: Label is optional metadata to be stored with a contract instance. + created: + description: Created Tx position when the contract was instantiated. + type: object + properties: + block_height: + type: string + format: uint64 + title: BlockHeight is the block the contract was created at + tx_index: + type: string + format: uint64 + title: >- + TxIndex is a monotonic counter within the block + (actual transaction index, + + or gas consumed) + ibc_port_id: + type: string + extension: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + Extension is an extension point to store custom + metadata within the + + persistence model. + title: ContractInfo stores a WASM contract instance + title: >- + QueryContractInfoResponse is the response type for the + Query/ContractInfo RPC + + method + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: address + description: address is the address of the contract to query + in: path + required: true + schema: + type: string + tags: + - gRPC Gateway API + "/cosmwasm/wasm/v1/contract/{address}/history": + get: + summary: ContractHistory gets the contract code history + operationId: ContractHistory_M2L3Y + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + entries: + type: array + items: + type: object + properties: + operation: + type: string + enum: + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_UNSPECIFIED + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_INIT + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_MIGRATE + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_GENESIS + default: CONTRACT_CODE_HISTORY_OPERATION_TYPE_UNSPECIFIED + description: >- + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_UNSPECIFIED: + ContractCodeHistoryOperationTypeUnspecified + placeholder for empty value + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_INIT: ContractCodeHistoryOperationTypeInit on chain contract instantiation + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_MIGRATE: ContractCodeHistoryOperationTypeMigrate code migration + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_GENESIS: ContractCodeHistoryOperationTypeGenesis based on genesis data + title: ContractCodeHistoryOperationType actions that caused a code change + code_id: + type: string + format: uint64 + title: CodeID is the reference to the stored WASM code + updated: + description: Updated Tx position when the operation was executed. + type: object + properties: + block_height: + type: string + format: uint64 + title: BlockHeight is the block the contract was created at + tx_index: + type: string + format: uint64 + title: >- + TxIndex is a monotonic counter within the block + (actual transaction index, + + or gas consumed) + msg: + type: string + format: byte + description: ContractCodeHistoryEntry metadata to a contract. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + title: |- + QueryContractHistoryResponse is the response type for the + Query/ContractHistory RPC method + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: address + description: address is the address of the contract to query + in: path + required: true + schema: + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + schema: + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + in: query + required: false + schema: + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + schema: + type: boolean + tags: + - gRPC Gateway API + "/cosmwasm/wasm/v1/contract/{address}/raw/{query_data}": + get: + summary: RawContractState gets single key from the raw store data of a contract + operationId: RawContractState_A25W1 + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + data: + type: string + format: byte + title: Data contains the raw store data + title: |- + QueryRawContractStateResponse is the response type for the + Query/RawContractState RPC method + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: address + description: address is the address of the contract + in: path + required: true + schema: + type: string + - name: query_data + in: path + required: true + schema: + type: string + format: byte + tags: + - gRPC Gateway API + "/cosmwasm/wasm/v1/contract/{address}/smart/{query_data}": + get: + summary: SmartContractState get smart query result from the contract + operationId: SmartContractState_FMP76 + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + data: + type: string + format: byte + title: Data contains the json data returned from the smart contract + title: |- + QuerySmartContractStateResponse is the response type for the + Query/SmartContractState RPC method + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: address + description: address is the address of the contract + in: path + required: true + schema: + type: string + - name: query_data + description: QueryData contains the query data passed to the contract + in: path + required: true + schema: + type: string + format: byte + tags: + - gRPC Gateway API + "/cosmwasm/wasm/v1/contract/{address}/state": + get: + summary: AllContractState gets all raw store data for a single contract + operationId: AllContractState_N88EG + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + models: + type: array + items: + type: object + properties: + key: + type: string + format: byte + title: hex-encode key to read it better (this is often ascii) + value: + type: string + format: byte + title: base64-encode raw value + title: Model is a struct that holds a KV pair + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + title: |- + QueryAllContractStateResponse is the response type for the + Query/AllContractState RPC method + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: address + description: address is the address of the contract + in: path + required: true + schema: + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + schema: + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + in: query + required: false + schema: + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + schema: + type: boolean + tags: + - gRPC Gateway API + "/cosmwasm/wasm/v1/contracts/creator/{creator_address}": + get: + summary: ContractsByCreator gets the contracts by creator + operationId: ContractsByCreator_4VHDU + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + contract_addresses: + type: array + items: + type: string + title: ContractAddresses result set + pagination: + description: Pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + QueryContractsByCreatorResponse is the response type for the + Query/ContractsByCreator RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: creator_address + description: CreatorAddress is the address of contract creator + in: path + required: true + schema: + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + schema: + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + in: query + required: false + schema: + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + schema: + type: boolean + tags: + - gRPC Gateway API + "/cosmos/feegrant/v1beta1/allowance/{granter}/{grantee}": + get: + summary: Allowance returns fee granted to the grantee by the granter. + operationId: Allowance_5N8HR + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + allowance: + description: allowance is a allowance granted for grantee by granter. + type: object + properties: + granter: + type: string + description: granter is the address of the user granting an allowance of their + funds. + grantee: + type: string + description: grantee is the address of the user being granted an allowance of + another user's funds. + allowance: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: allowance can be any of basic and filtered fee allowance. + title: Grant is stored in the KVStore to record a grant with full context + description: QueryAllowanceResponse is the response type for the Query/Allowance + RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: granter + description: granter is the address of the user granting an allowance of their + funds. + in: path + required: true + schema: + type: string + - name: grantee + description: grantee is the address of the user being granted an allowance of + another user's funds. + in: path + required: true + schema: + type: string + tags: + - gRPC Gateway API + "/cosmos/feegrant/v1beta1/allowances/{grantee}": + get: + summary: Allowances returns all the grants for address. + operationId: Allowances_PKM8A + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + allowances: + type: array + items: + type: object + properties: + granter: + type: string + description: granter is the address of the user granting an allowance of their + funds. + grantee: + type: string + description: grantee is the address of the user being granted an allowance of + another user's funds. + allowance: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: allowance can be any of basic and filtered fee allowance. + title: Grant is stored in the KVStore to record a grant with full context + description: allowances are allowance's granted for grantee by granter. + pagination: + description: pagination defines an pagination for the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: QueryAllowancesResponse is the response type for the + Query/Allowances RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: grantee + in: path + required: true + schema: + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + schema: + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + in: query + required: false + schema: + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + schema: + type: boolean + tags: + - gRPC Gateway API + "/cosmos/feegrant/v1beta1/issued/{granter}": + get: + summary: |- + AllowancesByGranter returns all the grants given by an address + Since v0.46 + operationId: AllowancesByGranter_1A39E + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + allowances: + type: array + items: + type: object + properties: + granter: + type: string + description: granter is the address of the user granting an allowance of their + funds. + grantee: + type: string + description: grantee is the address of the user being granted an allowance of + another user's funds. + allowance: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: allowance can be any of basic and filtered fee allowance. + title: Grant is stored in the KVStore to record a grant with full context + description: allowances that have been issued by the granter. + pagination: + description: pagination defines an pagination for the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: QueryAllowancesByGranterResponse is the response type for the + Query/AllowancesByGranter RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: granter + in: path + required: true + schema: + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + schema: + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + in: query + required: false + schema: + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + schema: + type: boolean + tags: + - gRPC Gateway API + get: + operationId: MinimumGasPrices_18KUX + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + minimum_gas_prices: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + DecCoin defines a token with a denomination and a + decimal amount. + + + NOTE: The amount field is an Dec which implements the custom method + + signatures required by gogoproto. + description: |- + QueryMinimumGasPricesResponse is the response type for the + Query/MinimumGasPrices RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + /cosmos/evidence/v1beta1/evidence: + get: + summary: AllEvidence queries all evidence. + operationId: AllEvidence_ZM26C + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + evidence: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: evidence returns all evidences. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryAllEvidenceResponse is the response type for the + Query/AllEvidence RPC + + method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + schema: + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + in: query + required: false + schema: + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + schema: + type: boolean + tags: + - gRPC Gateway API + "/cosmos/evidence/v1beta1/evidence/{evidence_hash}": + get: + summary: Evidence queries evidence based on evidence hash. + operationId: Evidence_2RMX9 + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + evidence: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: evidence returns the requested evidence. + description: QueryEvidenceResponse is the response type for the Query/Evidence + RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: evidence_hash + description: evidence_hash defines the hash of the requested evidence. + in: path + required: true + schema: + type: string + format: byte + tags: + - gRPC Gateway API + /cosmos/base/node/v1beta1/config: + get: + summary: Config queries for the operator configuration. + operationId: Config_B18ME + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + minimum_gas_price: + type: string + description: ConfigResponse defines the response structure for the Config gRPC + query. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + /cosmos/params/v1beta1/params: + get: + summary: |- + Params queries a specific parameter of a module, given its subspace and + key. + operationId: Params_9R7UX + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + param: + description: param defines the queried parameter. + type: object + properties: + subspace: + type: string + key: + type: string + value: + type: string + description: QueryParamsResponse is response type for the Query/Params RPC + method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: subspace + description: subspace defines the module to query the parameter for. + in: query + required: false + schema: + type: string + - name: key + description: key defines the key of the parameter in the subspace. + in: query + required: false + schema: + type: string + tags: + - gRPC Gateway API + "/cosmos/gov/v1beta1/params/{params_type}": + get: + summary: Params queries all parameters of the gov module. + operationId: Params_SZ6SI + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + voting_params: + description: voting_params defines the parameters related to voting. + type: object + properties: + voting_period: + type: string + description: Length of the voting period. + deposit_params: + description: deposit_params defines the parameters related to deposit. + type: object + properties: + min_deposit: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an + amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + description: Minimum deposit for a proposal to enter voting period. + max_deposit_period: + type: string + description: >- + Maximum period for Atom holders to deposit on a + proposal. Initial value: 2 + months. + tally_params: + description: tally_params defines the parameters related to tally. + type: object + properties: + quorum: + type: string + format: byte + description: >- + Minimum percentage of total stake needed to vote for a + result to be + considered valid. + threshold: + type: string + format: byte + description: "Minimum proportion of Yes votes for proposal to pass. Default + value: 0.5." + veto_threshold: + type: string + format: byte + description: >- + Minimum value of Veto votes to Total votes ratio for + proposal to be + vetoed. Default value: 1/3. + description: QueryParamsResponse is the response type for the Query/Params RPC + method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: params_type + description: >- + params_type defines which parameters to query for, can be one of + "voting", + + "tallying" or "deposit". + in: path + required: true + schema: + type: string + tags: + - gRPC Gateway API + /cosmos/gov/v1beta1/proposals: + get: + summary: Proposals queries all proposals based on given status. + operationId: Proposals_VOWB2 + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + proposals: + type: array + items: + type: object + properties: + proposal_id: + type: string + format: uint64 + content: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + status: + type: string + enum: + - PROPOSAL_STATUS_UNSPECIFIED + - PROPOSAL_STATUS_DEPOSIT_PERIOD + - PROPOSAL_STATUS_VOTING_PERIOD + - PROPOSAL_STATUS_PASSED + - PROPOSAL_STATUS_REJECTED + - PROPOSAL_STATUS_FAILED + default: PROPOSAL_STATUS_UNSPECIFIED + description: >- + ProposalStatus enumerates the valid statuses of a + proposal. + + - PROPOSAL_STATUS_UNSPECIFIED: PROPOSAL_STATUS_UNSPECIFIED defines the default propopsal status. + - PROPOSAL_STATUS_DEPOSIT_PERIOD: PROPOSAL_STATUS_DEPOSIT_PERIOD defines a proposal status during the deposit + period. + - PROPOSAL_STATUS_VOTING_PERIOD: PROPOSAL_STATUS_VOTING_PERIOD defines a proposal status during the voting + period. + - PROPOSAL_STATUS_PASSED: PROPOSAL_STATUS_PASSED defines a proposal status of a proposal that has + passed. + - PROPOSAL_STATUS_REJECTED: PROPOSAL_STATUS_REJECTED defines a proposal status of a proposal that has + been rejected. + - PROPOSAL_STATUS_FAILED: PROPOSAL_STATUS_FAILED defines a proposal status of a proposal that has + failed. + final_tally_result: + type: object + properties: + yes: + type: string + abstain: + type: string + no: + type: string + no_with_veto: + type: string + description: TallyResult defines a standard tally for a governance proposal. + submit_time: + type: string + format: date-time + deposit_end_time: + type: string + format: date-time + total_deposit: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an + amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + voting_start_time: + type: string + format: date-time + voting_end_time: + type: string + format: date-time + description: Proposal defines the core field members of a governance proposal. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryProposalsResponse is the response type for the + Query/Proposals RPC + + method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: proposal_status + description: >- + proposal_status defines the status of the proposals. + + - PROPOSAL_STATUS_UNSPECIFIED: PROPOSAL_STATUS_UNSPECIFIED defines the default propopsal status. + - PROPOSAL_STATUS_DEPOSIT_PERIOD: PROPOSAL_STATUS_DEPOSIT_PERIOD defines a proposal status during the deposit + period. + - PROPOSAL_STATUS_VOTING_PERIOD: PROPOSAL_STATUS_VOTING_PERIOD defines a proposal status during the voting + period. + - PROPOSAL_STATUS_PASSED: PROPOSAL_STATUS_PASSED defines a proposal status of a proposal that has + passed. + - PROPOSAL_STATUS_REJECTED: PROPOSAL_STATUS_REJECTED defines a proposal status of a proposal that has + been rejected. + - PROPOSAL_STATUS_FAILED: PROPOSAL_STATUS_FAILED defines a proposal status of a proposal that has + failed. + in: query + required: false + schema: + type: string + enum: + - PROPOSAL_STATUS_UNSPECIFIED + - PROPOSAL_STATUS_DEPOSIT_PERIOD + - PROPOSAL_STATUS_VOTING_PERIOD + - PROPOSAL_STATUS_PASSED + - PROPOSAL_STATUS_REJECTED + - PROPOSAL_STATUS_FAILED + default: PROPOSAL_STATUS_UNSPECIFIED + - name: voter + description: voter defines the voter address for the proposals. + in: query + required: false + schema: + type: string + - name: depositor + description: depositor defines the deposit addresses from the proposals. + in: query + required: false + schema: + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + schema: + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + in: query + required: false + schema: + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + schema: + type: boolean + tags: + - gRPC Gateway API + "/cosmos/gov/v1beta1/proposals/{proposal_id}": + get: + summary: Proposal queries proposal details based on ProposalID. + operationId: Proposal_76NCB + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + proposal: + type: object + properties: + proposal_id: + type: string + format: uint64 + content: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + status: + type: string + enum: + - PROPOSAL_STATUS_UNSPECIFIED + - PROPOSAL_STATUS_DEPOSIT_PERIOD + - PROPOSAL_STATUS_VOTING_PERIOD + - PROPOSAL_STATUS_PASSED + - PROPOSAL_STATUS_REJECTED + - PROPOSAL_STATUS_FAILED + default: PROPOSAL_STATUS_UNSPECIFIED + description: >- + ProposalStatus enumerates the valid statuses of a + proposal. + + - PROPOSAL_STATUS_UNSPECIFIED: PROPOSAL_STATUS_UNSPECIFIED defines the default propopsal status. + - PROPOSAL_STATUS_DEPOSIT_PERIOD: PROPOSAL_STATUS_DEPOSIT_PERIOD defines a proposal status during the deposit + period. + - PROPOSAL_STATUS_VOTING_PERIOD: PROPOSAL_STATUS_VOTING_PERIOD defines a proposal status during the voting + period. + - PROPOSAL_STATUS_PASSED: PROPOSAL_STATUS_PASSED defines a proposal status of a proposal that has + passed. + - PROPOSAL_STATUS_REJECTED: PROPOSAL_STATUS_REJECTED defines a proposal status of a proposal that has + been rejected. + - PROPOSAL_STATUS_FAILED: PROPOSAL_STATUS_FAILED defines a proposal status of a proposal that has + failed. + final_tally_result: + type: object + properties: + yes: + type: string + abstain: + type: string + no: + type: string + no_with_veto: + type: string + description: TallyResult defines a standard tally for a governance proposal. + submit_time: + type: string + format: date-time + deposit_end_time: + type: string + format: date-time + total_deposit: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an + amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + voting_start_time: + type: string + format: date-time + voting_end_time: + type: string + format: date-time + description: Proposal defines the core field members of a governance proposal. + description: QueryProposalResponse is the response type for the Query/Proposal + RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: proposal_id + description: proposal_id defines the unique id of the proposal. + in: path + required: true + schema: + type: string + format: uint64 + tags: + - gRPC Gateway API + "/cosmos/gov/v1beta1/proposals/{proposal_id}/deposits": + get: + summary: Deposits queries all deposits of a single proposal. + operationId: Deposits_9H9W1 + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + deposits: + type: array + items: + type: object + properties: + proposal_id: + type: string + format: uint64 + depositor: + type: string + amount: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an + amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + description: >- + Deposit defines an amount deposited by an account + address to an active + + proposal. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: QueryDepositsResponse is the response type for the Query/Deposits + RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: proposal_id + description: proposal_id defines the unique id of the proposal. + in: path + required: true + schema: + type: string + format: uint64 + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + schema: + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + in: query + required: false + schema: + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + schema: + type: boolean + tags: + - gRPC Gateway API + "/cosmos/gov/v1beta1/proposals/{proposal_id}/deposits/{depositor}": + get: + summary: Deposit queries single deposit information based proposalID, depositAddr. + operationId: Deposit_Q9ZCY + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + deposit: + type: object + properties: + proposal_id: + type: string + format: uint64 + depositor: + type: string + amount: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an + amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + description: >- + Deposit defines an amount deposited by an account address + to an active + + proposal. + description: QueryDepositResponse is the response type for the Query/Deposit RPC + method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: proposal_id + description: proposal_id defines the unique id of the proposal. + in: path + required: true + schema: + type: string + format: uint64 + - name: depositor + description: depositor defines the deposit addresses from the proposals. + in: path + required: true + schema: + type: string + tags: + - gRPC Gateway API + "/cosmos/gov/v1beta1/proposals/{proposal_id}/tally": + get: + summary: TallyResult queries the tally of a proposal vote. + operationId: TallyResult_P38T1 + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + tally: + type: object + properties: + yes: + type: string + abstain: + type: string + no: + type: string + no_with_veto: + type: string + description: TallyResult defines a standard tally for a governance proposal. + description: QueryTallyResultResponse is the response type for the Query/Tally + RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: proposal_id + description: proposal_id defines the unique id of the proposal. + in: path + required: true + schema: + type: string + format: uint64 + tags: + - gRPC Gateway API + "/cosmos/gov/v1beta1/proposals/{proposal_id}/votes": + get: + summary: Votes queries votes of a given proposal. + operationId: Votes_K1AD6 + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + votes: + type: array + items: + type: object + properties: + proposal_id: + type: string + format: uint64 + voter: + type: string + option: + description: >- + Deprecated: Prefer to use `options` instead. This + field is set in queries + + if and only if `len(options) == 1` and that option has weight 1. In all + + other cases, this field will default to VOTE_OPTION_UNSPECIFIED. + type: string + enum: + - VOTE_OPTION_UNSPECIFIED + - VOTE_OPTION_YES + - VOTE_OPTION_ABSTAIN + - VOTE_OPTION_NO + - VOTE_OPTION_NO_WITH_VETO + default: VOTE_OPTION_UNSPECIFIED + options: + type: array + items: + type: object + properties: + option: + type: string + enum: + - VOTE_OPTION_UNSPECIFIED + - VOTE_OPTION_YES + - VOTE_OPTION_ABSTAIN + - VOTE_OPTION_NO + - VOTE_OPTION_NO_WITH_VETO + default: VOTE_OPTION_UNSPECIFIED + description: >- + VoteOption enumerates the valid vote options + for a given governance proposal. + + - VOTE_OPTION_UNSPECIFIED: VOTE_OPTION_UNSPECIFIED defines a no-op vote option. + - VOTE_OPTION_YES: VOTE_OPTION_YES defines a yes vote option. + - VOTE_OPTION_ABSTAIN: VOTE_OPTION_ABSTAIN defines an abstain vote option. + - VOTE_OPTION_NO: VOTE_OPTION_NO defines a no vote option. + - VOTE_OPTION_NO_WITH_VETO: VOTE_OPTION_NO_WITH_VETO defines a no with veto vote option. + weight: + type: string + description: >- + WeightedVoteOption defines a unit of vote for vote + split. + + + Since: cosmos-sdk 0.43 + title: "Since: cosmos-sdk 0.43" + description: >- + Vote defines a vote on a governance proposal. + + A Vote consists of a proposal ID, the voter, and the vote option. + description: votes defined the queried votes. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: QueryVotesResponse is the response type for the Query/Votes RPC + method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: proposal_id + description: proposal_id defines the unique id of the proposal. + in: path + required: true + schema: + type: string + format: uint64 + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + schema: + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + in: query + required: false + schema: + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + schema: + type: boolean + tags: + - gRPC Gateway API + "/cosmos/gov/v1beta1/proposals/{proposal_id}/votes/{voter}": + get: + summary: Vote queries voted information based on proposalID, voterAddr. + operationId: Vote_ELJSA + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + vote: + type: object + properties: + proposal_id: + type: string + format: uint64 + voter: + type: string + option: + description: >- + Deprecated: Prefer to use `options` instead. This + field is set in queries + + if and only if `len(options) == 1` and that option has weight 1. In all + + other cases, this field will default to VOTE_OPTION_UNSPECIFIED. + type: string + enum: + - VOTE_OPTION_UNSPECIFIED + - VOTE_OPTION_YES + - VOTE_OPTION_ABSTAIN + - VOTE_OPTION_NO + - VOTE_OPTION_NO_WITH_VETO + default: VOTE_OPTION_UNSPECIFIED + options: + type: array + items: + type: object + properties: + option: + type: string + enum: + - VOTE_OPTION_UNSPECIFIED + - VOTE_OPTION_YES + - VOTE_OPTION_ABSTAIN + - VOTE_OPTION_NO + - VOTE_OPTION_NO_WITH_VETO + default: VOTE_OPTION_UNSPECIFIED + description: >- + VoteOption enumerates the valid vote options for + a given governance proposal. + + - VOTE_OPTION_UNSPECIFIED: VOTE_OPTION_UNSPECIFIED defines a no-op vote option. + - VOTE_OPTION_YES: VOTE_OPTION_YES defines a yes vote option. + - VOTE_OPTION_ABSTAIN: VOTE_OPTION_ABSTAIN defines an abstain vote option. + - VOTE_OPTION_NO: VOTE_OPTION_NO defines a no vote option. + - VOTE_OPTION_NO_WITH_VETO: VOTE_OPTION_NO_WITH_VETO defines a no with veto vote option. + weight: + type: string + description: >- + WeightedVoteOption defines a unit of vote for vote + split. + + + Since: cosmos-sdk 0.43 + title: "Since: cosmos-sdk 0.43" + description: >- + Vote defines a vote on a governance proposal. + + A Vote consists of a proposal ID, the voter, and the vote option. + description: QueryVoteResponse is the response type for the Query/Vote RPC + method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: proposal_id + description: proposal_id defines the unique id of the proposal. + in: path + required: true + schema: + type: string + format: uint64 + - name: voter + description: voter defines the oter address for the proposals. + in: path + required: true + schema: + type: string + tags: + - gRPC Gateway API + get: + summary: Params retrieves the FeeShare module params + operationId: Params_4OI6Q + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + params: + title: params is the returned FeeShare parameter + type: object + properties: + enable_fee_share: + type: boolean + title: enable_feeshare defines a parameter to enable the feeshare module + developer_shares: + type: string + title: >- + developer_shares defines the proportion of the + transaction fees to be + + distributed to the registered contract owner + allowed_denoms: + type: array + items: + type: string + description: >- + allowed_denoms defines the list of denoms that are + allowed to be paid to + + the contract withdraw addresses. If said denom is not in the list, the fees + + will ONLY be sent to the community pool. + + If this list is empty, all denoms are allowed. + description: QueryParamsResponse is the response type for the Query/Params RPC + method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + /cosmos/slashing/v1beta1/params: + get: + summary: Params queries the parameters of slashing module + operationId: Params_EP1KV + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + params: + type: object + properties: + signed_blocks_window: + type: string + format: int64 + min_signed_per_window: + type: string + format: byte + downtime_jail_duration: + type: string + slash_fraction_double_sign: + type: string + format: byte + slash_fraction_downtime: + type: string + format: byte + description: Params represents the parameters used for by the slashing module. + title: QueryParamsResponse is the response type for the Query/Params RPC method + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + /cosmos/slashing/v1beta1/signing_infos: + get: + summary: SigningInfos queries signing info of all validators + operationId: SigningInfos_TR6NI + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + info: + type: array + items: + type: object + properties: + address: + type: string + start_height: + type: string + format: int64 + title: Height at which validator was first a candidate OR was unjailed + index_offset: + type: string + format: int64 + description: >- + Index which is incremented each time the validator + was a bonded + + in a block and may have signed a precommit or not. This in conjunction with the + + `SignedBlocksWindow` param determines the index in the `MissedBlocksBitArray`. + jailed_until: + type: string + format: date-time + description: Timestamp until which the validator is jailed due to liveness + downtime. + tombstoned: + type: boolean + description: >- + Whether or not a validator has been tombstoned + (killed out of validator set). It is set + + once the validator commits an equivocation or for any other configured misbehiavor. + missed_blocks_counter: + type: string + format: int64 + description: >- + A counter kept to avoid unnecessary array reads. + + Note that `Sum(MissedBlocksBitArray)` always equals `MissedBlocksCounter`. + description: >- + ValidatorSigningInfo defines a validator's signing info + for monitoring their + + liveness activity. + title: info is the signing info of all validators + pagination: + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + PageResponse is to be embedded in gRPC response messages + where the + + corresponding request message has used PageRequest. + + message SomeResponse { + repeated Bar results = 1; + PageResponse page = 2; + } + title: >- + QuerySigningInfosResponse is the response type for the + Query/SigningInfos RPC + + method + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + schema: + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + in: query + required: false + schema: + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + schema: + type: boolean + tags: + - gRPC Gateway API + "/cosmos/slashing/v1beta1/signing_infos/{cons_address}": + get: + summary: SigningInfo queries the signing info of given cons address + operationId: SigningInfo_8QMFV + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + val_signing_info: + type: object + properties: + address: + type: string + start_height: + type: string + format: int64 + title: Height at which validator was first a candidate OR was unjailed + index_offset: + type: string + format: int64 + description: >- + Index which is incremented each time the validator was + a bonded + + in a block and may have signed a precommit or not. This in conjunction with the + + `SignedBlocksWindow` param determines the index in the `MissedBlocksBitArray`. + jailed_until: + type: string + format: date-time + description: Timestamp until which the validator is jailed due to liveness + downtime. + tombstoned: + type: boolean + description: >- + Whether or not a validator has been tombstoned (killed + out of validator set). It is set + + once the validator commits an equivocation or for any other configured misbehiavor. + missed_blocks_counter: + type: string + format: int64 + description: >- + A counter kept to avoid unnecessary array reads. + + Note that `Sum(MissedBlocksBitArray)` always equals `MissedBlocksCounter`. + description: >- + ValidatorSigningInfo defines a validator's signing info + for monitoring their + + liveness activity. + title: val_signing_info is the signing info of requested val cons address + title: >- + QuerySigningInfoResponse is the response type for the + Query/SigningInfo RPC + + method + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: cons_address + description: cons_address is the address to query signing info of + in: path + required: true + schema: + type: string + tags: + - gRPC Gateway API + "/cosmos/upgrade/v1beta1/applied_plan/{name}": + get: + summary: AppliedPlan queries a previously applied upgrade plan by its name. + operationId: AppliedPlan_4G511 + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + height: + type: string + format: int64 + description: height is the block height at which the plan was applied. + description: >- + QueryAppliedPlanResponse is the response type for the + Query/AppliedPlan RPC + + method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: name + description: name is the name of the applied plan to query for. + in: path + required: true + schema: + type: string + tags: + - gRPC Gateway API + /cosmos/upgrade/v1beta1/current_plan: + get: + summary: CurrentPlan queries the current upgrade plan. + operationId: CurrentPlan_EEL3L + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + plan: + description: plan is the current upgrade plan. + type: object + properties: + name: + type: string + description: >- + Sets the name for the upgrade. This name will be used + by the upgraded + + version of the software to apply any special "on-upgrade" commands during + + the first BeginBlock method after the upgrade is applied. It is also used + + to detect whether a software version can handle a given upgrade. If no + + upgrade handler with this name has been set in the software, it will be + + assumed that the software is out-of-date when the upgrade Time or Height is + + reached and the software will exit. + time: + type: string + format: date-time + description: >- + Deprecated: Time based upgrades have been deprecated. + Time based upgrade logic + + has been removed from the SDK. + + If this field is not empty, an error will be thrown. + height: + type: string + format: int64 + description: |- + The height at which the upgrade must be performed. + Only used if Time is not set. + info: + type: string + title: >- + Any application specific upgrade info to be included + on-chain + + such as a git commit that validators could automatically upgrade to + upgraded_client_state: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + Deprecated: UpgradedClientState field has been + deprecated. IBC upgrade logic has been + + moved to the IBC module in the sub module 02-client. + + If this field is not empty, an error will be thrown. + description: >- + QueryCurrentPlanResponse is the response type for the + Query/CurrentPlan RPC + + method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + /cosmos/upgrade/v1beta1/module_versions: + get: + summary: ModuleVersions queries the list of module versions from state. + description: "Since: cosmos-sdk 0.43" + operationId: ModuleVersions_PJ2IL + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + module_versions: + type: array + items: + type: object + properties: + name: + type: string + title: name of the app module + version: + type: string + format: uint64 + title: consensus version of the app module + description: >- + ModuleVersion specifies a module and its consensus + version. + + + Since: cosmos-sdk 0.43 + description: module_versions is a list of module names with their consensus + versions. + description: >- + QueryModuleVersionsResponse is the response type for the + Query/ModuleVersions + + RPC method. + + + Since: cosmos-sdk 0.43 + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: module_name + description: |- + module_name is a field to query a specific module + consensus version from state. Leaving this empty will + fetch the full list of module versions from state. + in: query + required: false + schema: + type: string + tags: + - gRPC Gateway API + "/cosmos/upgrade/v1beta1/upgraded_consensus_state/{last_height}": + get: + summary: >- + UpgradedConsensusState queries the consensus state that will serve + + as a trusted kernel for the next version of this chain. It will only be + + stored at the last height of this chain. + + UpgradedConsensusState RPC not supported with legacy querier + + This rpc is deprecated now that IBC has its own replacement + + (https://github.com/cosmos/ibc-go/blob/2c880a22e9f9cc75f62b527ca94aa75ce1106001/proto/ibc/core/client/v1/query.proto#L54) + operationId: UpgradedConsensusState_NHBES + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + upgraded_consensus_state: + type: string + format: byte + title: "Since: cosmos-sdk 0.43" + description: >- + QueryUpgradedConsensusStateResponse is the response type for + the Query/UpgradedConsensusState + + RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: last_height + description: |- + last height of the current chain must be sent in request + as this is the height under which next consensus state is stored + in: path + required: true + schema: + type: string + format: int64 + tags: + - gRPC Gateway API + /cosmos/authz/v1beta1/grants: + get: + summary: Returns list of `Authorization`, granted to the grantee by the granter. + operationId: Grants_0MX8R + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + grants: + type: array + items: + type: object + properties: + authorization: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + expiration: + type: string + format: date-time + description: |- + Grant gives permissions to execute + the provide method with expiration time. + description: authorizations is a list of grants granted for grantee by granter. + pagination: + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + PageResponse is to be embedded in gRPC response messages + where the + + corresponding request message has used PageRequest. + + message SomeResponse { + repeated Bar results = 1; + PageResponse page = 2; + } + description: QueryGrantsResponse is the response type for the + Query/Authorizations RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: granter + in: query + required: false + schema: + type: string + - name: grantee + in: query + required: false + schema: + type: string + - name: msg_type_url + description: Optional, msg_type_url, when set, will query only grants matching + given msg type. + in: query + required: false + schema: + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + schema: + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + in: query + required: false + schema: + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + schema: + type: boolean + tags: + - gRPC Gateway API + "/cosmos/authz/v1beta1/grants/grantee/{grantee}": + get: + summary: GranteeGrants returns a list of `GrantAuthorization` by grantee. + description: "Since: cosmos-sdk 0.45.2" + operationId: GranteeGrants_8IKJS + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + grants: + type: array + items: + type: object + properties: + granter: + type: string + grantee: + type: string + authorization: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + expiration: + type: string + format: date-time + description: "Since: cosmos-sdk 0.45.2" + title: >- + GrantAuthorization extends a grant with both the + addresses of the grantee and granter. + + It is used in genesis.proto and query.proto + description: grants is a list of grants granted to the grantee. + pagination: + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + PageResponse is to be embedded in gRPC response messages + where the + + corresponding request message has used PageRequest. + + message SomeResponse { + repeated Bar results = 1; + PageResponse page = 2; + } + description: QueryGranteeGrantsResponse is the response type for the + Query/GranteeGrants RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: grantee + in: path + required: true + schema: + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + schema: + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + in: query + required: false + schema: + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + schema: + type: boolean + tags: + - gRPC Gateway API + "/cosmos/authz/v1beta1/grants/granter/{granter}": + get: + summary: GranterGrants returns list of `GrantAuthorization`, granted by granter. + description: "Since: cosmos-sdk 0.45.2" + operationId: GranterGrants_NWMPX + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + grants: + type: array + items: + type: object + properties: + granter: + type: string + grantee: + type: string + authorization: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + expiration: + type: string + format: date-time + description: "Since: cosmos-sdk 0.45.2" + title: >- + GrantAuthorization extends a grant with both the + addresses of the grantee and granter. + + It is used in genesis.proto and query.proto + description: grants is a list of grants granted by the granter. + pagination: + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + PageResponse is to be embedded in gRPC response messages + where the + + corresponding request message has used PageRequest. + + message SomeResponse { + repeated Bar results = 1; + PageResponse page = 2; + } + description: QueryGranterGrantsResponse is the response type for the + Query/GranterGrants RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: granter + in: path + required: true + schema: + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + schema: + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + schema: + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + in: query + required: false + schema: + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + schema: + type: boolean + tags: + - gRPC Gateway API + /cosmos/mint/v1beta1/annual_provisions: + get: + summary: AnnualProvisions current minting annual provisions value. + operationId: AnnualProvisions_WMS1W + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + annual_provisions: + type: string + format: byte + description: annual_provisions is the current minting annual provisions value. + description: |- + QueryAnnualProvisionsResponse is the response type for the + Query/AnnualProvisions RPC method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + /cosmos/mint/v1beta1/inflation: + get: + summary: Inflation returns the current minting inflation value. + operationId: Inflation_SI7I6 + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + inflation: + type: string + format: byte + description: inflation is the current minting inflation value. + description: >- + QueryInflationResponse is the response type for the + Query/Inflation RPC + + method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + /cosmos/mint/v1beta1/params: + get: + summary: Params returns the total set of minting parameters. + operationId: Params_H9W1T + responses: + "200": + description: A successful response. + content: + application/json: + schema: + type: object + properties: + params: + description: params defines the parameters of the module. + type: object + properties: + mint_denom: + type: string + title: type of coin to mint + blocks_per_year: + type: string + format: uint64 + title: expected blocks per year + description: QueryParamsResponse is the response type for the Query/Params RPC + method. + default: + description: An unexpected error response. + content: + application/json: + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API +components: + schemas: + cosmos.auth.v1beta1.Params: + type: object + properties: + max_memo_characters: + type: string + format: uint64 + tx_sig_limit: + type: string + format: uint64 + tx_size_cost_per_byte: + type: string + format: uint64 + sig_verify_cost_ed25519: + type: string + format: uint64 + sig_verify_cost_secp256k1: + type: string + format: uint64 + description: Params defines the parameters for the auth module. + cosmos.auth.v1beta1.QueryAccountResponse: + type: object + properties: + account: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: account defines the account of the corresponding address. + description: QueryAccountResponse is the response type for the Query/Account RPC + method. + cosmos.auth.v1beta1.QueryAccountsResponse: + type: object + properties: + accounts: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: accounts are the existing accounts + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryAccountsResponse is the response type for the Query/Accounts RPC + method. + + + Since: cosmos-sdk 0.43 + cosmos.auth.v1beta1.QueryModuleAccountByNameResponse: + type: object + properties: + account: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: QueryModuleAccountByNameResponse is the response type for the + Query/ModuleAccountByName RPC method. + cosmos.auth.v1beta1.QueryParamsResponse: + type: object + properties: + params: + description: params defines the parameters of the module. + type: object + properties: + max_memo_characters: + type: string + format: uint64 + tx_sig_limit: + type: string + format: uint64 + tx_size_cost_per_byte: + type: string + format: uint64 + sig_verify_cost_ed25519: + type: string + format: uint64 + sig_verify_cost_secp256k1: + type: string + format: uint64 + description: QueryParamsResponse is the response type for the Query/Params RPC method. + cosmos.base.query.v1beta1.PageRequest: + type: object + properties: + key: + type: string + format: byte + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + offset: + type: string + format: uint64 + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key should + + be set. + limit: + type: string + format: uint64 + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + count_total: + type: boolean + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when key + + is set. + reverse: + type: boolean + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + description: |- + message SomeRequest { + Foo some_parameter = 1; + PageRequest pagination = 2; + } + title: |- + PageRequest is to be embedded in gRPC request messages for efficient + pagination. Ex: + cosmos.base.query.v1beta1.PageResponse: + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + PageResponse is to be embedded in gRPC response messages where the + corresponding request message has used PageRequest. + + message SomeResponse { + repeated Bar results = 1; + PageResponse page = 2; + } + google.protobuf.Any: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + grpc.gateway.runtime.Error: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + cosmos.bank.v1beta1.DenomUnit: + type: object + properties: + denom: + type: string + description: denom represents the string name of the given denom unit (e.g uatom). + exponent: + type: integer + format: int64 + description: >- + 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). + aliases: + type: array + items: + type: string + title: aliases is a list of string aliases for the given denom + description: |- + DenomUnit represents a struct that describes a given + denomination unit of the basic token. + cosmos.bank.v1beta1.Metadata: + type: object + properties: + description: + type: string + denom_units: + type: array + items: + type: object + properties: + denom: + type: string + description: denom represents the string name of the given denom unit (e.g + uatom). + exponent: + type: integer + format: int64 + description: >- + 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). + aliases: + type: array + items: + type: string + title: aliases is a list of string aliases for the given denom + description: |- + DenomUnit represents a struct that describes a given + denomination unit of the basic token. + title: denom_units represents the list of DenomUnit's for a given coin + base: + type: string + description: base represents the base denom (should be the DenomUnit with + exponent = 0). + display: + type: string + description: |- + display indicates the suggested denom that should be + displayed in clients. + name: + type: string + description: "Since: cosmos-sdk 0.43" + title: "name defines the name of the token (eg: Cosmos Atom)" + symbol: + type: string + description: >- + symbol is the token symbol usually shown on exchanges (eg: ATOM). + This can + + be the same as the display. + + + Since: cosmos-sdk 0.43 + description: |- + Metadata represents a struct that describes + a basic token. + cosmos.bank.v1beta1.Params: + type: object + properties: + send_enabled: + type: array + items: + type: object + properties: + denom: + type: string + enabled: + type: boolean + description: >- + SendEnabled maps coin denom to a send_enabled status (whether a + denom is + + sendable). + default_send_enabled: + type: boolean + description: Params defines the parameters for the bank module. + cosmos.bank.v1beta1.QueryAllBalancesResponse: + type: object + properties: + balances: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + description: balances is the balances of all the coins. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryAllBalancesResponse is the response type for the Query/AllBalances + RPC + + method. + cosmos.bank.v1beta1.QueryBalanceResponse: + type: object + properties: + balance: + type: object + properties: + denom: + type: string + amount: + type: string + description: |- + Coin defines a token with a denomination and an amount. + + NOTE: The amount field is an Int which implements the custom method + signatures required by gogoproto. + description: QueryBalanceResponse is the response type for the Query/Balance RPC + method. + cosmos.bank.v1beta1.QueryDenomMetadataResponse: + type: object + properties: + metadata: + type: object + properties: + description: + type: string + denom_units: + type: array + items: + type: object + properties: + denom: + type: string + description: denom represents the string name of the given denom unit (e.g + uatom). + exponent: + type: integer + format: int64 + description: >- + 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). + aliases: + type: array + items: + type: string + title: aliases is a list of string aliases for the given denom + description: |- + DenomUnit represents a struct that describes a given + denomination unit of the basic token. + title: denom_units represents the list of DenomUnit's for a given coin + base: + type: string + description: base represents the base denom (should be the DenomUnit with + exponent = 0). + display: + type: string + description: |- + display indicates the suggested denom that should be + displayed in clients. + name: + type: string + description: "Since: cosmos-sdk 0.43" + title: "name defines the name of the token (eg: Cosmos Atom)" + symbol: + type: string + description: >- + symbol is the token symbol usually shown on exchanges (eg: + ATOM). This can + + be the same as the display. + + + Since: cosmos-sdk 0.43 + description: |- + Metadata represents a struct that describes + a basic token. + description: >- + QueryDenomMetadataResponse is the response type for the + Query/DenomMetadata RPC + + method. + cosmos.bank.v1beta1.QueryDenomsMetadataResponse: + type: object + properties: + metadatas: + type: array + items: + type: object + properties: + description: + type: string + denom_units: + type: array + items: + type: object + properties: + denom: + type: string + description: denom represents the string name of the given denom unit (e.g + uatom). + exponent: + type: integer + format: int64 + description: >- + 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). + aliases: + type: array + items: + type: string + title: aliases is a list of string aliases for the given denom + description: |- + DenomUnit represents a struct that describes a given + denomination unit of the basic token. + title: denom_units represents the list of DenomUnit's for a given coin + base: + type: string + description: base represents the base denom (should be the DenomUnit with + exponent = 0). + display: + type: string + description: |- + display indicates the suggested denom that should be + displayed in clients. + name: + type: string + description: "Since: cosmos-sdk 0.43" + title: "name defines the name of the token (eg: Cosmos Atom)" + symbol: + type: string + description: >- + symbol is the token symbol usually shown on exchanges (eg: + ATOM). This can + + be the same as the display. + + + Since: cosmos-sdk 0.43 + description: |- + Metadata represents a struct that describes + a basic token. + description: metadata provides the client information for all the registered + tokens. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryDenomsMetadataResponse is the response type for the + Query/DenomsMetadata RPC + + method. + cosmos.bank.v1beta1.QueryParamsResponse: + type: object + properties: + params: + type: object + properties: + send_enabled: + type: array + items: + type: object + properties: + denom: + type: string + enabled: + type: boolean + description: >- + SendEnabled maps coin denom to a send_enabled status (whether + a denom is + + sendable). + default_send_enabled: + type: boolean + description: Params defines the parameters for the bank module. + description: QueryParamsResponse defines the response type for querying x/bank + parameters. + cosmos.bank.v1beta1.QuerySpendableBalancesResponse: + type: object + properties: + balances: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + description: balances is the spendable balances of all the coins. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QuerySpendableBalancesResponse defines the gRPC response structure for + querying + + an account's spendable balances. + cosmos.bank.v1beta1.QuerySupplyOfResponse: + type: object + properties: + amount: + type: object + properties: + denom: + type: string + amount: + type: string + description: |- + Coin defines a token with a denomination and an amount. + + NOTE: The amount field is an Int which implements the custom method + signatures required by gogoproto. + description: QuerySupplyOfResponse is the response type for the Query/SupplyOf + RPC method. + cosmos.bank.v1beta1.QueryTotalSupplyResponse: + type: object + properties: + supply: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + title: supply is the supply of the coins + pagination: + description: |- + pagination defines the pagination in the response. + + Since: cosmos-sdk 0.43 + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + title: >- + QueryTotalSupplyResponse is the response type for the Query/TotalSupply + RPC + + method + cosmos.bank.v1beta1.SendEnabled: + type: object + properties: + denom: + type: string + enabled: + type: boolean + description: |- + SendEnabled maps coin denom to a send_enabled status (whether a denom is + sendable). + cosmos.base.v1beta1.Coin: + type: object + properties: + denom: + type: string + amount: + type: string + description: |- + Coin defines a token with a denomination and an amount. + + NOTE: The amount field is an Int which implements the custom method + signatures required by gogoproto. + cosmos.staking.v1beta1.BondStatus: + type: string + enum: + - BOND_STATUS_UNSPECIFIED + - BOND_STATUS_UNBONDED + - BOND_STATUS_UNBONDING + - BOND_STATUS_BONDED + default: BOND_STATUS_UNSPECIFIED + description: >- + BondStatus is the status of a validator. + + - BOND_STATUS_UNSPECIFIED: UNSPECIFIED defines an invalid validator status. + - BOND_STATUS_UNBONDED: UNBONDED defines a validator that is not bonded. + - BOND_STATUS_UNBONDING: UNBONDING defines a validator that is unbonding. + - BOND_STATUS_BONDED: BONDED defines a validator that is bonded. + cosmos.staking.v1beta1.Commission: + type: object + properties: + commission_rates: + description: commission_rates defines the initial commission rates to be used + for creating a validator. + type: object + properties: + rate: + type: string + description: rate is the commission rate charged to delegators, as a fraction. + max_rate: + type: string + description: max_rate defines the maximum commission rate which validator can + ever charge, as a fraction. + max_change_rate: + type: string + description: max_change_rate defines the maximum daily increase of the validator + commission, as a fraction. + update_time: + type: string + format: date-time + description: update_time is the last time the commission rate was changed. + description: Commission defines commission parameters for a given validator. + cosmos.staking.v1beta1.CommissionRates: + type: object + properties: + rate: + type: string + description: rate is the commission rate charged to delegators, as a fraction. + max_rate: + type: string + description: max_rate defines the maximum commission rate which validator can + ever charge, as a fraction. + max_change_rate: + type: string + description: max_change_rate defines the maximum daily increase of the validator + commission, as a fraction. + description: >- + CommissionRates defines the initial commission rates to be used for + creating + + a validator. + cosmos.staking.v1beta1.Delegation: + type: object + properties: + delegator_address: + type: string + description: delegator_address is the bech32-encoded address of the delegator. + validator_address: + type: string + description: validator_address is the bech32-encoded address of the validator. + shares: + type: string + description: shares define the delegation shares received. + description: |- + Delegation represents the bond with tokens held by an account. It is + owned by one delegator, and is associated with the voting power of one + validator. + cosmos.staking.v1beta1.DelegationResponse: + type: object + properties: + delegation: + type: object + properties: + delegator_address: + type: string + description: delegator_address is the bech32-encoded address of the delegator. + validator_address: + type: string + description: validator_address is the bech32-encoded address of the validator. + shares: + type: string + description: shares define the delegation shares received. + description: >- + Delegation represents the bond with tokens held by an account. It is + + owned by one delegator, and is associated with the voting power of one + + validator. + balance: + type: object + properties: + denom: + type: string + amount: + type: string + description: |- + Coin defines a token with a denomination and an amount. + + NOTE: The amount field is an Int which implements the custom method + signatures required by gogoproto. + description: >- + DelegationResponse is equivalent to Delegation except that it contains a + + balance in addition to shares which is more suitable for client responses. + cosmos.staking.v1beta1.Description: + type: object + properties: + moniker: + type: string + description: moniker defines a human-readable name for the validator. + identity: + type: string + description: identity defines an optional identity signature (ex. UPort or + Keybase). + website: + type: string + description: website defines an optional website link. + security_contact: + type: string + description: security_contact defines an optional email for security contact. + details: + type: string + description: details define other optional details. + description: Description defines a validator description. + cosmos.staking.v1beta1.HistoricalInfo: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for processing a block in + the blockchain, + + including all blockchain data structures and the rules of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + valset: + type: array + items: + type: object + properties: + operator_address: + type: string + description: operator_address defines the address of the validator's operator; + bech encoded in JSON. + consensus_pubkey: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: consensus_pubkey is the consensus public key of the validator, as a + Protobuf Any. + jailed: + type: boolean + description: jailed defined whether the validator has been jailed from bonded + status or not. + status: + description: status is the validator status (bonded/unbonding/unbonded). + type: string + enum: + - BOND_STATUS_UNSPECIFIED + - BOND_STATUS_UNBONDED + - BOND_STATUS_UNBONDING + - BOND_STATUS_BONDED + default: BOND_STATUS_UNSPECIFIED + tokens: + type: string + description: tokens define the delegated tokens (incl. self-delegation). + delegator_shares: + type: string + description: delegator_shares defines total shares issued to a validator's + delegators. + description: + description: description defines the description terms for the validator. + type: object + properties: + moniker: + type: string + description: moniker defines a human-readable name for the validator. + identity: + type: string + description: identity defines an optional identity signature (ex. UPort or + Keybase). + website: + type: string + description: website defines an optional website link. + security_contact: + type: string + description: security_contact defines an optional email for security contact. + details: + type: string + description: details define other optional details. + unbonding_height: + type: string + format: int64 + description: unbonding_height defines, if unbonding, the height at which this + validator has begun unbonding. + unbonding_time: + type: string + format: date-time + description: unbonding_time defines, if unbonding, the min time for the + validator to complete unbonding. + commission: + description: commission defines the commission parameters. + type: object + properties: + commission_rates: + description: commission_rates defines the initial commission rates to be used + for creating a validator. + type: object + properties: + rate: + type: string + description: rate is the commission rate charged to delegators, as a fraction. + max_rate: + type: string + description: max_rate defines the maximum commission rate which validator can + ever charge, as a fraction. + max_change_rate: + type: string + description: max_change_rate defines the maximum daily increase of the validator + commission, as a fraction. + update_time: + type: string + format: date-time + description: update_time is the last time the commission rate was changed. + min_self_delegation: + type: string + description: min_self_delegation is the validator's self declared minimum self + delegation. + description: >- + Validator defines a validator, together with the total amount of + the + + Validator's bond shares and their exchange rate to coins. Slashing results in + + a decrease in the exchange rate, allowing correct calculation of future + + undelegations without iterating over delegators. When coins are delegated to + + this validator, the validator is credited with a delegation whose number of + + bond shares is based on the amount of coins delegated divided by the current + + exchange rate. Voting power can be calculated as total bonded shares + + multiplied by exchange rate. + description: >- + HistoricalInfo contains header and validator information for a given + block. + + It is stored as part of staking module's state, which persists the `n` most + + recent HistoricalInfo + + (`n` is set by the staking module's `historical_entries` parameter). + cosmos.staking.v1beta1.Params: + type: object + properties: + unbonding_time: + type: string + description: unbonding_time is the time duration of unbonding. + max_validators: + type: integer + format: int64 + description: max_validators is the maximum number of validators. + max_entries: + type: integer + format: int64 + description: max_entries is the max entries for either unbonding delegation or + redelegation (per pair/trio). + historical_entries: + type: integer + format: int64 + description: historical_entries is the number of historical entries to persist. + bond_denom: + type: string + description: bond_denom defines the bondable coin denomination. + description: Params defines the parameters for the staking module. + cosmos.staking.v1beta1.Pool: + type: object + properties: + not_bonded_tokens: + type: string + bonded_tokens: + type: string + description: |- + Pool is used for tracking bonded and not-bonded token supply of the bond + denomination. + cosmos.staking.v1beta1.QueryDelegationResponse: + type: object + properties: + delegation_response: + type: object + properties: + delegation: + type: object + properties: + delegator_address: + type: string + description: delegator_address is the bech32-encoded address of the delegator. + validator_address: + type: string + description: validator_address is the bech32-encoded address of the validator. + shares: + type: string + description: shares define the delegation shares received. + description: >- + Delegation represents the bond with tokens held by an account. + It is + + owned by one delegator, and is associated with the voting power of one + + validator. + balance: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + description: >- + DelegationResponse is equivalent to Delegation except that it + contains a + + balance in addition to shares which is more suitable for client responses. + description: QueryDelegationResponse is response type for the Query/Delegation + RPC method. + cosmos.staking.v1beta1.QueryDelegatorDelegationsResponse: + type: object + properties: + delegation_responses: + type: array + items: + type: object + properties: + delegation: + type: object + properties: + delegator_address: + type: string + description: delegator_address is the bech32-encoded address of the delegator. + validator_address: + type: string + description: validator_address is the bech32-encoded address of the validator. + shares: + type: string + description: shares define the delegation shares received. + description: >- + Delegation represents the bond with tokens held by an account. + It is + + owned by one delegator, and is associated with the voting power of one + + validator. + balance: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + description: >- + DelegationResponse is equivalent to Delegation except that it + contains a + + balance in addition to shares which is more suitable for client responses. + description: delegation_responses defines all the delegations' info of a + delegator. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + QueryDelegatorDelegationsResponse is response type for the + Query/DelegatorDelegations RPC method. + cosmos.staking.v1beta1.QueryDelegatorUnbondingDelegationsResponse: + type: object + properties: + unbonding_responses: + type: array + items: + type: object + properties: + delegator_address: + type: string + description: delegator_address is the bech32-encoded address of the delegator. + validator_address: + type: string + description: validator_address is the bech32-encoded address of the validator. + entries: + type: array + items: + type: object + properties: + creation_height: + type: string + format: int64 + description: creation_height is the height which the unbonding took place. + completion_time: + type: string + format: date-time + description: completion_time is the unix time for unbonding completion. + initial_balance: + type: string + description: initial_balance defines the tokens initially scheduled to receive + at completion. + balance: + type: string + description: balance defines the tokens to receive at completion. + description: UnbondingDelegationEntry defines an unbonding object with relevant + metadata. + description: entries are the unbonding delegation entries. + description: >- + UnbondingDelegation stores all of a single delegator's unbonding + bonds + + for a single validator in an time-ordered list. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + QueryUnbondingDelegatorDelegationsResponse is response type for the + Query/UnbondingDelegatorDelegations RPC method. + cosmos.staking.v1beta1.QueryDelegatorValidatorResponse: + type: object + properties: + validator: + type: object + properties: + operator_address: + type: string + description: operator_address defines the address of the validator's operator; + bech encoded in JSON. + consensus_pubkey: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: consensus_pubkey is the consensus public key of the validator, as a + Protobuf Any. + jailed: + type: boolean + description: jailed defined whether the validator has been jailed from bonded + status or not. + status: + description: status is the validator status (bonded/unbonding/unbonded). + type: string + enum: + - BOND_STATUS_UNSPECIFIED + - BOND_STATUS_UNBONDED + - BOND_STATUS_UNBONDING + - BOND_STATUS_BONDED + default: BOND_STATUS_UNSPECIFIED + tokens: + type: string + description: tokens define the delegated tokens (incl. self-delegation). + delegator_shares: + type: string + description: delegator_shares defines total shares issued to a validator's + delegators. + description: + description: description defines the description terms for the validator. + type: object + properties: + moniker: + type: string + description: moniker defines a human-readable name for the validator. + identity: + type: string + description: identity defines an optional identity signature (ex. UPort or + Keybase). + website: + type: string + description: website defines an optional website link. + security_contact: + type: string + description: security_contact defines an optional email for security contact. + details: + type: string + description: details define other optional details. + unbonding_height: + type: string + format: int64 + description: unbonding_height defines, if unbonding, the height at which this + validator has begun unbonding. + unbonding_time: + type: string + format: date-time + description: unbonding_time defines, if unbonding, the min time for the + validator to complete unbonding. + commission: + description: commission defines the commission parameters. + type: object + properties: + commission_rates: + description: commission_rates defines the initial commission rates to be used + for creating a validator. + type: object + properties: + rate: + type: string + description: rate is the commission rate charged to delegators, as a fraction. + max_rate: + type: string + description: max_rate defines the maximum commission rate which validator can + ever charge, as a fraction. + max_change_rate: + type: string + description: max_change_rate defines the maximum daily increase of the validator + commission, as a fraction. + update_time: + type: string + format: date-time + description: update_time is the last time the commission rate was changed. + min_self_delegation: + type: string + description: min_self_delegation is the validator's self declared minimum self + delegation. + description: >- + Validator defines a validator, together with the total amount of the + + Validator's bond shares and their exchange rate to coins. Slashing results in + + a decrease in the exchange rate, allowing correct calculation of future + + undelegations without iterating over delegators. When coins are delegated to + + this validator, the validator is credited with a delegation whose number of + + bond shares is based on the amount of coins delegated divided by the current + + exchange rate. Voting power can be calculated as total bonded shares + + multiplied by exchange rate. + description: |- + QueryDelegatorValidatorResponse response type for the + Query/DelegatorValidator RPC method. + cosmos.staking.v1beta1.QueryDelegatorValidatorsResponse: + type: object + properties: + validators: + type: array + items: + type: object + properties: + operator_address: + type: string + description: operator_address defines the address of the validator's operator; + bech encoded in JSON. + consensus_pubkey: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: consensus_pubkey is the consensus public key of the validator, as a + Protobuf Any. + jailed: + type: boolean + description: jailed defined whether the validator has been jailed from bonded + status or not. + status: + description: status is the validator status (bonded/unbonding/unbonded). + type: string + enum: + - BOND_STATUS_UNSPECIFIED + - BOND_STATUS_UNBONDED + - BOND_STATUS_UNBONDING + - BOND_STATUS_BONDED + default: BOND_STATUS_UNSPECIFIED + tokens: + type: string + description: tokens define the delegated tokens (incl. self-delegation). + delegator_shares: + type: string + description: delegator_shares defines total shares issued to a validator's + delegators. + description: + description: description defines the description terms for the validator. + type: object + properties: + moniker: + type: string + description: moniker defines a human-readable name for the validator. + identity: + type: string + description: identity defines an optional identity signature (ex. UPort or + Keybase). + website: + type: string + description: website defines an optional website link. + security_contact: + type: string + description: security_contact defines an optional email for security contact. + details: + type: string + description: details define other optional details. + unbonding_height: + type: string + format: int64 + description: unbonding_height defines, if unbonding, the height at which this + validator has begun unbonding. + unbonding_time: + type: string + format: date-time + description: unbonding_time defines, if unbonding, the min time for the + validator to complete unbonding. + commission: + description: commission defines the commission parameters. + type: object + properties: + commission_rates: + description: commission_rates defines the initial commission rates to be used + for creating a validator. + type: object + properties: + rate: + type: string + description: rate is the commission rate charged to delegators, as a fraction. + max_rate: + type: string + description: max_rate defines the maximum commission rate which validator can + ever charge, as a fraction. + max_change_rate: + type: string + description: max_change_rate defines the maximum daily increase of the validator + commission, as a fraction. + update_time: + type: string + format: date-time + description: update_time is the last time the commission rate was changed. + min_self_delegation: + type: string + description: min_self_delegation is the validator's self declared minimum self + delegation. + description: >- + Validator defines a validator, together with the total amount of + the + + Validator's bond shares and their exchange rate to coins. Slashing results in + + a decrease in the exchange rate, allowing correct calculation of future + + undelegations without iterating over delegators. When coins are delegated to + + this validator, the validator is credited with a delegation whose number of + + bond shares is based on the amount of coins delegated divided by the current + + exchange rate. Voting power can be calculated as total bonded shares + + multiplied by exchange rate. + description: validators defines the the validators' info of a delegator. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + QueryDelegatorValidatorsResponse is response type for the + Query/DelegatorValidators RPC method. + cosmos.staking.v1beta1.QueryHistoricalInfoResponse: + type: object + properties: + hist: + description: hist defines the historical info at the given height. + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for processing a + block in the blockchain, + + including all blockchain data structures and the rules of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + valset: + type: array + items: + type: object + properties: + operator_address: + type: string + description: operator_address defines the address of the validator's operator; + bech encoded in JSON. + consensus_pubkey: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: consensus_pubkey is the consensus public key of the validator, as a + Protobuf Any. + jailed: + type: boolean + description: jailed defined whether the validator has been jailed from bonded + status or not. + status: + description: status is the validator status (bonded/unbonding/unbonded). + type: string + enum: + - BOND_STATUS_UNSPECIFIED + - BOND_STATUS_UNBONDED + - BOND_STATUS_UNBONDING + - BOND_STATUS_BONDED + default: BOND_STATUS_UNSPECIFIED + tokens: + type: string + description: tokens define the delegated tokens (incl. self-delegation). + delegator_shares: + type: string + description: delegator_shares defines total shares issued to a validator's + delegators. + description: + description: description defines the description terms for the validator. + type: object + properties: + moniker: + type: string + description: moniker defines a human-readable name for the validator. + identity: + type: string + description: identity defines an optional identity signature (ex. UPort or + Keybase). + website: + type: string + description: website defines an optional website link. + security_contact: + type: string + description: security_contact defines an optional email for security contact. + details: + type: string + description: details define other optional details. + unbonding_height: + type: string + format: int64 + description: unbonding_height defines, if unbonding, the height at which this + validator has begun unbonding. + unbonding_time: + type: string + format: date-time + description: unbonding_time defines, if unbonding, the min time for the + validator to complete unbonding. + commission: + description: commission defines the commission parameters. + type: object + properties: + commission_rates: + description: commission_rates defines the initial commission rates to be used + for creating a validator. + type: object + properties: + rate: + type: string + description: rate is the commission rate charged to delegators, as a fraction. + max_rate: + type: string + description: max_rate defines the maximum commission rate which validator can + ever charge, as a fraction. + max_change_rate: + type: string + description: max_change_rate defines the maximum daily increase of the validator + commission, as a fraction. + update_time: + type: string + format: date-time + description: update_time is the last time the commission rate was changed. + min_self_delegation: + type: string + description: min_self_delegation is the validator's self declared minimum self + delegation. + description: >- + Validator defines a validator, together with the total amount + of the + + Validator's bond shares and their exchange rate to coins. Slashing results in + + a decrease in the exchange rate, allowing correct calculation of future + + undelegations without iterating over delegators. When coins are delegated to + + this validator, the validator is credited with a delegation whose number of + + bond shares is based on the amount of coins delegated divided by the current + + exchange rate. Voting power can be calculated as total bonded shares + + multiplied by exchange rate. + description: >- + QueryHistoricalInfoResponse is response type for the + Query/HistoricalInfo RPC + + method. + cosmos.staking.v1beta1.QueryParamsResponse: + type: object + properties: + params: + description: params holds all the parameters of this module. + type: object + properties: + unbonding_time: + type: string + description: unbonding_time is the time duration of unbonding. + max_validators: + type: integer + format: int64 + description: max_validators is the maximum number of validators. + max_entries: + type: integer + format: int64 + description: max_entries is the max entries for either unbonding delegation or + redelegation (per pair/trio). + historical_entries: + type: integer + format: int64 + description: historical_entries is the number of historical entries to persist. + bond_denom: + type: string + description: bond_denom defines the bondable coin denomination. + description: QueryParamsResponse is response type for the Query/Params RPC method. + cosmos.staking.v1beta1.QueryPoolResponse: + type: object + properties: + pool: + description: pool defines the pool info. + type: object + properties: + not_bonded_tokens: + type: string + bonded_tokens: + type: string + description: QueryPoolResponse is response type for the Query/Pool RPC method. + cosmos.staking.v1beta1.QueryRedelegationsResponse: + type: object + properties: + redelegation_responses: + type: array + items: + type: object + properties: + redelegation: + type: object + properties: + delegator_address: + type: string + description: delegator_address is the bech32-encoded address of the delegator. + validator_src_address: + type: string + description: validator_src_address is the validator redelegation source operator + address. + validator_dst_address: + type: string + description: validator_dst_address is the validator redelegation destination + operator address. + entries: + type: array + items: + type: object + properties: + creation_height: + type: string + format: int64 + description: creation_height defines the height which the redelegation took + place. + completion_time: + type: string + format: date-time + description: completion_time defines the unix time for redelegation completion. + initial_balance: + type: string + description: initial_balance defines the initial balance when redelegation + started. + shares_dst: + type: string + description: shares_dst is the amount of destination-validator shares created by + redelegation. + description: RedelegationEntry defines a redelegation object with relevant + metadata. + description: entries are the redelegation entries. + description: >- + Redelegation contains the list of a particular delegator's + redelegating bonds + + from a particular source validator to a particular destination validator. + entries: + type: array + items: + type: object + properties: + redelegation_entry: + type: object + properties: + creation_height: + type: string + format: int64 + description: creation_height defines the height which the redelegation took + place. + completion_time: + type: string + format: date-time + description: completion_time defines the unix time for redelegation completion. + initial_balance: + type: string + description: initial_balance defines the initial balance when redelegation + started. + shares_dst: + type: string + description: shares_dst is the amount of destination-validator shares created by + redelegation. + description: RedelegationEntry defines a redelegation object with relevant + metadata. + balance: + type: string + description: >- + RedelegationEntryResponse is equivalent to a + RedelegationEntry except that it + + contains a balance in addition to shares which is more suitable for client + + responses. + description: >- + RedelegationResponse is equivalent to a Redelegation except that + its entries + + contain a balance in addition to shares which is more suitable for client + + responses. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryRedelegationsResponse is response type for the Query/Redelegations + RPC + + method. + cosmos.staking.v1beta1.QueryUnbondingDelegationResponse: + type: object + properties: + unbond: + type: object + properties: + delegator_address: + type: string + description: delegator_address is the bech32-encoded address of the delegator. + validator_address: + type: string + description: validator_address is the bech32-encoded address of the validator. + entries: + type: array + items: + type: object + properties: + creation_height: + type: string + format: int64 + description: creation_height is the height which the unbonding took place. + completion_time: + type: string + format: date-time + description: completion_time is the unix time for unbonding completion. + initial_balance: + type: string + description: initial_balance defines the tokens initially scheduled to receive + at completion. + balance: + type: string + description: balance defines the tokens to receive at completion. + description: UnbondingDelegationEntry defines an unbonding object with relevant + metadata. + description: entries are the unbonding delegation entries. + description: >- + UnbondingDelegation stores all of a single delegator's unbonding + bonds + + for a single validator in an time-ordered list. + description: >- + QueryDelegationResponse is response type for the + Query/UnbondingDelegation + + RPC method. + cosmos.staking.v1beta1.QueryValidatorDelegationsResponse: + type: object + properties: + delegation_responses: + type: array + items: + type: object + properties: + delegation: + type: object + properties: + delegator_address: + type: string + description: delegator_address is the bech32-encoded address of the delegator. + validator_address: + type: string + description: validator_address is the bech32-encoded address of the validator. + shares: + type: string + description: shares define the delegation shares received. + description: >- + Delegation represents the bond with tokens held by an account. + It is + + owned by one delegator, and is associated with the voting power of one + + validator. + balance: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + description: >- + DelegationResponse is equivalent to Delegation except that it + contains a + + balance in addition to shares which is more suitable for client responses. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + title: |- + QueryValidatorDelegationsResponse is response type for the + Query/ValidatorDelegations RPC method + cosmos.staking.v1beta1.QueryValidatorResponse: + type: object + properties: + validator: + type: object + properties: + operator_address: + type: string + description: operator_address defines the address of the validator's operator; + bech encoded in JSON. + consensus_pubkey: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: consensus_pubkey is the consensus public key of the validator, as a + Protobuf Any. + jailed: + type: boolean + description: jailed defined whether the validator has been jailed from bonded + status or not. + status: + description: status is the validator status (bonded/unbonding/unbonded). + type: string + enum: + - BOND_STATUS_UNSPECIFIED + - BOND_STATUS_UNBONDED + - BOND_STATUS_UNBONDING + - BOND_STATUS_BONDED + default: BOND_STATUS_UNSPECIFIED + tokens: + type: string + description: tokens define the delegated tokens (incl. self-delegation). + delegator_shares: + type: string + description: delegator_shares defines total shares issued to a validator's + delegators. + description: + description: description defines the description terms for the validator. + type: object + properties: + moniker: + type: string + description: moniker defines a human-readable name for the validator. + identity: + type: string + description: identity defines an optional identity signature (ex. UPort or + Keybase). + website: + type: string + description: website defines an optional website link. + security_contact: + type: string + description: security_contact defines an optional email for security contact. + details: + type: string + description: details define other optional details. + unbonding_height: + type: string + format: int64 + description: unbonding_height defines, if unbonding, the height at which this + validator has begun unbonding. + unbonding_time: + type: string + format: date-time + description: unbonding_time defines, if unbonding, the min time for the + validator to complete unbonding. + commission: + description: commission defines the commission parameters. + type: object + properties: + commission_rates: + description: commission_rates defines the initial commission rates to be used + for creating a validator. + type: object + properties: + rate: + type: string + description: rate is the commission rate charged to delegators, as a fraction. + max_rate: + type: string + description: max_rate defines the maximum commission rate which validator can + ever charge, as a fraction. + max_change_rate: + type: string + description: max_change_rate defines the maximum daily increase of the validator + commission, as a fraction. + update_time: + type: string + format: date-time + description: update_time is the last time the commission rate was changed. + min_self_delegation: + type: string + description: min_self_delegation is the validator's self declared minimum self + delegation. + description: >- + Validator defines a validator, together with the total amount of the + + Validator's bond shares and their exchange rate to coins. Slashing results in + + a decrease in the exchange rate, allowing correct calculation of future + + undelegations without iterating over delegators. When coins are delegated to + + this validator, the validator is credited with a delegation whose number of + + bond shares is based on the amount of coins delegated divided by the current + + exchange rate. Voting power can be calculated as total bonded shares + + multiplied by exchange rate. + title: QueryValidatorResponse is response type for the Query/Validator RPC + method + cosmos.staking.v1beta1.QueryValidatorUnbondingDelegationsResponse: + type: object + properties: + unbonding_responses: + type: array + items: + type: object + properties: + delegator_address: + type: string + description: delegator_address is the bech32-encoded address of the delegator. + validator_address: + type: string + description: validator_address is the bech32-encoded address of the validator. + entries: + type: array + items: + type: object + properties: + creation_height: + type: string + format: int64 + description: creation_height is the height which the unbonding took place. + completion_time: + type: string + format: date-time + description: completion_time is the unix time for unbonding completion. + initial_balance: + type: string + description: initial_balance defines the tokens initially scheduled to receive + at completion. + balance: + type: string + description: balance defines the tokens to receive at completion. + description: UnbondingDelegationEntry defines an unbonding object with relevant + metadata. + description: entries are the unbonding delegation entries. + description: >- + UnbondingDelegation stores all of a single delegator's unbonding + bonds + + for a single validator in an time-ordered list. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + QueryValidatorUnbondingDelegationsResponse is response type for the + Query/ValidatorUnbondingDelegations RPC method. + cosmos.staking.v1beta1.QueryValidatorsResponse: + type: object + properties: + validators: + type: array + items: + type: object + properties: + operator_address: + type: string + description: operator_address defines the address of the validator's operator; + bech encoded in JSON. + consensus_pubkey: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: consensus_pubkey is the consensus public key of the validator, as a + Protobuf Any. + jailed: + type: boolean + description: jailed defined whether the validator has been jailed from bonded + status or not. + status: + description: status is the validator status (bonded/unbonding/unbonded). + type: string + enum: + - BOND_STATUS_UNSPECIFIED + - BOND_STATUS_UNBONDED + - BOND_STATUS_UNBONDING + - BOND_STATUS_BONDED + default: BOND_STATUS_UNSPECIFIED + tokens: + type: string + description: tokens define the delegated tokens (incl. self-delegation). + delegator_shares: + type: string + description: delegator_shares defines total shares issued to a validator's + delegators. + description: + description: description defines the description terms for the validator. + type: object + properties: + moniker: + type: string + description: moniker defines a human-readable name for the validator. + identity: + type: string + description: identity defines an optional identity signature (ex. UPort or + Keybase). + website: + type: string + description: website defines an optional website link. + security_contact: + type: string + description: security_contact defines an optional email for security contact. + details: + type: string + description: details define other optional details. + unbonding_height: + type: string + format: int64 + description: unbonding_height defines, if unbonding, the height at which this + validator has begun unbonding. + unbonding_time: + type: string + format: date-time + description: unbonding_time defines, if unbonding, the min time for the + validator to complete unbonding. + commission: + description: commission defines the commission parameters. + type: object + properties: + commission_rates: + description: commission_rates defines the initial commission rates to be used + for creating a validator. + type: object + properties: + rate: + type: string + description: rate is the commission rate charged to delegators, as a fraction. + max_rate: + type: string + description: max_rate defines the maximum commission rate which validator can + ever charge, as a fraction. + max_change_rate: + type: string + description: max_change_rate defines the maximum daily increase of the validator + commission, as a fraction. + update_time: + type: string + format: date-time + description: update_time is the last time the commission rate was changed. + min_self_delegation: + type: string + description: min_self_delegation is the validator's self declared minimum self + delegation. + description: >- + Validator defines a validator, together with the total amount of + the + + Validator's bond shares and their exchange rate to coins. Slashing results in + + a decrease in the exchange rate, allowing correct calculation of future + + undelegations without iterating over delegators. When coins are delegated to + + this validator, the validator is credited with a delegation whose number of + + bond shares is based on the amount of coins delegated divided by the current + + exchange rate. Voting power can be calculated as total bonded shares + + multiplied by exchange rate. + description: validators contains all the queried validators. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + title: QueryValidatorsResponse is response type for the Query/Validators RPC + method + cosmos.staking.v1beta1.Redelegation: + type: object + properties: + delegator_address: + type: string + description: delegator_address is the bech32-encoded address of the delegator. + validator_src_address: + type: string + description: validator_src_address is the validator redelegation source operator + address. + validator_dst_address: + type: string + description: validator_dst_address is the validator redelegation destination + operator address. + entries: + type: array + items: + type: object + properties: + creation_height: + type: string + format: int64 + description: creation_height defines the height which the redelegation took + place. + completion_time: + type: string + format: date-time + description: completion_time defines the unix time for redelegation completion. + initial_balance: + type: string + description: initial_balance defines the initial balance when redelegation + started. + shares_dst: + type: string + description: shares_dst is the amount of destination-validator shares created by + redelegation. + description: RedelegationEntry defines a redelegation object with relevant + metadata. + description: entries are the redelegation entries. + description: >- + Redelegation contains the list of a particular delegator's redelegating + bonds + + from a particular source validator to a particular destination validator. + cosmos.staking.v1beta1.RedelegationEntry: + type: object + properties: + creation_height: + type: string + format: int64 + description: creation_height defines the height which the redelegation took + place. + completion_time: + type: string + format: date-time + description: completion_time defines the unix time for redelegation completion. + initial_balance: + type: string + description: initial_balance defines the initial balance when redelegation + started. + shares_dst: + type: string + description: shares_dst is the amount of destination-validator shares created by + redelegation. + description: RedelegationEntry defines a redelegation object with relevant metadata. + cosmos.staking.v1beta1.RedelegationEntryResponse: + type: object + properties: + redelegation_entry: + type: object + properties: + creation_height: + type: string + format: int64 + description: creation_height defines the height which the redelegation took + place. + completion_time: + type: string + format: date-time + description: completion_time defines the unix time for redelegation completion. + initial_balance: + type: string + description: initial_balance defines the initial balance when redelegation + started. + shares_dst: + type: string + description: shares_dst is the amount of destination-validator shares created by + redelegation. + description: RedelegationEntry defines a redelegation object with relevant + metadata. + balance: + type: string + description: >- + RedelegationEntryResponse is equivalent to a RedelegationEntry except + that it + + contains a balance in addition to shares which is more suitable for client + + responses. + cosmos.staking.v1beta1.RedelegationResponse: + type: object + properties: + redelegation: + type: object + properties: + delegator_address: + type: string + description: delegator_address is the bech32-encoded address of the delegator. + validator_src_address: + type: string + description: validator_src_address is the validator redelegation source operator + address. + validator_dst_address: + type: string + description: validator_dst_address is the validator redelegation destination + operator address. + entries: + type: array + items: + type: object + properties: + creation_height: + type: string + format: int64 + description: creation_height defines the height which the redelegation took + place. + completion_time: + type: string + format: date-time + description: completion_time defines the unix time for redelegation completion. + initial_balance: + type: string + description: initial_balance defines the initial balance when redelegation + started. + shares_dst: + type: string + description: shares_dst is the amount of destination-validator shares created by + redelegation. + description: RedelegationEntry defines a redelegation object with relevant + metadata. + description: entries are the redelegation entries. + description: >- + Redelegation contains the list of a particular delegator's + redelegating bonds + + from a particular source validator to a particular destination validator. + entries: + type: array + items: + type: object + properties: + redelegation_entry: + type: object + properties: + creation_height: + type: string + format: int64 + description: creation_height defines the height which the redelegation took + place. + completion_time: + type: string + format: date-time + description: completion_time defines the unix time for redelegation completion. + initial_balance: + type: string + description: initial_balance defines the initial balance when redelegation + started. + shares_dst: + type: string + description: shares_dst is the amount of destination-validator shares created by + redelegation. + description: RedelegationEntry defines a redelegation object with relevant + metadata. + balance: + type: string + description: >- + RedelegationEntryResponse is equivalent to a RedelegationEntry + except that it + + contains a balance in addition to shares which is more suitable for client + + responses. + description: >- + RedelegationResponse is equivalent to a Redelegation except that its + entries + + contain a balance in addition to shares which is more suitable for client + + responses. + cosmos.staking.v1beta1.UnbondingDelegation: + type: object + properties: + delegator_address: + type: string + description: delegator_address is the bech32-encoded address of the delegator. + validator_address: + type: string + description: validator_address is the bech32-encoded address of the validator. + entries: + type: array + items: + type: object + properties: + creation_height: + type: string + format: int64 + description: creation_height is the height which the unbonding took place. + completion_time: + type: string + format: date-time + description: completion_time is the unix time for unbonding completion. + initial_balance: + type: string + description: initial_balance defines the tokens initially scheduled to receive + at completion. + balance: + type: string + description: balance defines the tokens to receive at completion. + description: UnbondingDelegationEntry defines an unbonding object with relevant + metadata. + description: entries are the unbonding delegation entries. + description: |- + UnbondingDelegation stores all of a single delegator's unbonding bonds + for a single validator in an time-ordered list. + cosmos.staking.v1beta1.UnbondingDelegationEntry: + type: object + properties: + creation_height: + type: string + format: int64 + description: creation_height is the height which the unbonding took place. + completion_time: + type: string + format: date-time + description: completion_time is the unix time for unbonding completion. + initial_balance: + type: string + description: initial_balance defines the tokens initially scheduled to receive + at completion. + balance: + type: string + description: balance defines the tokens to receive at completion. + description: UnbondingDelegationEntry defines an unbonding object with relevant + metadata. + cosmos.staking.v1beta1.Validator: + type: object + properties: + operator_address: + type: string + description: operator_address defines the address of the validator's operator; + bech encoded in JSON. + consensus_pubkey: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: consensus_pubkey is the consensus public key of the validator, as a + Protobuf Any. + jailed: + type: boolean + description: jailed defined whether the validator has been jailed from bonded + status or not. + status: + description: status is the validator status (bonded/unbonding/unbonded). + type: string + enum: + - BOND_STATUS_UNSPECIFIED + - BOND_STATUS_UNBONDED + - BOND_STATUS_UNBONDING + - BOND_STATUS_BONDED + default: BOND_STATUS_UNSPECIFIED + tokens: + type: string + description: tokens define the delegated tokens (incl. self-delegation). + delegator_shares: + type: string + description: delegator_shares defines total shares issued to a validator's + delegators. + description: + description: description defines the description terms for the validator. + type: object + properties: + moniker: + type: string + description: moniker defines a human-readable name for the validator. + identity: + type: string + description: identity defines an optional identity signature (ex. UPort or + Keybase). + website: + type: string + description: website defines an optional website link. + security_contact: + type: string + description: security_contact defines an optional email for security contact. + details: + type: string + description: details define other optional details. + unbonding_height: + type: string + format: int64 + description: unbonding_height defines, if unbonding, the height at which this + validator has begun unbonding. + unbonding_time: + type: string + format: date-time + description: unbonding_time defines, if unbonding, the min time for the + validator to complete unbonding. + commission: + description: commission defines the commission parameters. + type: object + properties: + commission_rates: + description: commission_rates defines the initial commission rates to be used + for creating a validator. + type: object + properties: + rate: + type: string + description: rate is the commission rate charged to delegators, as a fraction. + max_rate: + type: string + description: max_rate defines the maximum commission rate which validator can + ever charge, as a fraction. + max_change_rate: + type: string + description: max_change_rate defines the maximum daily increase of the validator + commission, as a fraction. + update_time: + type: string + format: date-time + description: update_time is the last time the commission rate was changed. + min_self_delegation: + type: string + description: min_self_delegation is the validator's self declared minimum self + delegation. + description: >- + Validator defines a validator, together with the total amount of the + + Validator's bond shares and their exchange rate to coins. Slashing results in + + a decrease in the exchange rate, allowing correct calculation of future + + undelegations without iterating over delegators. When coins are delegated to + + this validator, the validator is credited with a delegation whose number of + + bond shares is based on the amount of coins delegated divided by the current + + exchange rate. Voting power can be calculated as total bonded shares + + multiplied by exchange rate. + tendermint.types.BlockID: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + tendermint.types.Header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for processing a block in the + blockchain, + + including all blockchain data structures and the rules of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + tendermint.types.PartSetHeader: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + tendermint.version.Consensus: + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for processing a block in the + blockchain, + + including all blockchain data structures and the rules of the application's + + state transition machine. + cosmos.base.tendermint.v1beta1.GetBlockByHeightResponse: + type: object + properties: + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + block: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for processing a + block in the blockchain, + + including all blockchain data structures and the rules of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + data: + type: object + properties: + txs: + type: array + items: + type: string + format: byte + description: >- + Txs that will be applied by state @ block.Height+1. + + NOTE: not all txs here are valid. We're just agreeing on the order first. + + This means that block.AppHash does not include these txs. + title: Data contains the set of transactions included in the block + evidence: + type: object + properties: + evidence: + type: array + items: + type: object + properties: + duplicate_vote_evidence: + type: object + properties: + vote_a: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: >- + SignedMsgType is a type of signed message in + the consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or commit + vote from validators for + + consensus. + vote_b: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: >- + SignedMsgType is a type of signed message in + the consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or commit + vote from validators for + + consensus. + total_voting_power: + type: string + format: int64 + validator_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: DuplicateVoteEvidence contains evidence of a validator signed two + conflicting votes. + light_client_attack_evidence: + type: object + properties: + conflicting_block: + type: object + properties: + signed_header: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules + for processing a block in the + blockchain, + + including all blockchain data structures and the rules of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: BlockIdFlag indicates which BlcokID the signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: CommitSig is a part of the Vote included in a Commit. + description: Commit contains the evidence that a block was committed by a set of + validators. + validator_set: + type: object + properties: + validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + proposer: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + common_height: + type: string + format: int64 + byzantine_validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: LightClientAttackEvidence contains evidence of a set of validators + attempting to mislead a light client. + last_commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: BlockIdFlag indicates which BlcokID the signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: CommitSig is a part of the Vote included in a Commit. + description: Commit contains the evidence that a block was committed by a set of + validators. + description: GetBlockByHeightResponse is the response type for the + Query/GetBlockByHeight RPC method. + cosmos.base.tendermint.v1beta1.GetLatestBlockResponse: + type: object + properties: + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + block: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for processing a + block in the blockchain, + + including all blockchain data structures and the rules of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + data: + type: object + properties: + txs: + type: array + items: + type: string + format: byte + description: >- + Txs that will be applied by state @ block.Height+1. + + NOTE: not all txs here are valid. We're just agreeing on the order first. + + This means that block.AppHash does not include these txs. + title: Data contains the set of transactions included in the block + evidence: + type: object + properties: + evidence: + type: array + items: + type: object + properties: + duplicate_vote_evidence: + type: object + properties: + vote_a: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: >- + SignedMsgType is a type of signed message in + the consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or commit + vote from validators for + + consensus. + vote_b: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: >- + SignedMsgType is a type of signed message in + the consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or commit + vote from validators for + + consensus. + total_voting_power: + type: string + format: int64 + validator_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: DuplicateVoteEvidence contains evidence of a validator signed two + conflicting votes. + light_client_attack_evidence: + type: object + properties: + conflicting_block: + type: object + properties: + signed_header: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules + for processing a block in the + blockchain, + + including all blockchain data structures and the rules of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: BlockIdFlag indicates which BlcokID the signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: CommitSig is a part of the Vote included in a Commit. + description: Commit contains the evidence that a block was committed by a set of + validators. + validator_set: + type: object + properties: + validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + proposer: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + common_height: + type: string + format: int64 + byzantine_validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: LightClientAttackEvidence contains evidence of a set of validators + attempting to mislead a light client. + last_commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: BlockIdFlag indicates which BlcokID the signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: CommitSig is a part of the Vote included in a Commit. + description: Commit contains the evidence that a block was committed by a set of + validators. + description: GetLatestBlockResponse is the response type for the + Query/GetLatestBlock RPC method. + cosmos.base.tendermint.v1beta1.GetLatestValidatorSetResponse: + type: object + properties: + block_height: + type: string + format: int64 + validators: + type: array + items: + type: object + properties: + address: + type: string + pub_key: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + description: Validator is the type for the validator-set. + pagination: + description: pagination defines an pagination for the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: GetLatestValidatorSetResponse is the response type for the + Query/GetValidatorSetByHeight RPC method. + cosmos.base.tendermint.v1beta1.GetNodeInfoResponse: + type: object + properties: + default_node_info: + type: object + properties: + protocol_version: + type: object + properties: + p2p: + type: string + format: uint64 + block: + type: string + format: uint64 + app: + type: string + format: uint64 + default_node_id: + type: string + listen_addr: + type: string + network: + type: string + version: + type: string + channels: + type: string + format: byte + moniker: + type: string + other: + type: object + properties: + tx_index: + type: string + rpc_address: + type: string + application_version: + type: object + properties: + name: + type: string + app_name: + type: string + version: + type: string + git_commit: + type: string + build_tags: + type: string + go_version: + type: string + build_deps: + type: array + items: + type: object + properties: + path: + type: string + title: module path + version: + type: string + title: module version + sum: + type: string + title: checksum + title: Module is the type for VersionInfo + cosmos_sdk_version: + type: string + title: "Since: cosmos-sdk 0.43" + description: VersionInfo is the type for the GetNodeInfoResponse message. + description: GetNodeInfoResponse is the request type for the Query/GetNodeInfo + RPC method. + cosmos.base.tendermint.v1beta1.GetSyncingResponse: + type: object + properties: + syncing: + type: boolean + description: GetSyncingResponse is the response type for the Query/GetSyncing + RPC method. + cosmos.base.tendermint.v1beta1.GetValidatorSetByHeightResponse: + type: object + properties: + block_height: + type: string + format: int64 + validators: + type: array + items: + type: object + properties: + address: + type: string + pub_key: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + description: Validator is the type for the validator-set. + pagination: + description: pagination defines an pagination for the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: GetValidatorSetByHeightResponse is the response type for the + Query/GetValidatorSetByHeight RPC method. + cosmos.base.tendermint.v1beta1.Module: + type: object + properties: + path: + type: string + title: module path + version: + type: string + title: module version + sum: + type: string + title: checksum + title: Module is the type for VersionInfo + cosmos.base.tendermint.v1beta1.Validator: + type: object + properties: + address: + type: string + pub_key: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + description: Validator is the type for the validator-set. + cosmos.base.tendermint.v1beta1.VersionInfo: + type: object + properties: + name: + type: string + app_name: + type: string + version: + type: string + git_commit: + type: string + build_tags: + type: string + go_version: + type: string + build_deps: + type: array + items: + type: object + properties: + path: + type: string + title: module path + version: + type: string + title: module version + sum: + type: string + title: checksum + title: Module is the type for VersionInfo + cosmos_sdk_version: + type: string + title: "Since: cosmos-sdk 0.43" + description: VersionInfo is the type for the GetNodeInfoResponse message. + tendermint.crypto.PublicKey: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + tendermint.p2p.DefaultNodeInfo: + type: object + properties: + protocol_version: + type: object + properties: + p2p: + type: string + format: uint64 + block: + type: string + format: uint64 + app: + type: string + format: uint64 + default_node_id: + type: string + listen_addr: + type: string + network: + type: string + version: + type: string + channels: + type: string + format: byte + moniker: + type: string + other: + type: object + properties: + tx_index: + type: string + rpc_address: + type: string + tendermint.p2p.DefaultNodeInfoOther: + type: object + properties: + tx_index: + type: string + rpc_address: + type: string + tendermint.p2p.ProtocolVersion: + type: object + properties: + p2p: + type: string + format: uint64 + block: + type: string + format: uint64 + app: + type: string + format: uint64 + tendermint.types.Block: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for processing a block in + the blockchain, + + including all blockchain data structures and the rules of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + data: + type: object + properties: + txs: + type: array + items: + type: string + format: byte + description: >- + Txs that will be applied by state @ block.Height+1. + + NOTE: not all txs here are valid. We're just agreeing on the order first. + + This means that block.AppHash does not include these txs. + title: Data contains the set of transactions included in the block + evidence: + type: object + properties: + evidence: + type: array + items: + type: object + properties: + duplicate_vote_evidence: + type: object + properties: + vote_a: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: >- + SignedMsgType is a type of signed message in the + consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or commit vote + from validators for + + consensus. + vote_b: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: >- + SignedMsgType is a type of signed message in the + consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or commit vote + from validators for + + consensus. + total_voting_power: + type: string + format: int64 + validator_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: DuplicateVoteEvidence contains evidence of a validator signed two + conflicting votes. + light_client_attack_evidence: + type: object + properties: + conflicting_block: + type: object + properties: + signed_header: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for + processing a block in the blockchain, + + including all blockchain data structures and the rules of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: BlockIdFlag indicates which BlcokID the signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: CommitSig is a part of the Vote included in a Commit. + description: Commit contains the evidence that a block was committed by a set of + validators. + validator_set: + type: object + properties: + validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + proposer: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + common_height: + type: string + format: int64 + byzantine_validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: LightClientAttackEvidence contains evidence of a set of validators + attempting to mislead a light client. + last_commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: BlockIdFlag indicates which BlcokID the signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: CommitSig is a part of the Vote included in a Commit. + description: Commit contains the evidence that a block was committed by a set of + validators. + tendermint.types.BlockIDFlag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: BlockIdFlag indicates which BlcokID the signature is for + tendermint.types.Commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: BlockIdFlag indicates which BlcokID the signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: CommitSig is a part of the Vote included in a Commit. + description: Commit contains the evidence that a block was committed by a set of + validators. + tendermint.types.CommitSig: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: BlockIdFlag indicates which BlcokID the signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: CommitSig is a part of the Vote included in a Commit. + tendermint.types.Data: + type: object + properties: + txs: + type: array + items: + type: string + format: byte + description: >- + Txs that will be applied by state @ block.Height+1. + + NOTE: not all txs here are valid. We're just agreeing on the order first. + + This means that block.AppHash does not include these txs. + title: Data contains the set of transactions included in the block + tendermint.types.DuplicateVoteEvidence: + type: object + properties: + vote_a: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: |- + SignedMsgType is a type of signed message in the consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or commit vote from validators + for + + consensus. + vote_b: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: |- + SignedMsgType is a type of signed message in the consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or commit vote from validators + for + + consensus. + total_voting_power: + type: string + format: int64 + validator_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: DuplicateVoteEvidence contains evidence of a validator signed two + conflicting votes. + tendermint.types.Evidence: + type: object + properties: + duplicate_vote_evidence: + type: object + properties: + vote_a: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: |- + SignedMsgType is a type of signed message in the consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or commit vote from + validators for + + consensus. + vote_b: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: |- + SignedMsgType is a type of signed message in the consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or commit vote from + validators for + + consensus. + total_voting_power: + type: string + format: int64 + validator_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: DuplicateVoteEvidence contains evidence of a validator signed two + conflicting votes. + light_client_attack_evidence: + type: object + properties: + conflicting_block: + type: object + properties: + signed_header: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for + processing a block in the blockchain, + + including all blockchain data structures and the rules of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: BlockIdFlag indicates which BlcokID the signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: CommitSig is a part of the Vote included in a Commit. + description: Commit contains the evidence that a block was committed by a set of + validators. + validator_set: + type: object + properties: + validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + proposer: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + common_height: + type: string + format: int64 + byzantine_validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: LightClientAttackEvidence contains evidence of a set of validators + attempting to mislead a light client. + tendermint.types.EvidenceList: + type: object + properties: + evidence: + type: array + items: + type: object + properties: + duplicate_vote_evidence: + type: object + properties: + vote_a: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: >- + SignedMsgType is a type of signed message in the + consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or commit vote from + validators for + + consensus. + vote_b: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: >- + SignedMsgType is a type of signed message in the + consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or commit vote from + validators for + + consensus. + total_voting_power: + type: string + format: int64 + validator_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: DuplicateVoteEvidence contains evidence of a validator signed two + conflicting votes. + light_client_attack_evidence: + type: object + properties: + conflicting_block: + type: object + properties: + signed_header: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for + processing a block in the blockchain, + + including all blockchain data structures and the rules of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: BlockIdFlag indicates which BlcokID the signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: CommitSig is a part of the Vote included in a Commit. + description: Commit contains the evidence that a block was committed by a set of + validators. + validator_set: + type: object + properties: + validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + proposer: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + common_height: + type: string + format: int64 + byzantine_validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: LightClientAttackEvidence contains evidence of a set of validators + attempting to mislead a light client. + tendermint.types.LightBlock: + type: object + properties: + signed_header: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for processing a + block in the blockchain, + + including all blockchain data structures and the rules of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: BlockIdFlag indicates which BlcokID the signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: CommitSig is a part of the Vote included in a Commit. + description: Commit contains the evidence that a block was committed by a set of + validators. + validator_set: + type: object + properties: + validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + proposer: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + tendermint.types.LightClientAttackEvidence: + type: object + properties: + conflicting_block: + type: object + properties: + signed_header: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for processing a + block in the blockchain, + + including all blockchain data structures and the rules of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: BlockIdFlag indicates which BlcokID the signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: CommitSig is a part of the Vote included in a Commit. + description: Commit contains the evidence that a block was committed by a set of + validators. + validator_set: + type: object + properties: + validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + proposer: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + common_height: + type: string + format: int64 + byzantine_validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: LightClientAttackEvidence contains evidence of a set of validators + attempting to mislead a light client. + tendermint.types.SignedHeader: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for processing a block in + the blockchain, + + including all blockchain data structures and the rules of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: BlockIdFlag indicates which BlcokID the signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: CommitSig is a part of the Vote included in a Commit. + description: Commit contains the evidence that a block was committed by a set of + validators. + tendermint.types.SignedMsgType: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: |- + SignedMsgType is a type of signed message in the consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + tendermint.types.Validator: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + tendermint.types.ValidatorSet: + type: object + properties: + validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + proposer: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + tendermint.types.Vote: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: |- + SignedMsgType is a type of signed message in the consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: |- + Vote represents a prevote, precommit, or commit vote from validators for + consensus. + router.v1.Params: + type: object + properties: + fee_percentage: + type: string + description: Params defines the set of IBC router parameters. + router.v1.QueryParamsResponse: + type: object + properties: + params: + description: params defines the parameters of the module. + type: object + properties: + fee_percentage: + type: string + description: QueryParamsResponse is the response type for the Query/Params RPC method. + type: object + properties: + params: + description: params defines the parameters of the module. + type: object + properties: + denom_creation_fee: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + denom_creation_gas_consume: + type: string + format: uint64 + title: >- + if denom_creation_fee is an empty array, then this field is used + to add more gas consumption + + to the base cost. + + https://github.com/CosmWasm/token-factory/issues/11 + description: QueryParamsResponse is the response type for the Query/Params RPC method. + cosmos.base.v1beta1.DecCoin: + type: object + properties: + denom: + type: string + amount: + type: string + description: |- + DecCoin defines a token with a denomination and a decimal amount. + + NOTE: The amount field is an Dec which implements the custom method + signatures required by gogoproto. + cosmos.distribution.v1beta1.DelegationDelegatorReward: + type: object + properties: + validator_address: + type: string + reward: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + DecCoin defines a token with a denomination and a decimal amount. + + + NOTE: The amount field is an Dec which implements the custom method + + signatures required by gogoproto. + description: |- + DelegationDelegatorReward represents the properties + of a delegator's delegation reward. + cosmos.distribution.v1beta1.Params: + type: object + properties: + community_tax: + type: string + base_proposer_reward: + type: string + bonus_proposer_reward: + type: string + withdraw_addr_enabled: + type: boolean + description: Params defines the set of params for the distribution module. + cosmos.distribution.v1beta1.QueryCommunityPoolResponse: + type: object + properties: + pool: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + DecCoin defines a token with a denomination and a decimal amount. + + + NOTE: The amount field is an Dec which implements the custom method + + signatures required by gogoproto. + description: pool defines community pool's coins. + description: >- + QueryCommunityPoolResponse is the response type for the + Query/CommunityPool + + RPC method. + cosmos.distribution.v1beta1.QueryDelegationRewardsResponse: + type: object + properties: + rewards: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + DecCoin defines a token with a denomination and a decimal amount. + + + NOTE: The amount field is an Dec which implements the custom method + + signatures required by gogoproto. + description: rewards defines the rewards accrued by a delegation. + description: |- + QueryDelegationRewardsResponse is the response type for the + Query/DelegationRewards RPC method. + cosmos.distribution.v1beta1.QueryDelegationTotalRewardsResponse: + type: object + properties: + rewards: + type: array + items: + type: object + properties: + validator_address: + type: string + reward: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + DecCoin defines a token with a denomination and a decimal + amount. + + + NOTE: The amount field is an Dec which implements the custom method + + signatures required by gogoproto. + description: |- + DelegationDelegatorReward represents the properties + of a delegator's delegation reward. + description: rewards defines all the rewards accrued by a delegator. + total: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + DecCoin defines a token with a denomination and a decimal amount. + + + NOTE: The amount field is an Dec which implements the custom method + + signatures required by gogoproto. + description: total defines the sum of all the rewards. + description: |- + QueryDelegationTotalRewardsResponse is the response type for the + Query/DelegationTotalRewards RPC method. + cosmos.distribution.v1beta1.QueryDelegatorValidatorsResponse: + type: object + properties: + validators: + type: array + items: + type: string + description: validators defines the validators a delegator is delegating for. + description: |- + QueryDelegatorValidatorsResponse is the response type for the + Query/DelegatorValidators RPC method. + cosmos.distribution.v1beta1.QueryDelegatorWithdrawAddressResponse: + type: object + properties: + withdraw_address: + type: string + description: withdraw_address defines the delegator address to query for. + description: |- + QueryDelegatorWithdrawAddressResponse is the response type for the + Query/DelegatorWithdrawAddress RPC method. + cosmos.distribution.v1beta1.QueryParamsResponse: + type: object + properties: + params: + description: params defines the parameters of the module. + type: object + properties: + community_tax: + type: string + base_proposer_reward: + type: string + bonus_proposer_reward: + type: string + withdraw_addr_enabled: + type: boolean + description: QueryParamsResponse is the response type for the Query/Params RPC method. + cosmos.distribution.v1beta1.QueryValidatorCommissionResponse: + type: object + properties: + commission: + description: commission defines the commision the validator received. + type: object + properties: + commission: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + DecCoin defines a token with a denomination and a decimal + amount. + + + NOTE: The amount field is an Dec which implements the custom method + + signatures required by gogoproto. + title: |- + QueryValidatorCommissionResponse is the response type for the + Query/ValidatorCommission RPC method + cosmos.distribution.v1beta1.QueryValidatorOutstandingRewardsResponse: + type: object + properties: + rewards: + type: object + properties: + rewards: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + DecCoin defines a token with a denomination and a decimal + amount. + + + NOTE: The amount field is an Dec which implements the custom method + + signatures required by gogoproto. + description: >- + ValidatorOutstandingRewards represents outstanding (un-withdrawn) + rewards + + for a validator inexpensive to track, allows simple sanity checks. + description: |- + QueryValidatorOutstandingRewardsResponse is the response type for the + Query/ValidatorOutstandingRewards RPC method. + cosmos.distribution.v1beta1.QueryValidatorSlashesResponse: + type: object + properties: + slashes: + type: array + items: + type: object + properties: + validator_period: + type: string + format: uint64 + fraction: + type: string + description: |- + ValidatorSlashEvent represents a validator slash event. + Height is implicit within the store key. + This is needed to calculate appropriate amount of staking tokens + for delegations which are withdrawn after a slash has occurred. + description: slashes defines the slashes the validator received. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + QueryValidatorSlashesResponse is the response type for the + Query/ValidatorSlashes RPC method. + cosmos.distribution.v1beta1.ValidatorAccumulatedCommission: + type: object + properties: + commission: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + DecCoin defines a token with a denomination and a decimal amount. + + + NOTE: The amount field is an Dec which implements the custom method + + signatures required by gogoproto. + description: |- + ValidatorAccumulatedCommission represents accumulated commission + for a validator kept as a running counter, can be withdrawn at any time. + cosmos.distribution.v1beta1.ValidatorOutstandingRewards: + type: object + properties: + rewards: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + DecCoin defines a token with a denomination and a decimal amount. + + + NOTE: The amount field is an Dec which implements the custom method + + signatures required by gogoproto. + description: >- + ValidatorOutstandingRewards represents outstanding (un-withdrawn) + rewards + + for a validator inexpensive to track, allows simple sanity checks. + cosmos.distribution.v1beta1.ValidatorSlashEvent: + type: object + properties: + validator_period: + type: string + format: uint64 + fraction: + type: string + description: |- + ValidatorSlashEvent represents a validator slash event. + Height is implicit within the store key. + This is needed to calculate appropriate amount of staking tokens + for delegations which are withdrawn after a slash has occurred. + cosmos.base.abci.v1beta1.ABCIMessageLog: + type: object + properties: + msg_index: + type: integer + format: int64 + log: + type: string + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + value: + type: string + description: >- + Attribute defines an attribute wrapper where the key and + value are + + strings instead of raw bytes. + description: >- + StringEvent defines en Event object wrapper where all the + attributes + + contain key/value pairs that are strings instead of raw bytes. + description: >- + Events contains a slice of Event objects that were emitted during + some + + execution. + description: ABCIMessageLog defines a structure containing an indexed tx ABCI + message log. + cosmos.base.abci.v1beta1.Attribute: + type: object + properties: + key: + type: string + value: + type: string + description: |- + Attribute defines an attribute wrapper where the key and value are + strings instead of raw bytes. + cosmos.base.abci.v1beta1.GasInfo: + type: object + properties: + gas_wanted: + type: string + format: uint64 + description: GasWanted is the maximum units of work we allow this tx to perform. + gas_used: + type: string + format: uint64 + description: GasUsed is the amount of gas actually consumed. + description: GasInfo defines tx execution gas context. + cosmos.base.abci.v1beta1.Result: + type: object + properties: + data: + type: string + format: byte + description: >- + Data is any data returned from message or handler execution. It MUST + be + + length prefixed in order to separate data from multiple message executions. + log: + type: string + description: Log contains the log information from message or handler execution. + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + format: byte + value: + type: string + format: byte + index: + type: boolean + description: EventAttribute is a single key-value pair, associated with an + event. + description: >- + Event allows application developers to attach additional + information to + + ResponseBeginBlock, ResponseEndBlock, ResponseCheckTx and ResponseDeliverTx. + + Later, transactions may be queried using these events. + description: >- + Events contains a slice of Event objects that were emitted during + message + + or handler execution. + description: Result is the union of ResponseFormat and ResponseCheckTx. + cosmos.base.abci.v1beta1.StringEvent: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + value: + type: string + description: |- + Attribute defines an attribute wrapper where the key and value are + strings instead of raw bytes. + description: |- + StringEvent defines en Event object wrapper where all the attributes + contain key/value pairs that are strings instead of raw bytes. + cosmos.base.abci.v1beta1.TxResponse: + type: object + properties: + height: + type: string + format: int64 + title: The block height + txhash: + type: string + description: The transaction hash. + codespace: + type: string + title: Namespace for the Code + code: + type: integer + format: int64 + description: Response code. + data: + type: string + description: Result bytes, if any. + raw_log: + type: string + description: |- + The output of the application's logger (raw string). May be + non-deterministic. + logs: + type: array + items: + type: object + properties: + msg_index: + type: integer + format: int64 + log: + type: string + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + value: + type: string + description: >- + Attribute defines an attribute wrapper where the key + and value are + + strings instead of raw bytes. + description: >- + StringEvent defines en Event object wrapper where all the + attributes + + contain key/value pairs that are strings instead of raw bytes. + description: >- + Events contains a slice of Event objects that were emitted + during some + + execution. + description: ABCIMessageLog defines a structure containing an indexed tx ABCI + message log. + description: The output of the application's logger (typed). May be + non-deterministic. + info: + type: string + description: Additional information. May be non-deterministic. + gas_wanted: + type: string + format: int64 + description: Amount of gas requested for transaction. + gas_used: + type: string + format: int64 + description: Amount of gas consumed by transaction. + tx: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: The request transaction bytes. + timestamp: + type: string + description: >- + Time of the previous block. For heights > 1, it's the weighted + median of + + the timestamps of the valid votes in the block.LastCommit. For height == 1, + + it's genesis time. + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + format: byte + value: + type: string + format: byte + index: + type: boolean + description: EventAttribute is a single key-value pair, associated with an + event. + description: >- + Event allows application developers to attach additional + information to + + ResponseBeginBlock, ResponseEndBlock, ResponseCheckTx and ResponseDeliverTx. + + Later, transactions may be queried using these events. + description: >- + Events defines all the events emitted by processing a transaction. + Note, + + these events include those emitted by processing all the messages and those + + emitted from the ante handler. Whereas Logs contains the events, with + + additional metadata, emitted only by processing the messages. + + + Since: cosmos-sdk 0.42.11, 0.44.5, 0.45 + description: >- + TxResponse defines a structure containing relevant tx data and metadata. + The + + tags are stringified and the log is JSON decoded. + cosmos.crypto.multisig.v1beta1.CompactBitArray: + type: object + properties: + extra_bits_stored: + type: integer + format: int64 + elems: + type: string + format: byte + description: >- + CompactBitArray is an implementation of a space efficient bit array. + + This is used to ensure that the encoded data takes up a minimal amount of + + space after proto encoding. + + This is not thread safe, and is not intended for concurrent usage. + cosmos.tx.signing.v1beta1.SignMode: + type: string + enum: + - SIGN_MODE_UNSPECIFIED + - SIGN_MODE_DIRECT + - SIGN_MODE_TEXTUAL + - SIGN_MODE_LEGACY_AMINO_JSON + - SIGN_MODE_EIP_191 + default: SIGN_MODE_UNSPECIFIED + description: >- + SignMode represents a signing mode with its own security guarantees. + + - SIGN_MODE_UNSPECIFIED: SIGN_MODE_UNSPECIFIED specifies an unknown signing mode and will be + rejected + - SIGN_MODE_DIRECT: SIGN_MODE_DIRECT specifies a signing mode which uses SignDoc and is + verified with raw bytes from Tx + - SIGN_MODE_TEXTUAL: SIGN_MODE_TEXTUAL is a future signing mode that will verify some + human-readable textual representation on top of the binary representation + + from SIGN_MODE_DIRECT + - SIGN_MODE_LEGACY_AMINO_JSON: SIGN_MODE_LEGACY_AMINO_JSON is a backwards compatibility mode which uses + Amino JSON and will be removed in the future + - SIGN_MODE_EIP_191: SIGN_MODE_EIP_191 specifies the sign mode for EIP 191 signing on the Cosmos + SDK. Ref: https://eips.ethereum.org/EIPS/eip-191 + + + Currently, SIGN_MODE_EIP_191 is registered as a SignMode enum variant, + + but is not implemented on the SDK by default. To enable EIP-191, you need + + to pass a custom `TxConfig` that has an implementation of + + `SignModeHandler` for EIP-191. The SDK may decide to fully support + + EIP-191 in the future. + + + Since: cosmos-sdk 0.45.2 + cosmos.tx.v1beta1.AuthInfo: + type: object + properties: + signer_infos: + type: array + items: + type: object + properties: + public_key: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + public_key is the public key of the signer. It is optional for + accounts + + that already exist in state. If unset, the verifier can use the required \ + + signer address for this position and lookup the public key. + mode_info: + title: >- + mode_info describes the signing mode of the signer and is a + nested + + structure to support nested multisig pubkey's + type: object + properties: + single: + title: single represents a single signer + type: object + properties: + mode: + title: mode is the signing mode of the single signer + type: string + enum: + - SIGN_MODE_UNSPECIFIED + - SIGN_MODE_DIRECT + - SIGN_MODE_TEXTUAL + - SIGN_MODE_LEGACY_AMINO_JSON + - SIGN_MODE_EIP_191 + default: SIGN_MODE_UNSPECIFIED + description: >- + SignMode represents a signing mode with its own + security guarantees. + + - SIGN_MODE_UNSPECIFIED: SIGN_MODE_UNSPECIFIED specifies an unknown signing mode and will be + rejected + - SIGN_MODE_DIRECT: SIGN_MODE_DIRECT specifies a signing mode which uses SignDoc and is + verified with raw bytes from Tx + - SIGN_MODE_TEXTUAL: SIGN_MODE_TEXTUAL is a future signing mode that will verify some + human-readable textual representation on top of the binary representation + + from SIGN_MODE_DIRECT + - SIGN_MODE_LEGACY_AMINO_JSON: SIGN_MODE_LEGACY_AMINO_JSON is a backwards compatibility mode which uses + Amino JSON and will be removed in the future + - SIGN_MODE_EIP_191: SIGN_MODE_EIP_191 specifies the sign mode for EIP 191 signing on the Cosmos + SDK. Ref: https://eips.ethereum.org/EIPS/eip-191 + + + Currently, SIGN_MODE_EIP_191 is registered as a SignMode enum variant, + + but is not implemented on the SDK by default. To enable EIP-191, you need + + to pass a custom `TxConfig` that has an implementation of + + `SignModeHandler` for EIP-191. The SDK may decide to fully support + + EIP-191 in the future. + + + Since: cosmos-sdk 0.45.2 + multi: + title: multi represents a nested multisig signer + type: object + properties: + bitarray: + title: bitarray specifies which keys within the multisig are signing + type: object + properties: + extra_bits_stored: + type: integer + format: int64 + elems: + type: string + format: byte + description: >- + CompactBitArray is an implementation of a space + efficient bit array. + + This is used to ensure that the encoded data takes up a minimal amount of + + space after proto encoding. + + This is not thread safe, and is not intended for concurrent usage. + mode_infos: + type: array + items: {} + title: >- + mode_infos is the corresponding modes of the signers + of the multisig + + which could include nested multisig public keys + description: ModeInfo describes the signing mode of a single or nested multisig + signer. + sequence: + type: string + format: uint64 + description: >- + sequence is the sequence of the account, which describes the + + number of committed transactions signed by a given address. It is used to + + prevent replay attacks. + description: >- + SignerInfo describes the public key and signing mode of a single + top-level + + signer. + description: >- + signer_infos defines the signing modes for the required signers. The + number + + and order of elements must match the required signers from TxBody's + + messages. The first element is the primary signer and the one which pays + + the fee. + fee: + description: >- + Fee is the fee and gas limit for the transaction. The first signer + is the + + primary signer and the one which pays the fee. The fee can be calculated + + based on the cost of evaluating the body and doing signature verification + + of the signers. This can be estimated via simulation. + type: object + properties: + amount: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + title: amount is the amount of coins to be paid as a fee + gas_limit: + type: string + format: uint64 + title: >- + gas_limit is the maximum gas that can be used in transaction + processing + + before an out of gas error occurs + payer: + type: string + description: >- + if unset, the first signer is responsible for paying the fees. + If set, the specified account must pay the fees. + + the payer must be a tx signer (and thus have signed this field in AuthInfo). + + setting this field does *not* change the ordering of required signers for the transaction. + granter: + type: string + title: >- + if set, the fee payer (either the first signer or the value of + the payer field) requests that a fee grant be used + + to pay fees instead of the fee payer's own balance. If an appropriate fee grant does not exist or the chain does + + not support fee grants, this will fail + description: |- + AuthInfo describes the fee and signer modes that are used to sign a + transaction. + cosmos.tx.v1beta1.BroadcastMode: + type: string + enum: + - BROADCAST_MODE_UNSPECIFIED + - BROADCAST_MODE_BLOCK + - BROADCAST_MODE_SYNC + - BROADCAST_MODE_ASYNC + default: BROADCAST_MODE_UNSPECIFIED + description: >- + BroadcastMode specifies the broadcast mode for the TxService.Broadcast + RPC method. + + - BROADCAST_MODE_UNSPECIFIED: zero-value for mode ordering + - BROADCAST_MODE_BLOCK: BROADCAST_MODE_BLOCK defines a tx broadcasting mode where the client waits for + the tx to be committed in a block. + - BROADCAST_MODE_SYNC: BROADCAST_MODE_SYNC defines a tx broadcasting mode where the client waits for + a CheckTx execution response only. + - BROADCAST_MODE_ASYNC: BROADCAST_MODE_ASYNC defines a tx broadcasting mode where the client returns + immediately. + cosmos.tx.v1beta1.BroadcastTxRequest: + type: object + properties: + tx_bytes: + type: string + format: byte + description: tx_bytes is the raw transaction. + mode: + type: string + enum: + - BROADCAST_MODE_UNSPECIFIED + - BROADCAST_MODE_BLOCK + - BROADCAST_MODE_SYNC + - BROADCAST_MODE_ASYNC + default: BROADCAST_MODE_UNSPECIFIED + description: >- + BroadcastMode specifies the broadcast mode for the + TxService.Broadcast RPC method. + + - BROADCAST_MODE_UNSPECIFIED: zero-value for mode ordering + - BROADCAST_MODE_BLOCK: BROADCAST_MODE_BLOCK defines a tx broadcasting mode where the client waits for + the tx to be committed in a block. + - BROADCAST_MODE_SYNC: BROADCAST_MODE_SYNC defines a tx broadcasting mode where the client waits for + a CheckTx execution response only. + - BROADCAST_MODE_ASYNC: BROADCAST_MODE_ASYNC defines a tx broadcasting mode where the client returns + immediately. + description: >- + BroadcastTxRequest is the request type for the + Service.BroadcastTxRequest + + RPC method. + cosmos.tx.v1beta1.BroadcastTxResponse: + type: object + properties: + tx_response: + type: object + properties: + height: + type: string + format: int64 + title: The block height + txhash: + type: string + description: The transaction hash. + codespace: + type: string + title: Namespace for the Code + code: + type: integer + format: int64 + description: Response code. + data: + type: string + description: Result bytes, if any. + raw_log: + type: string + description: |- + The output of the application's logger (raw string). May be + non-deterministic. + logs: + type: array + items: + type: object + properties: + msg_index: + type: integer + format: int64 + log: + type: string + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + value: + type: string + description: >- + Attribute defines an attribute wrapper where the + key and value are + + strings instead of raw bytes. + description: >- + StringEvent defines en Event object wrapper where all + the attributes + + contain key/value pairs that are strings instead of raw bytes. + description: >- + Events contains a slice of Event objects that were emitted + during some + + execution. + description: ABCIMessageLog defines a structure containing an indexed tx ABCI + message log. + description: The output of the application's logger (typed). May be + non-deterministic. + info: + type: string + description: Additional information. May be non-deterministic. + gas_wanted: + type: string + format: int64 + description: Amount of gas requested for transaction. + gas_used: + type: string + format: int64 + description: Amount of gas consumed by transaction. + tx: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: The request transaction bytes. + timestamp: + type: string + description: >- + Time of the previous block. For heights > 1, it's the weighted + median of + + the timestamps of the valid votes in the block.LastCommit. For height == 1, + + it's genesis time. + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + format: byte + value: + type: string + format: byte + index: + type: boolean + description: EventAttribute is a single key-value pair, associated with an + event. + description: >- + Event allows application developers to attach additional + information to + + ResponseBeginBlock, ResponseEndBlock, ResponseCheckTx and ResponseDeliverTx. + + Later, transactions may be queried using these events. + description: >- + Events defines all the events emitted by processing a + transaction. Note, + + these events include those emitted by processing all the messages and those + + emitted from the ante handler. Whereas Logs contains the events, with + + additional metadata, emitted only by processing the messages. + + + Since: cosmos-sdk 0.42.11, 0.44.5, 0.45 + description: >- + TxResponse defines a structure containing relevant tx data and + metadata. The + + tags are stringified and the log is JSON decoded. + description: |- + BroadcastTxResponse is the response type for the + Service.BroadcastTx method. + cosmos.tx.v1beta1.Fee: + type: object + properties: + amount: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + title: amount is the amount of coins to be paid as a fee + gas_limit: + type: string + format: uint64 + title: >- + gas_limit is the maximum gas that can be used in transaction + processing + + before an out of gas error occurs + payer: + type: string + description: >- + if unset, the first signer is responsible for paying the fees. If + set, the specified account must pay the fees. + + the payer must be a tx signer (and thus have signed this field in AuthInfo). + + setting this field does *not* change the ordering of required signers for the transaction. + granter: + type: string + title: >- + if set, the fee payer (either the first signer or the value of the + payer field) requests that a fee grant be used + + to pay fees instead of the fee payer's own balance. If an appropriate fee grant does not exist or the chain does + + not support fee grants, this will fail + description: >- + Fee includes the amount of coins paid in fees and the maximum + + gas to be used by the transaction. The ratio yields an effective "gasprice", + + which must be above some miminum to be accepted into the mempool. + cosmos.tx.v1beta1.GetBlockWithTxsResponse: + type: object + properties: + txs: + type: array + items: + type: object + properties: + body: + title: body is the processable content of the transaction + type: object + properties: + messages: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + messages is a list of messages to be executed. The + required signers of + + those messages define the number and order of elements in AuthInfo's + + signer_infos and Tx's signatures. Each required signer address is added to + + the list only the first time it occurs. + + By convention, the first required signer (usually from the first message) + + is referred to as the primary signer and pays the fee for the whole + + transaction. + memo: + type: string + description: >- + memo is any arbitrary note/comment to be added to the + transaction. + + WARNING: in clients, any publicly exposed text should not be called memo, + + but should be called `note` instead (see https://github.com/cosmos/cosmos-sdk/issues/9122). + timeout_height: + type: string + format: uint64 + title: >- + timeout is the block height after which this transaction + will not + + be processed by the chain + extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be added + by chains + + when the default options are not sufficient. If any of these are present + + and can't be handled, the transaction will be rejected + non_critical_extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be added + by chains + + when the default options are not sufficient. If any of these are present + + and can't be handled, they will be ignored + description: TxBody is the body of a transaction that all signers sign over. + auth_info: + title: >- + auth_info is the authorization related content of the + transaction, + + specifically signers, signer modes and fee + type: object + properties: + signer_infos: + type: array + items: + type: object + properties: + public_key: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + public_key is the public key of the signer. It is + optional for accounts + + that already exist in state. If unset, the verifier can use the required \ + + signer address for this position and lookup the public key. + mode_info: + title: >- + mode_info describes the signing mode of the signer + and is a nested + + structure to support nested multisig pubkey's + type: object + properties: + single: + title: single represents a single signer + type: object + properties: + mode: + title: mode is the signing mode of the single signer + type: string + enum: + - SIGN_MODE_UNSPECIFIED + - SIGN_MODE_DIRECT + - SIGN_MODE_TEXTUAL + - SIGN_MODE_LEGACY_AMINO_JSON + - SIGN_MODE_EIP_191 + default: SIGN_MODE_UNSPECIFIED + description: >- + SignMode represents a signing mode with its + own security guarantees. + + - SIGN_MODE_UNSPECIFIED: SIGN_MODE_UNSPECIFIED specifies an unknown signing mode and will be + rejected + - SIGN_MODE_DIRECT: SIGN_MODE_DIRECT specifies a signing mode which uses SignDoc and is + verified with raw bytes from Tx + - SIGN_MODE_TEXTUAL: SIGN_MODE_TEXTUAL is a future signing mode that will verify some + human-readable textual representation on top of the binary representation + + from SIGN_MODE_DIRECT + - SIGN_MODE_LEGACY_AMINO_JSON: SIGN_MODE_LEGACY_AMINO_JSON is a backwards compatibility mode which uses + Amino JSON and will be removed in the future + - SIGN_MODE_EIP_191: SIGN_MODE_EIP_191 specifies the sign mode for EIP 191 signing on the Cosmos + SDK. Ref: https://eips.ethereum.org/EIPS/eip-191 + + + Currently, SIGN_MODE_EIP_191 is registered as a SignMode enum variant, + + but is not implemented on the SDK by default. To enable EIP-191, you need + + to pass a custom `TxConfig` that has an implementation of + + `SignModeHandler` for EIP-191. The SDK may decide to fully support + + EIP-191 in the future. + + + Since: cosmos-sdk 0.45.2 + multi: + title: multi represents a nested multisig signer + type: object + properties: + bitarray: + title: bitarray specifies which keys within the multisig are signing + type: object + properties: + extra_bits_stored: + type: integer + format: int64 + elems: + type: string + format: byte + description: >- + CompactBitArray is an implementation of a + space efficient bit array. + + This is used to ensure that the encoded data takes up a minimal amount of + + space after proto encoding. + + This is not thread safe, and is not intended for concurrent usage. + mode_infos: + type: array + items: {} + title: >- + mode_infos is the corresponding modes of the + signers of the multisig + + which could include nested multisig public keys + description: ModeInfo describes the signing mode of a single or nested multisig + signer. + sequence: + type: string + format: uint64 + description: >- + sequence is the sequence of the account, which + describes the + + number of committed transactions signed by a given address. It is used to + + prevent replay attacks. + description: >- + SignerInfo describes the public key and signing mode of + a single top-level + + signer. + description: >- + signer_infos defines the signing modes for the required + signers. The number + + and order of elements must match the required signers from TxBody's + + messages. The first element is the primary signer and the one which pays + + the fee. + fee: + description: >- + Fee is the fee and gas limit for the transaction. The + first signer is the + + primary signer and the one which pays the fee. The fee can be calculated + + based on the cost of evaluating the body and doing signature verification + + of the signers. This can be estimated via simulation. + type: object + properties: + amount: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an + amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + title: amount is the amount of coins to be paid as a fee + gas_limit: + type: string + format: uint64 + title: >- + gas_limit is the maximum gas that can be used in + transaction processing + + before an out of gas error occurs + payer: + type: string + description: >- + if unset, the first signer is responsible for paying + the fees. If set, the specified account must pay the + fees. + + the payer must be a tx signer (and thus have signed this field in AuthInfo). + + setting this field does *not* change the ordering of required signers for the transaction. + granter: + type: string + title: >- + if set, the fee payer (either the first signer or the + value of the payer field) requests that a fee grant be + used + + to pay fees instead of the fee payer's own balance. If an appropriate fee grant does not exist or the chain does + + not support fee grants, this will fail + description: >- + AuthInfo describes the fee and signer modes that are used to + sign a + + transaction. + signatures: + type: array + items: + type: string + format: byte + description: >- + signatures is a list of signatures that matches the length and + order of + + AuthInfo's signer_infos to allow connecting signature meta information like + + public key and signing mode by position. + description: Tx is the standard type used for broadcasting transactions. + description: txs are the transactions in the block. + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + block: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for processing a + block in the blockchain, + + including all blockchain data structures and the rules of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + data: + type: object + properties: + txs: + type: array + items: + type: string + format: byte + description: >- + Txs that will be applied by state @ block.Height+1. + + NOTE: not all txs here are valid. We're just agreeing on the order first. + + This means that block.AppHash does not include these txs. + title: Data contains the set of transactions included in the block + evidence: + type: object + properties: + evidence: + type: array + items: + type: object + properties: + duplicate_vote_evidence: + type: object + properties: + vote_a: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: >- + SignedMsgType is a type of signed message in + the consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or commit + vote from validators for + + consensus. + vote_b: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: >- + SignedMsgType is a type of signed message in + the consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or commit + vote from validators for + + consensus. + total_voting_power: + type: string + format: int64 + validator_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: DuplicateVoteEvidence contains evidence of a validator signed two + conflicting votes. + light_client_attack_evidence: + type: object + properties: + conflicting_block: + type: object + properties: + signed_header: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules + for processing a block in the + blockchain, + + including all blockchain data structures and the rules of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: BlockIdFlag indicates which BlcokID the signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: CommitSig is a part of the Vote included in a Commit. + description: Commit contains the evidence that a block was committed by a set of + validators. + validator_set: + type: object + properties: + validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + proposer: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + common_height: + type: string + format: int64 + byzantine_validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: LightClientAttackEvidence contains evidence of a set of validators + attempting to mislead a light client. + last_commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: BlockIdFlag indicates which BlcokID the signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: CommitSig is a part of the Vote included in a Commit. + description: Commit contains the evidence that a block was committed by a set of + validators. + pagination: + description: pagination defines a pagination for the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + GetBlockWithTxsResponse is the response type for the + Service.GetBlockWithTxs method. + + + Since: cosmos-sdk 0.45.2 + cosmos.tx.v1beta1.GetTxResponse: + type: object + properties: + tx: + type: object + properties: + body: + title: body is the processable content of the transaction + type: object + properties: + messages: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + messages is a list of messages to be executed. The required + signers of + + those messages define the number and order of elements in AuthInfo's + + signer_infos and Tx's signatures. Each required signer address is added to + + the list only the first time it occurs. + + By convention, the first required signer (usually from the first message) + + is referred to as the primary signer and pays the fee for the whole + + transaction. + memo: + type: string + description: >- + memo is any arbitrary note/comment to be added to the + transaction. + + WARNING: in clients, any publicly exposed text should not be called memo, + + but should be called `note` instead (see https://github.com/cosmos/cosmos-sdk/issues/9122). + timeout_height: + type: string + format: uint64 + title: >- + timeout is the block height after which this transaction + will not + + be processed by the chain + extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be added by + chains + + when the default options are not sufficient. If any of these are present + + and can't be handled, the transaction will be rejected + non_critical_extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be added by + chains + + when the default options are not sufficient. If any of these are present + + and can't be handled, they will be ignored + description: TxBody is the body of a transaction that all signers sign over. + auth_info: + title: >- + auth_info is the authorization related content of the + transaction, + + specifically signers, signer modes and fee + type: object + properties: + signer_infos: + type: array + items: + type: object + properties: + public_key: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + public_key is the public key of the signer. It is + optional for accounts + + that already exist in state. If unset, the verifier can use the required \ + + signer address for this position and lookup the public key. + mode_info: + title: >- + mode_info describes the signing mode of the signer and + is a nested + + structure to support nested multisig pubkey's + type: object + properties: + single: + title: single represents a single signer + type: object + properties: + mode: + title: mode is the signing mode of the single signer + type: string + enum: + - SIGN_MODE_UNSPECIFIED + - SIGN_MODE_DIRECT + - SIGN_MODE_TEXTUAL + - SIGN_MODE_LEGACY_AMINO_JSON + - SIGN_MODE_EIP_191 + default: SIGN_MODE_UNSPECIFIED + description: >- + SignMode represents a signing mode with its + own security guarantees. + + - SIGN_MODE_UNSPECIFIED: SIGN_MODE_UNSPECIFIED specifies an unknown signing mode and will be + rejected + - SIGN_MODE_DIRECT: SIGN_MODE_DIRECT specifies a signing mode which uses SignDoc and is + verified with raw bytes from Tx + - SIGN_MODE_TEXTUAL: SIGN_MODE_TEXTUAL is a future signing mode that will verify some + human-readable textual representation on top of the binary representation + + from SIGN_MODE_DIRECT + - SIGN_MODE_LEGACY_AMINO_JSON: SIGN_MODE_LEGACY_AMINO_JSON is a backwards compatibility mode which uses + Amino JSON and will be removed in the future + - SIGN_MODE_EIP_191: SIGN_MODE_EIP_191 specifies the sign mode for EIP 191 signing on the Cosmos + SDK. Ref: https://eips.ethereum.org/EIPS/eip-191 + + + Currently, SIGN_MODE_EIP_191 is registered as a SignMode enum variant, + + but is not implemented on the SDK by default. To enable EIP-191, you need + + to pass a custom `TxConfig` that has an implementation of + + `SignModeHandler` for EIP-191. The SDK may decide to fully support + + EIP-191 in the future. + + + Since: cosmos-sdk 0.45.2 + multi: + title: multi represents a nested multisig signer + type: object + properties: + bitarray: + title: bitarray specifies which keys within the multisig are signing + type: object + properties: + extra_bits_stored: + type: integer + format: int64 + elems: + type: string + format: byte + description: >- + CompactBitArray is an implementation of a + space efficient bit array. + + This is used to ensure that the encoded data takes up a minimal amount of + + space after proto encoding. + + This is not thread safe, and is not intended for concurrent usage. + mode_infos: + type: array + items: {} + title: >- + mode_infos is the corresponding modes of the + signers of the multisig + + which could include nested multisig public keys + description: ModeInfo describes the signing mode of a single or nested multisig + signer. + sequence: + type: string + format: uint64 + description: >- + sequence is the sequence of the account, which + describes the + + number of committed transactions signed by a given address. It is used to + + prevent replay attacks. + description: >- + SignerInfo describes the public key and signing mode of a + single top-level + + signer. + description: >- + signer_infos defines the signing modes for the required + signers. The number + + and order of elements must match the required signers from TxBody's + + messages. The first element is the primary signer and the one which pays + + the fee. + fee: + description: >- + Fee is the fee and gas limit for the transaction. The first + signer is the + + primary signer and the one which pays the fee. The fee can be calculated + + based on the cost of evaluating the body and doing signature verification + + of the signers. This can be estimated via simulation. + type: object + properties: + amount: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an + amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + title: amount is the amount of coins to be paid as a fee + gas_limit: + type: string + format: uint64 + title: >- + gas_limit is the maximum gas that can be used in + transaction processing + + before an out of gas error occurs + payer: + type: string + description: >- + if unset, the first signer is responsible for paying the + fees. If set, the specified account must pay the fees. + + the payer must be a tx signer (and thus have signed this field in AuthInfo). + + setting this field does *not* change the ordering of required signers for the transaction. + granter: + type: string + title: >- + if set, the fee payer (either the first signer or the + value of the payer field) requests that a fee grant be + used + + to pay fees instead of the fee payer's own balance. If an appropriate fee grant does not exist or the chain does + + not support fee grants, this will fail + description: >- + AuthInfo describes the fee and signer modes that are used to + sign a + + transaction. + signatures: + type: array + items: + type: string + format: byte + description: >- + signatures is a list of signatures that matches the length and + order of + + AuthInfo's signer_infos to allow connecting signature meta information like + + public key and signing mode by position. + description: Tx is the standard type used for broadcasting transactions. + tx_response: + type: object + properties: + height: + type: string + format: int64 + title: The block height + txhash: + type: string + description: The transaction hash. + codespace: + type: string + title: Namespace for the Code + code: + type: integer + format: int64 + description: Response code. + data: + type: string + description: Result bytes, if any. + raw_log: + type: string + description: |- + The output of the application's logger (raw string). May be + non-deterministic. + logs: + type: array + items: + type: object + properties: + msg_index: + type: integer + format: int64 + log: + type: string + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + value: + type: string + description: >- + Attribute defines an attribute wrapper where the + key and value are + + strings instead of raw bytes. + description: >- + StringEvent defines en Event object wrapper where all + the attributes + + contain key/value pairs that are strings instead of raw bytes. + description: >- + Events contains a slice of Event objects that were emitted + during some + + execution. + description: ABCIMessageLog defines a structure containing an indexed tx ABCI + message log. + description: The output of the application's logger (typed). May be + non-deterministic. + info: + type: string + description: Additional information. May be non-deterministic. + gas_wanted: + type: string + format: int64 + description: Amount of gas requested for transaction. + gas_used: + type: string + format: int64 + description: Amount of gas consumed by transaction. + tx: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: The request transaction bytes. + timestamp: + type: string + description: >- + Time of the previous block. For heights > 1, it's the weighted + median of + + the timestamps of the valid votes in the block.LastCommit. For height == 1, + + it's genesis time. + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + format: byte + value: + type: string + format: byte + index: + type: boolean + description: EventAttribute is a single key-value pair, associated with an + event. + description: >- + Event allows application developers to attach additional + information to + + ResponseBeginBlock, ResponseEndBlock, ResponseCheckTx and ResponseDeliverTx. + + Later, transactions may be queried using these events. + description: >- + Events defines all the events emitted by processing a + transaction. Note, + + these events include those emitted by processing all the messages and those + + emitted from the ante handler. Whereas Logs contains the events, with + + additional metadata, emitted only by processing the messages. + + + Since: cosmos-sdk 0.42.11, 0.44.5, 0.45 + description: >- + TxResponse defines a structure containing relevant tx data and + metadata. The + + tags are stringified and the log is JSON decoded. + description: GetTxResponse is the response type for the Service.GetTx method. + cosmos.tx.v1beta1.GetTxsEventResponse: + type: object + properties: + txs: + type: array + items: + type: object + properties: + body: + title: body is the processable content of the transaction + type: object + properties: + messages: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + messages is a list of messages to be executed. The + required signers of + + those messages define the number and order of elements in AuthInfo's + + signer_infos and Tx's signatures. Each required signer address is added to + + the list only the first time it occurs. + + By convention, the first required signer (usually from the first message) + + is referred to as the primary signer and pays the fee for the whole + + transaction. + memo: + type: string + description: >- + memo is any arbitrary note/comment to be added to the + transaction. + + WARNING: in clients, any publicly exposed text should not be called memo, + + but should be called `note` instead (see https://github.com/cosmos/cosmos-sdk/issues/9122). + timeout_height: + type: string + format: uint64 + title: >- + timeout is the block height after which this transaction + will not + + be processed by the chain + extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be added + by chains + + when the default options are not sufficient. If any of these are present + + and can't be handled, the transaction will be rejected + non_critical_extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be added + by chains + + when the default options are not sufficient. If any of these are present + + and can't be handled, they will be ignored + description: TxBody is the body of a transaction that all signers sign over. + auth_info: + title: >- + auth_info is the authorization related content of the + transaction, + + specifically signers, signer modes and fee + type: object + properties: + signer_infos: + type: array + items: + type: object + properties: + public_key: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + public_key is the public key of the signer. It is + optional for accounts + + that already exist in state. If unset, the verifier can use the required \ + + signer address for this position and lookup the public key. + mode_info: + title: >- + mode_info describes the signing mode of the signer + and is a nested + + structure to support nested multisig pubkey's + type: object + properties: + single: + title: single represents a single signer + type: object + properties: + mode: + title: mode is the signing mode of the single signer + type: string + enum: + - SIGN_MODE_UNSPECIFIED + - SIGN_MODE_DIRECT + - SIGN_MODE_TEXTUAL + - SIGN_MODE_LEGACY_AMINO_JSON + - SIGN_MODE_EIP_191 + default: SIGN_MODE_UNSPECIFIED + description: >- + SignMode represents a signing mode with its + own security guarantees. + + - SIGN_MODE_UNSPECIFIED: SIGN_MODE_UNSPECIFIED specifies an unknown signing mode and will be + rejected + - SIGN_MODE_DIRECT: SIGN_MODE_DIRECT specifies a signing mode which uses SignDoc and is + verified with raw bytes from Tx + - SIGN_MODE_TEXTUAL: SIGN_MODE_TEXTUAL is a future signing mode that will verify some + human-readable textual representation on top of the binary representation + + from SIGN_MODE_DIRECT + - SIGN_MODE_LEGACY_AMINO_JSON: SIGN_MODE_LEGACY_AMINO_JSON is a backwards compatibility mode which uses + Amino JSON and will be removed in the future + - SIGN_MODE_EIP_191: SIGN_MODE_EIP_191 specifies the sign mode for EIP 191 signing on the Cosmos + SDK. Ref: https://eips.ethereum.org/EIPS/eip-191 + + + Currently, SIGN_MODE_EIP_191 is registered as a SignMode enum variant, + + but is not implemented on the SDK by default. To enable EIP-191, you need + + to pass a custom `TxConfig` that has an implementation of + + `SignModeHandler` for EIP-191. The SDK may decide to fully support + + EIP-191 in the future. + + + Since: cosmos-sdk 0.45.2 + multi: + title: multi represents a nested multisig signer + type: object + properties: + bitarray: + title: bitarray specifies which keys within the multisig are signing + type: object + properties: + extra_bits_stored: + type: integer + format: int64 + elems: + type: string + format: byte + description: >- + CompactBitArray is an implementation of a + space efficient bit array. + + This is used to ensure that the encoded data takes up a minimal amount of + + space after proto encoding. + + This is not thread safe, and is not intended for concurrent usage. + mode_infos: + type: array + items: {} + title: >- + mode_infos is the corresponding modes of the + signers of the multisig + + which could include nested multisig public keys + description: ModeInfo describes the signing mode of a single or nested multisig + signer. + sequence: + type: string + format: uint64 + description: >- + sequence is the sequence of the account, which + describes the + + number of committed transactions signed by a given address. It is used to + + prevent replay attacks. + description: >- + SignerInfo describes the public key and signing mode of + a single top-level + + signer. + description: >- + signer_infos defines the signing modes for the required + signers. The number + + and order of elements must match the required signers from TxBody's + + messages. The first element is the primary signer and the one which pays + + the fee. + fee: + description: >- + Fee is the fee and gas limit for the transaction. The + first signer is the + + primary signer and the one which pays the fee. The fee can be calculated + + based on the cost of evaluating the body and doing signature verification + + of the signers. This can be estimated via simulation. + type: object + properties: + amount: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an + amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + title: amount is the amount of coins to be paid as a fee + gas_limit: + type: string + format: uint64 + title: >- + gas_limit is the maximum gas that can be used in + transaction processing + + before an out of gas error occurs + payer: + type: string + description: >- + if unset, the first signer is responsible for paying + the fees. If set, the specified account must pay the + fees. + + the payer must be a tx signer (and thus have signed this field in AuthInfo). + + setting this field does *not* change the ordering of required signers for the transaction. + granter: + type: string + title: >- + if set, the fee payer (either the first signer or the + value of the payer field) requests that a fee grant be + used + + to pay fees instead of the fee payer's own balance. If an appropriate fee grant does not exist or the chain does + + not support fee grants, this will fail + description: >- + AuthInfo describes the fee and signer modes that are used to + sign a + + transaction. + signatures: + type: array + items: + type: string + format: byte + description: >- + signatures is a list of signatures that matches the length and + order of + + AuthInfo's signer_infos to allow connecting signature meta information like + + public key and signing mode by position. + description: Tx is the standard type used for broadcasting transactions. + description: txs is the list of queried transactions. + tx_responses: + type: array + items: + type: object + properties: + height: + type: string + format: int64 + title: The block height + txhash: + type: string + description: The transaction hash. + codespace: + type: string + title: Namespace for the Code + code: + type: integer + format: int64 + description: Response code. + data: + type: string + description: Result bytes, if any. + raw_log: + type: string + description: |- + The output of the application's logger (raw string). May be + non-deterministic. + logs: + type: array + items: + type: object + properties: + msg_index: + type: integer + format: int64 + log: + type: string + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + value: + type: string + description: >- + Attribute defines an attribute wrapper where the + key and value are + + strings instead of raw bytes. + description: >- + StringEvent defines en Event object wrapper where all + the attributes + + contain key/value pairs that are strings instead of raw bytes. + description: >- + Events contains a slice of Event objects that were + emitted during some + + execution. + description: ABCIMessageLog defines a structure containing an indexed tx ABCI + message log. + description: The output of the application's logger (typed). May be + non-deterministic. + info: + type: string + description: Additional information. May be non-deterministic. + gas_wanted: + type: string + format: int64 + description: Amount of gas requested for transaction. + gas_used: + type: string + format: int64 + description: Amount of gas consumed by transaction. + tx: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: The request transaction bytes. + timestamp: + type: string + description: >- + Time of the previous block. For heights > 1, it's the weighted + median of + + the timestamps of the valid votes in the block.LastCommit. For height == 1, + + it's genesis time. + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + format: byte + value: + type: string + format: byte + index: + type: boolean + description: EventAttribute is a single key-value pair, associated with an + event. + description: >- + Event allows application developers to attach additional + information to + + ResponseBeginBlock, ResponseEndBlock, ResponseCheckTx and ResponseDeliverTx. + + Later, transactions may be queried using these events. + description: >- + Events defines all the events emitted by processing a + transaction. Note, + + these events include those emitted by processing all the messages and those + + emitted from the ante handler. Whereas Logs contains the events, with + + additional metadata, emitted only by processing the messages. + + + Since: cosmos-sdk 0.42.11, 0.44.5, 0.45 + description: >- + TxResponse defines a structure containing relevant tx data and + metadata. The + + tags are stringified and the log is JSON decoded. + description: tx_responses is the list of queried TxResponses. + pagination: + description: pagination defines a pagination for the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + GetTxsEventResponse is the response type for the Service.TxsByEvents + RPC method. + cosmos.tx.v1beta1.ModeInfo: + type: object + properties: + single: + title: single represents a single signer + type: object + properties: + mode: + title: mode is the signing mode of the single signer + type: string + enum: + - SIGN_MODE_UNSPECIFIED + - SIGN_MODE_DIRECT + - SIGN_MODE_TEXTUAL + - SIGN_MODE_LEGACY_AMINO_JSON + - SIGN_MODE_EIP_191 + default: SIGN_MODE_UNSPECIFIED + description: >- + SignMode represents a signing mode with its own security + guarantees. + + - SIGN_MODE_UNSPECIFIED: SIGN_MODE_UNSPECIFIED specifies an unknown signing mode and will be + rejected + - SIGN_MODE_DIRECT: SIGN_MODE_DIRECT specifies a signing mode which uses SignDoc and is + verified with raw bytes from Tx + - SIGN_MODE_TEXTUAL: SIGN_MODE_TEXTUAL is a future signing mode that will verify some + human-readable textual representation on top of the binary representation + + from SIGN_MODE_DIRECT + - SIGN_MODE_LEGACY_AMINO_JSON: SIGN_MODE_LEGACY_AMINO_JSON is a backwards compatibility mode which uses + Amino JSON and will be removed in the future + - SIGN_MODE_EIP_191: SIGN_MODE_EIP_191 specifies the sign mode for EIP 191 signing on the Cosmos + SDK. Ref: https://eips.ethereum.org/EIPS/eip-191 + + + Currently, SIGN_MODE_EIP_191 is registered as a SignMode enum variant, + + but is not implemented on the SDK by default. To enable EIP-191, you need + + to pass a custom `TxConfig` that has an implementation of + + `SignModeHandler` for EIP-191. The SDK may decide to fully support + + EIP-191 in the future. + + + Since: cosmos-sdk 0.45.2 + multi: + title: multi represents a nested multisig signer + type: object + properties: + bitarray: + title: bitarray specifies which keys within the multisig are signing + type: object + properties: + extra_bits_stored: + type: integer + format: int64 + elems: + type: string + format: byte + description: >- + CompactBitArray is an implementation of a space efficient bit + array. + + This is used to ensure that the encoded data takes up a minimal amount of + + space after proto encoding. + + This is not thread safe, and is not intended for concurrent usage. + mode_infos: + type: array + items: {} + title: >- + mode_infos is the corresponding modes of the signers of the + multisig + + which could include nested multisig public keys + description: ModeInfo describes the signing mode of a single or nested multisig + signer. + cosmos.tx.v1beta1.ModeInfo.Multi: + type: object + properties: + bitarray: + title: bitarray specifies which keys within the multisig are signing + type: object + properties: + extra_bits_stored: + type: integer + format: int64 + elems: + type: string + format: byte + description: >- + CompactBitArray is an implementation of a space efficient bit array. + + This is used to ensure that the encoded data takes up a minimal amount of + + space after proto encoding. + + This is not thread safe, and is not intended for concurrent usage. + mode_infos: + type: array + items: {} + title: |- + mode_infos is the corresponding modes of the signers of the multisig + which could include nested multisig public keys + title: Multi is the mode info for a multisig public key + cosmos.tx.v1beta1.ModeInfo.Single: + type: object + properties: + mode: + title: mode is the signing mode of the single signer + type: string + enum: + - SIGN_MODE_UNSPECIFIED + - SIGN_MODE_DIRECT + - SIGN_MODE_TEXTUAL + - SIGN_MODE_LEGACY_AMINO_JSON + - SIGN_MODE_EIP_191 + default: SIGN_MODE_UNSPECIFIED + description: >- + SignMode represents a signing mode with its own security guarantees. + + - SIGN_MODE_UNSPECIFIED: SIGN_MODE_UNSPECIFIED specifies an unknown signing mode and will be + rejected + - SIGN_MODE_DIRECT: SIGN_MODE_DIRECT specifies a signing mode which uses SignDoc and is + verified with raw bytes from Tx + - SIGN_MODE_TEXTUAL: SIGN_MODE_TEXTUAL is a future signing mode that will verify some + human-readable textual representation on top of the binary representation + + from SIGN_MODE_DIRECT + - SIGN_MODE_LEGACY_AMINO_JSON: SIGN_MODE_LEGACY_AMINO_JSON is a backwards compatibility mode which uses + Amino JSON and will be removed in the future + - SIGN_MODE_EIP_191: SIGN_MODE_EIP_191 specifies the sign mode for EIP 191 signing on the Cosmos + SDK. Ref: https://eips.ethereum.org/EIPS/eip-191 + + + Currently, SIGN_MODE_EIP_191 is registered as a SignMode enum variant, + + but is not implemented on the SDK by default. To enable EIP-191, you need + + to pass a custom `TxConfig` that has an implementation of + + `SignModeHandler` for EIP-191. The SDK may decide to fully support + + EIP-191 in the future. + + + Since: cosmos-sdk 0.45.2 + title: >- + Single is the mode info for a single signer. It is structured as a + message + + to allow for additional fields such as locale for SIGN_MODE_TEXTUAL in the + + future + cosmos.tx.v1beta1.OrderBy: + type: string + enum: + - ORDER_BY_UNSPECIFIED + - ORDER_BY_ASC + - ORDER_BY_DESC + default: ORDER_BY_UNSPECIFIED + description: >- + - ORDER_BY_UNSPECIFIED: ORDER_BY_UNSPECIFIED specifies an unknown + sorting order. OrderBy defaults to ASC in this case. + - ORDER_BY_ASC: ORDER_BY_ASC defines ascending order + - ORDER_BY_DESC: ORDER_BY_DESC defines descending order + title: OrderBy defines the sorting order + cosmos.tx.v1beta1.SignerInfo: + type: object + properties: + public_key: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + public_key is the public key of the signer. It is optional for + accounts + + that already exist in state. If unset, the verifier can use the required \ + + signer address for this position and lookup the public key. + mode_info: + title: |- + mode_info describes the signing mode of the signer and is a nested + structure to support nested multisig pubkey's + type: object + properties: + single: + title: single represents a single signer + type: object + properties: + mode: + title: mode is the signing mode of the single signer + type: string + enum: + - SIGN_MODE_UNSPECIFIED + - SIGN_MODE_DIRECT + - SIGN_MODE_TEXTUAL + - SIGN_MODE_LEGACY_AMINO_JSON + - SIGN_MODE_EIP_191 + default: SIGN_MODE_UNSPECIFIED + description: >- + SignMode represents a signing mode with its own security + guarantees. + + - SIGN_MODE_UNSPECIFIED: SIGN_MODE_UNSPECIFIED specifies an unknown signing mode and will be + rejected + - SIGN_MODE_DIRECT: SIGN_MODE_DIRECT specifies a signing mode which uses SignDoc and is + verified with raw bytes from Tx + - SIGN_MODE_TEXTUAL: SIGN_MODE_TEXTUAL is a future signing mode that will verify some + human-readable textual representation on top of the binary representation + + from SIGN_MODE_DIRECT + - SIGN_MODE_LEGACY_AMINO_JSON: SIGN_MODE_LEGACY_AMINO_JSON is a backwards compatibility mode which uses + Amino JSON and will be removed in the future + - SIGN_MODE_EIP_191: SIGN_MODE_EIP_191 specifies the sign mode for EIP 191 signing on the Cosmos + SDK. Ref: https://eips.ethereum.org/EIPS/eip-191 + + + Currently, SIGN_MODE_EIP_191 is registered as a SignMode enum variant, + + but is not implemented on the SDK by default. To enable EIP-191, you need + + to pass a custom `TxConfig` that has an implementation of + + `SignModeHandler` for EIP-191. The SDK may decide to fully support + + EIP-191 in the future. + + + Since: cosmos-sdk 0.45.2 + multi: + title: multi represents a nested multisig signer + type: object + properties: + bitarray: + title: bitarray specifies which keys within the multisig are signing + type: object + properties: + extra_bits_stored: + type: integer + format: int64 + elems: + type: string + format: byte + description: >- + CompactBitArray is an implementation of a space efficient + bit array. + + This is used to ensure that the encoded data takes up a minimal amount of + + space after proto encoding. + + This is not thread safe, and is not intended for concurrent usage. + mode_infos: + type: array + items: {} + title: >- + mode_infos is the corresponding modes of the signers of the + multisig + + which could include nested multisig public keys + description: ModeInfo describes the signing mode of a single or nested multisig + signer. + sequence: + type: string + format: uint64 + description: >- + sequence is the sequence of the account, which describes the + + number of committed transactions signed by a given address. It is used to + + prevent replay attacks. + description: >- + SignerInfo describes the public key and signing mode of a single + top-level + + signer. + cosmos.tx.v1beta1.SimulateRequest: + type: object + properties: + tx: + description: |- + tx is the transaction to simulate. + Deprecated. Send raw tx bytes instead. + type: object + properties: + body: + title: body is the processable content of the transaction + type: object + properties: + messages: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + messages is a list of messages to be executed. The required + signers of + + those messages define the number and order of elements in AuthInfo's + + signer_infos and Tx's signatures. Each required signer address is added to + + the list only the first time it occurs. + + By convention, the first required signer (usually from the first message) + + is referred to as the primary signer and pays the fee for the whole + + transaction. + memo: + type: string + description: >- + memo is any arbitrary note/comment to be added to the + transaction. + + WARNING: in clients, any publicly exposed text should not be called memo, + + but should be called `note` instead (see https://github.com/cosmos/cosmos-sdk/issues/9122). + timeout_height: + type: string + format: uint64 + title: >- + timeout is the block height after which this transaction + will not + + be processed by the chain + extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be added by + chains + + when the default options are not sufficient. If any of these are present + + and can't be handled, the transaction will be rejected + non_critical_extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be added by + chains + + when the default options are not sufficient. If any of these are present + + and can't be handled, they will be ignored + description: TxBody is the body of a transaction that all signers sign over. + auth_info: + title: >- + auth_info is the authorization related content of the + transaction, + + specifically signers, signer modes and fee + type: object + properties: + signer_infos: + type: array + items: + type: object + properties: + public_key: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + public_key is the public key of the signer. It is + optional for accounts + + that already exist in state. If unset, the verifier can use the required \ + + signer address for this position and lookup the public key. + mode_info: + title: >- + mode_info describes the signing mode of the signer and + is a nested + + structure to support nested multisig pubkey's + type: object + properties: + single: + title: single represents a single signer + type: object + properties: + mode: + title: mode is the signing mode of the single signer + type: string + enum: + - SIGN_MODE_UNSPECIFIED + - SIGN_MODE_DIRECT + - SIGN_MODE_TEXTUAL + - SIGN_MODE_LEGACY_AMINO_JSON + - SIGN_MODE_EIP_191 + default: SIGN_MODE_UNSPECIFIED + description: >- + SignMode represents a signing mode with its + own security guarantees. + + - SIGN_MODE_UNSPECIFIED: SIGN_MODE_UNSPECIFIED specifies an unknown signing mode and will be + rejected + - SIGN_MODE_DIRECT: SIGN_MODE_DIRECT specifies a signing mode which uses SignDoc and is + verified with raw bytes from Tx + - SIGN_MODE_TEXTUAL: SIGN_MODE_TEXTUAL is a future signing mode that will verify some + human-readable textual representation on top of the binary representation + + from SIGN_MODE_DIRECT + - SIGN_MODE_LEGACY_AMINO_JSON: SIGN_MODE_LEGACY_AMINO_JSON is a backwards compatibility mode which uses + Amino JSON and will be removed in the future + - SIGN_MODE_EIP_191: SIGN_MODE_EIP_191 specifies the sign mode for EIP 191 signing on the Cosmos + SDK. Ref: https://eips.ethereum.org/EIPS/eip-191 + + + Currently, SIGN_MODE_EIP_191 is registered as a SignMode enum variant, + + but is not implemented on the SDK by default. To enable EIP-191, you need + + to pass a custom `TxConfig` that has an implementation of + + `SignModeHandler` for EIP-191. The SDK may decide to fully support + + EIP-191 in the future. + + + Since: cosmos-sdk 0.45.2 + multi: + title: multi represents a nested multisig signer + type: object + properties: + bitarray: + title: bitarray specifies which keys within the multisig are signing + type: object + properties: + extra_bits_stored: + type: integer + format: int64 + elems: + type: string + format: byte + description: >- + CompactBitArray is an implementation of a + space efficient bit array. + + This is used to ensure that the encoded data takes up a minimal amount of + + space after proto encoding. + + This is not thread safe, and is not intended for concurrent usage. + mode_infos: + type: array + items: {} + title: >- + mode_infos is the corresponding modes of the + signers of the multisig + + which could include nested multisig public keys + description: ModeInfo describes the signing mode of a single or nested multisig + signer. + sequence: + type: string + format: uint64 + description: >- + sequence is the sequence of the account, which + describes the + + number of committed transactions signed by a given address. It is used to + + prevent replay attacks. + description: >- + SignerInfo describes the public key and signing mode of a + single top-level + + signer. + description: >- + signer_infos defines the signing modes for the required + signers. The number + + and order of elements must match the required signers from TxBody's + + messages. The first element is the primary signer and the one which pays + + the fee. + fee: + description: >- + Fee is the fee and gas limit for the transaction. The first + signer is the + + primary signer and the one which pays the fee. The fee can be calculated + + based on the cost of evaluating the body and doing signature verification + + of the signers. This can be estimated via simulation. + type: object + properties: + amount: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an + amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + title: amount is the amount of coins to be paid as a fee + gas_limit: + type: string + format: uint64 + title: >- + gas_limit is the maximum gas that can be used in + transaction processing + + before an out of gas error occurs + payer: + type: string + description: >- + if unset, the first signer is responsible for paying the + fees. If set, the specified account must pay the fees. + + the payer must be a tx signer (and thus have signed this field in AuthInfo). + + setting this field does *not* change the ordering of required signers for the transaction. + granter: + type: string + title: >- + if set, the fee payer (either the first signer or the + value of the payer field) requests that a fee grant be + used + + to pay fees instead of the fee payer's own balance. If an appropriate fee grant does not exist or the chain does + + not support fee grants, this will fail + description: >- + AuthInfo describes the fee and signer modes that are used to + sign a + + transaction. + signatures: + type: array + items: + type: string + format: byte + description: >- + signatures is a list of signatures that matches the length and + order of + + AuthInfo's signer_infos to allow connecting signature meta information like + + public key and signing mode by position. + tx_bytes: + type: string + format: byte + description: |- + tx_bytes is the raw transaction. + + Since: cosmos-sdk 0.43 + description: |- + SimulateRequest is the request type for the Service.Simulate + RPC method. + cosmos.tx.v1beta1.SimulateResponse: + type: object + properties: + gas_info: + description: gas_info is the information about gas used in the simulation. + type: object + properties: + gas_wanted: + type: string + format: uint64 + description: GasWanted is the maximum units of work we allow this tx to perform. + gas_used: + type: string + format: uint64 + description: GasUsed is the amount of gas actually consumed. + result: + description: result is the result of the simulation. + type: object + properties: + data: + type: string + format: byte + description: >- + Data is any data returned from message or handler execution. It + MUST be + + length prefixed in order to separate data from multiple message executions. + log: + type: string + description: Log contains the log information from message or handler execution. + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + format: byte + value: + type: string + format: byte + index: + type: boolean + description: EventAttribute is a single key-value pair, associated with an + event. + description: >- + Event allows application developers to attach additional + information to + + ResponseBeginBlock, ResponseEndBlock, ResponseCheckTx and ResponseDeliverTx. + + Later, transactions may be queried using these events. + description: >- + Events contains a slice of Event objects that were emitted + during message + + or handler execution. + description: |- + SimulateResponse is the response type for the + Service.SimulateRPC method. + cosmos.tx.v1beta1.Tx: + type: object + properties: + body: + title: body is the processable content of the transaction + type: object + properties: + messages: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + messages is a list of messages to be executed. The required + signers of + + those messages define the number and order of elements in AuthInfo's + + signer_infos and Tx's signatures. Each required signer address is added to + + the list only the first time it occurs. + + By convention, the first required signer (usually from the first message) + + is referred to as the primary signer and pays the fee for the whole + + transaction. + memo: + type: string + description: >- + memo is any arbitrary note/comment to be added to the + transaction. + + WARNING: in clients, any publicly exposed text should not be called memo, + + but should be called `note` instead (see https://github.com/cosmos/cosmos-sdk/issues/9122). + timeout_height: + type: string + format: uint64 + title: >- + timeout is the block height after which this transaction will + not + + be processed by the chain + extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be added by + chains + + when the default options are not sufficient. If any of these are present + + and can't be handled, the transaction will be rejected + non_critical_extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be added by + chains + + when the default options are not sufficient. If any of these are present + + and can't be handled, they will be ignored + description: TxBody is the body of a transaction that all signers sign over. + auth_info: + title: |- + auth_info is the authorization related content of the transaction, + specifically signers, signer modes and fee + type: object + properties: + signer_infos: + type: array + items: + type: object + properties: + public_key: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + public_key is the public key of the signer. It is optional + for accounts + + that already exist in state. If unset, the verifier can use the required \ + + signer address for this position and lookup the public key. + mode_info: + title: >- + mode_info describes the signing mode of the signer and is + a nested + + structure to support nested multisig pubkey's + type: object + properties: + single: + title: single represents a single signer + type: object + properties: + mode: + title: mode is the signing mode of the single signer + type: string + enum: + - SIGN_MODE_UNSPECIFIED + - SIGN_MODE_DIRECT + - SIGN_MODE_TEXTUAL + - SIGN_MODE_LEGACY_AMINO_JSON + - SIGN_MODE_EIP_191 + default: SIGN_MODE_UNSPECIFIED + description: >- + SignMode represents a signing mode with its own + security guarantees. + + - SIGN_MODE_UNSPECIFIED: SIGN_MODE_UNSPECIFIED specifies an unknown signing mode and will be + rejected + - SIGN_MODE_DIRECT: SIGN_MODE_DIRECT specifies a signing mode which uses SignDoc and is + verified with raw bytes from Tx + - SIGN_MODE_TEXTUAL: SIGN_MODE_TEXTUAL is a future signing mode that will verify some + human-readable textual representation on top of the binary representation + + from SIGN_MODE_DIRECT + - SIGN_MODE_LEGACY_AMINO_JSON: SIGN_MODE_LEGACY_AMINO_JSON is a backwards compatibility mode which uses + Amino JSON and will be removed in the future + - SIGN_MODE_EIP_191: SIGN_MODE_EIP_191 specifies the sign mode for EIP 191 signing on the Cosmos + SDK. Ref: https://eips.ethereum.org/EIPS/eip-191 + + + Currently, SIGN_MODE_EIP_191 is registered as a SignMode enum variant, + + but is not implemented on the SDK by default. To enable EIP-191, you need + + to pass a custom `TxConfig` that has an implementation of + + `SignModeHandler` for EIP-191. The SDK may decide to fully support + + EIP-191 in the future. + + + Since: cosmos-sdk 0.45.2 + multi: + title: multi represents a nested multisig signer + type: object + properties: + bitarray: + title: bitarray specifies which keys within the multisig are signing + type: object + properties: + extra_bits_stored: + type: integer + format: int64 + elems: + type: string + format: byte + description: >- + CompactBitArray is an implementation of a space + efficient bit array. + + This is used to ensure that the encoded data takes up a minimal amount of + + space after proto encoding. + + This is not thread safe, and is not intended for concurrent usage. + mode_infos: + type: array + items: {} + title: >- + mode_infos is the corresponding modes of the + signers of the multisig + + which could include nested multisig public keys + description: ModeInfo describes the signing mode of a single or nested multisig + signer. + sequence: + type: string + format: uint64 + description: >- + sequence is the sequence of the account, which describes + the + + number of committed transactions signed by a given address. It is used to + + prevent replay attacks. + description: >- + SignerInfo describes the public key and signing mode of a + single top-level + + signer. + description: >- + signer_infos defines the signing modes for the required signers. + The number + + and order of elements must match the required signers from TxBody's + + messages. The first element is the primary signer and the one which pays + + the fee. + fee: + description: >- + Fee is the fee and gas limit for the transaction. The first + signer is the + + primary signer and the one which pays the fee. The fee can be calculated + + based on the cost of evaluating the body and doing signature verification + + of the signers. This can be estimated via simulation. + type: object + properties: + amount: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + title: amount is the amount of coins to be paid as a fee + gas_limit: + type: string + format: uint64 + title: >- + gas_limit is the maximum gas that can be used in transaction + processing + + before an out of gas error occurs + payer: + type: string + description: >- + if unset, the first signer is responsible for paying the + fees. If set, the specified account must pay the fees. + + the payer must be a tx signer (and thus have signed this field in AuthInfo). + + setting this field does *not* change the ordering of required signers for the transaction. + granter: + type: string + title: >- + if set, the fee payer (either the first signer or the value + of the payer field) requests that a fee grant be used + + to pay fees instead of the fee payer's own balance. If an appropriate fee grant does not exist or the chain does + + not support fee grants, this will fail + description: |- + AuthInfo describes the fee and signer modes that are used to sign a + transaction. + signatures: + type: array + items: + type: string + format: byte + description: >- + signatures is a list of signatures that matches the length and order + of + + AuthInfo's signer_infos to allow connecting signature meta information like + + public key and signing mode by position. + description: Tx is the standard type used for broadcasting transactions. + cosmos.tx.v1beta1.TxBody: + type: object + properties: + messages: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + messages is a list of messages to be executed. The required signers + of + + those messages define the number and order of elements in AuthInfo's + + signer_infos and Tx's signatures. Each required signer address is added to + + the list only the first time it occurs. + + By convention, the first required signer (usually from the first message) + + is referred to as the primary signer and pays the fee for the whole + + transaction. + memo: + type: string + description: >- + memo is any arbitrary note/comment to be added to the transaction. + + WARNING: in clients, any publicly exposed text should not be called memo, + + but should be called `note` instead (see https://github.com/cosmos/cosmos-sdk/issues/9122). + timeout_height: + type: string + format: uint64 + title: |- + timeout is the block height after which this transaction will not + be processed by the chain + extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be added by chains + + when the default options are not sufficient. If any of these are present + + and can't be handled, the transaction will be rejected + non_critical_extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be added by chains + + when the default options are not sufficient. If any of these are present + + and can't be handled, they will be ignored + description: TxBody is the body of a transaction that all signers sign over. + tendermint.abci.Event: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + format: byte + value: + type: string + format: byte + index: + type: boolean + description: EventAttribute is a single key-value pair, associated with an + event. + description: >- + Event allows application developers to attach additional information to + + ResponseBeginBlock, ResponseEndBlock, ResponseCheckTx and ResponseDeliverTx. + + Later, transactions may be queried using these events. + tendermint.abci.EventAttribute: + type: object + properties: + key: + type: string + format: byte + value: + type: string + format: byte + index: + type: boolean + description: EventAttribute is a single key-value pair, associated with an event. + intertx.QueryInterchainAccountResponse: + type: object + properties: + interchain_account_address: + type: string + title: QueryInterchainAccountResponse the response type for the + Query/InterchainAccountAddress RPC + cosmwasm.wasm.v1.AbsoluteTxPosition: + type: object + properties: + block_height: + type: string + format: uint64 + title: BlockHeight is the block the contract was created at + tx_index: + type: string + format: uint64 + title: >- + TxIndex is a monotonic counter within the block (actual transaction + index, + + or gas consumed) + description: >- + AbsoluteTxPosition is a unique transaction position that allows for + global + + ordering of transactions. + cosmwasm.wasm.v1.AccessConfig: + type: object + properties: + permission: + type: string + enum: + - ACCESS_TYPE_UNSPECIFIED + - ACCESS_TYPE_NOBODY + - ACCESS_TYPE_ONLY_ADDRESS + - ACCESS_TYPE_EVERYBODY + - ACCESS_TYPE_ANY_OF_ADDRESSES + default: ACCESS_TYPE_UNSPECIFIED + description: >- + - ACCESS_TYPE_UNSPECIFIED: AccessTypeUnspecified placeholder for + empty value + - ACCESS_TYPE_NOBODY: AccessTypeNobody forbidden + - ACCESS_TYPE_ONLY_ADDRESS: AccessTypeOnlyAddress restricted to a single address + Deprecated: use AccessTypeAnyOfAddresses instead + - ACCESS_TYPE_EVERYBODY: AccessTypeEverybody unrestricted + - ACCESS_TYPE_ANY_OF_ADDRESSES: AccessTypeAnyOfAddresses allow any of the addresses + title: AccessType permission types + address: + type: string + title: |- + Address + Deprecated: replaced by addresses + addresses: + type: array + items: + type: string + description: AccessConfig access control type. + cosmwasm.wasm.v1.AccessType: + type: string + enum: + - ACCESS_TYPE_UNSPECIFIED + - ACCESS_TYPE_NOBODY + - ACCESS_TYPE_ONLY_ADDRESS + - ACCESS_TYPE_EVERYBODY + - ACCESS_TYPE_ANY_OF_ADDRESSES + default: ACCESS_TYPE_UNSPECIFIED + description: >- + - ACCESS_TYPE_UNSPECIFIED: AccessTypeUnspecified placeholder for empty + value + - ACCESS_TYPE_NOBODY: AccessTypeNobody forbidden + - ACCESS_TYPE_ONLY_ADDRESS: AccessTypeOnlyAddress restricted to a single address + Deprecated: use AccessTypeAnyOfAddresses instead + - ACCESS_TYPE_EVERYBODY: AccessTypeEverybody unrestricted + - ACCESS_TYPE_ANY_OF_ADDRESSES: AccessTypeAnyOfAddresses allow any of the addresses + title: AccessType permission types + cosmwasm.wasm.v1.CodeInfoResponse: + type: object + properties: + code_id: + type: string + format: uint64 + creator: + type: string + data_hash: + type: string + format: byte + instantiate_permission: + type: object + properties: + permission: + type: string + enum: + - ACCESS_TYPE_UNSPECIFIED + - ACCESS_TYPE_NOBODY + - ACCESS_TYPE_ONLY_ADDRESS + - ACCESS_TYPE_EVERYBODY + - ACCESS_TYPE_ANY_OF_ADDRESSES + default: ACCESS_TYPE_UNSPECIFIED + description: >- + - ACCESS_TYPE_UNSPECIFIED: AccessTypeUnspecified placeholder for + empty value + - ACCESS_TYPE_NOBODY: AccessTypeNobody forbidden + - ACCESS_TYPE_ONLY_ADDRESS: AccessTypeOnlyAddress restricted to a single address + Deprecated: use AccessTypeAnyOfAddresses instead + - ACCESS_TYPE_EVERYBODY: AccessTypeEverybody unrestricted + - ACCESS_TYPE_ANY_OF_ADDRESSES: AccessTypeAnyOfAddresses allow any of the addresses + title: AccessType permission types + address: + type: string + title: |- + Address + Deprecated: replaced by addresses + addresses: + type: array + items: + type: string + description: AccessConfig access control type. + title: CodeInfoResponse contains code meta data from CodeInfo + cosmwasm.wasm.v1.ContractCodeHistoryEntry: + type: object + properties: + operation: + type: string + enum: + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_UNSPECIFIED + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_INIT + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_MIGRATE + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_GENESIS + default: CONTRACT_CODE_HISTORY_OPERATION_TYPE_UNSPECIFIED + description: >- + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_UNSPECIFIED: + ContractCodeHistoryOperationTypeUnspecified placeholder for empty + value + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_INIT: ContractCodeHistoryOperationTypeInit on chain contract instantiation + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_MIGRATE: ContractCodeHistoryOperationTypeMigrate code migration + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_GENESIS: ContractCodeHistoryOperationTypeGenesis based on genesis data + title: ContractCodeHistoryOperationType actions that caused a code change + code_id: + type: string + format: uint64 + title: CodeID is the reference to the stored WASM code + updated: + description: Updated Tx position when the operation was executed. + type: object + properties: + block_height: + type: string + format: uint64 + title: BlockHeight is the block the contract was created at + tx_index: + type: string + format: uint64 + title: >- + TxIndex is a monotonic counter within the block (actual + transaction index, + + or gas consumed) + msg: + type: string + format: byte + description: ContractCodeHistoryEntry metadata to a contract. + cosmwasm.wasm.v1.ContractCodeHistoryOperationType: + type: string + enum: + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_UNSPECIFIED + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_INIT + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_MIGRATE + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_GENESIS + default: CONTRACT_CODE_HISTORY_OPERATION_TYPE_UNSPECIFIED + description: >- + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_UNSPECIFIED: + ContractCodeHistoryOperationTypeUnspecified placeholder for empty value + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_INIT: ContractCodeHistoryOperationTypeInit on chain contract instantiation + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_MIGRATE: ContractCodeHistoryOperationTypeMigrate code migration + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_GENESIS: ContractCodeHistoryOperationTypeGenesis based on genesis data + title: ContractCodeHistoryOperationType actions that caused a code change + cosmwasm.wasm.v1.ContractInfo: + type: object + properties: + code_id: + type: string + format: uint64 + title: CodeID is the reference to the stored Wasm code + creator: + type: string + title: Creator address who initially instantiated the contract + admin: + type: string + title: Admin is an optional address that can execute migrations + label: + type: string + description: Label is optional metadata to be stored with a contract instance. + created: + description: Created Tx position when the contract was instantiated. + type: object + properties: + block_height: + type: string + format: uint64 + title: BlockHeight is the block the contract was created at + tx_index: + type: string + format: uint64 + title: >- + TxIndex is a monotonic counter within the block (actual + transaction index, + + or gas consumed) + ibc_port_id: + type: string + extension: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: |- + Extension is an extension point to store custom metadata within the + persistence model. + title: ContractInfo stores a WASM contract instance + cosmwasm.wasm.v1.Model: + type: object + properties: + key: + type: string + format: byte + title: hex-encode key to read it better (this is often ascii) + value: + type: string + format: byte + title: base64-encode raw value + title: Model is a struct that holds a KV pair + cosmwasm.wasm.v1.Params: + type: object + properties: + code_upload_access: + type: object + properties: + permission: + type: string + enum: + - ACCESS_TYPE_UNSPECIFIED + - ACCESS_TYPE_NOBODY + - ACCESS_TYPE_ONLY_ADDRESS + - ACCESS_TYPE_EVERYBODY + - ACCESS_TYPE_ANY_OF_ADDRESSES + default: ACCESS_TYPE_UNSPECIFIED + description: >- + - ACCESS_TYPE_UNSPECIFIED: AccessTypeUnspecified placeholder for + empty value + - ACCESS_TYPE_NOBODY: AccessTypeNobody forbidden + - ACCESS_TYPE_ONLY_ADDRESS: AccessTypeOnlyAddress restricted to a single address + Deprecated: use AccessTypeAnyOfAddresses instead + - ACCESS_TYPE_EVERYBODY: AccessTypeEverybody unrestricted + - ACCESS_TYPE_ANY_OF_ADDRESSES: AccessTypeAnyOfAddresses allow any of the addresses + title: AccessType permission types + address: + type: string + title: |- + Address + Deprecated: replaced by addresses + addresses: + type: array + items: + type: string + description: AccessConfig access control type. + instantiate_default_permission: + type: string + enum: + - ACCESS_TYPE_UNSPECIFIED + - ACCESS_TYPE_NOBODY + - ACCESS_TYPE_ONLY_ADDRESS + - ACCESS_TYPE_EVERYBODY + - ACCESS_TYPE_ANY_OF_ADDRESSES + default: ACCESS_TYPE_UNSPECIFIED + description: >- + - ACCESS_TYPE_UNSPECIFIED: AccessTypeUnspecified placeholder for + empty value + - ACCESS_TYPE_NOBODY: AccessTypeNobody forbidden + - ACCESS_TYPE_ONLY_ADDRESS: AccessTypeOnlyAddress restricted to a single address + Deprecated: use AccessTypeAnyOfAddresses instead + - ACCESS_TYPE_EVERYBODY: AccessTypeEverybody unrestricted + - ACCESS_TYPE_ANY_OF_ADDRESSES: AccessTypeAnyOfAddresses allow any of the addresses + title: AccessType permission types + description: Params defines the set of wasm parameters. + cosmwasm.wasm.v1.QueryAllContractStateResponse: + type: object + properties: + models: + type: array + items: + type: object + properties: + key: + type: string + format: byte + title: hex-encode key to read it better (this is often ascii) + value: + type: string + format: byte + title: base64-encode raw value + title: Model is a struct that holds a KV pair + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + title: |- + QueryAllContractStateResponse is the response type for the + Query/AllContractState RPC method + cosmwasm.wasm.v1.QueryCodeResponse: + type: object + properties: + code_info: + type: object + properties: + code_id: + type: string + format: uint64 + creator: + type: string + data_hash: + type: string + format: byte + instantiate_permission: + type: object + properties: + permission: + type: string + enum: + - ACCESS_TYPE_UNSPECIFIED + - ACCESS_TYPE_NOBODY + - ACCESS_TYPE_ONLY_ADDRESS + - ACCESS_TYPE_EVERYBODY + - ACCESS_TYPE_ANY_OF_ADDRESSES + default: ACCESS_TYPE_UNSPECIFIED + description: >- + - ACCESS_TYPE_UNSPECIFIED: AccessTypeUnspecified placeholder + for empty value + - ACCESS_TYPE_NOBODY: AccessTypeNobody forbidden + - ACCESS_TYPE_ONLY_ADDRESS: AccessTypeOnlyAddress restricted to a single address + Deprecated: use AccessTypeAnyOfAddresses instead + - ACCESS_TYPE_EVERYBODY: AccessTypeEverybody unrestricted + - ACCESS_TYPE_ANY_OF_ADDRESSES: AccessTypeAnyOfAddresses allow any of the addresses + title: AccessType permission types + address: + type: string + title: |- + Address + Deprecated: replaced by addresses + addresses: + type: array + items: + type: string + description: AccessConfig access control type. + title: CodeInfoResponse contains code meta data from CodeInfo + data: + type: string + format: byte + title: QueryCodeResponse is the response type for the Query/Code RPC method + cosmwasm.wasm.v1.QueryCodesResponse: + type: object + properties: + code_infos: + type: array + items: + type: object + properties: + code_id: + type: string + format: uint64 + creator: + type: string + data_hash: + type: string + format: byte + instantiate_permission: + type: object + properties: + permission: + type: string + enum: + - ACCESS_TYPE_UNSPECIFIED + - ACCESS_TYPE_NOBODY + - ACCESS_TYPE_ONLY_ADDRESS + - ACCESS_TYPE_EVERYBODY + - ACCESS_TYPE_ANY_OF_ADDRESSES + default: ACCESS_TYPE_UNSPECIFIED + description: >- + - ACCESS_TYPE_UNSPECIFIED: AccessTypeUnspecified + placeholder for empty value + - ACCESS_TYPE_NOBODY: AccessTypeNobody forbidden + - ACCESS_TYPE_ONLY_ADDRESS: AccessTypeOnlyAddress restricted to a single address + Deprecated: use AccessTypeAnyOfAddresses instead + - ACCESS_TYPE_EVERYBODY: AccessTypeEverybody unrestricted + - ACCESS_TYPE_ANY_OF_ADDRESSES: AccessTypeAnyOfAddresses allow any of the addresses + title: AccessType permission types + address: + type: string + title: |- + Address + Deprecated: replaced by addresses + addresses: + type: array + items: + type: string + description: AccessConfig access control type. + title: CodeInfoResponse contains code meta data from CodeInfo + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + title: QueryCodesResponse is the response type for the Query/Codes RPC method + cosmwasm.wasm.v1.QueryContractHistoryResponse: + type: object + properties: + entries: + type: array + items: + type: object + properties: + operation: + type: string + enum: + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_UNSPECIFIED + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_INIT + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_MIGRATE + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_GENESIS + default: CONTRACT_CODE_HISTORY_OPERATION_TYPE_UNSPECIFIED + description: >- + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_UNSPECIFIED: + ContractCodeHistoryOperationTypeUnspecified placeholder for + empty value + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_INIT: ContractCodeHistoryOperationTypeInit on chain contract instantiation + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_MIGRATE: ContractCodeHistoryOperationTypeMigrate code migration + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_GENESIS: ContractCodeHistoryOperationTypeGenesis based on genesis data + title: ContractCodeHistoryOperationType actions that caused a code change + code_id: + type: string + format: uint64 + title: CodeID is the reference to the stored WASM code + updated: + description: Updated Tx position when the operation was executed. + type: object + properties: + block_height: + type: string + format: uint64 + title: BlockHeight is the block the contract was created at + tx_index: + type: string + format: uint64 + title: >- + TxIndex is a monotonic counter within the block (actual + transaction index, + + or gas consumed) + msg: + type: string + format: byte + description: ContractCodeHistoryEntry metadata to a contract. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + title: |- + QueryContractHistoryResponse is the response type for the + Query/ContractHistory RPC method + cosmwasm.wasm.v1.QueryContractInfoResponse: + type: object + properties: + address: + type: string + title: address is the address of the contract + contract_info: + type: object + properties: + code_id: + type: string + format: uint64 + title: CodeID is the reference to the stored Wasm code + creator: + type: string + title: Creator address who initially instantiated the contract + admin: + type: string + title: Admin is an optional address that can execute migrations + label: + type: string + description: Label is optional metadata to be stored with a contract instance. + created: + description: Created Tx position when the contract was instantiated. + type: object + properties: + block_height: + type: string + format: uint64 + title: BlockHeight is the block the contract was created at + tx_index: + type: string + format: uint64 + title: >- + TxIndex is a monotonic counter within the block (actual + transaction index, + + or gas consumed) + ibc_port_id: + type: string + extension: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + Extension is an extension point to store custom metadata within + the + + persistence model. + title: ContractInfo stores a WASM contract instance + title: >- + QueryContractInfoResponse is the response type for the + Query/ContractInfo RPC + + method + cosmwasm.wasm.v1.QueryContractsByCodeResponse: + type: object + properties: + contracts: + type: array + items: + type: string + title: contracts are a set of contract addresses + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + title: |- + QueryContractsByCodeResponse is the response type for the + Query/ContractsByCode RPC method + cosmwasm.wasm.v1.QueryContractsByCreatorResponse: + type: object + properties: + contract_addresses: + type: array + items: + type: string + title: ContractAddresses result set + pagination: + description: Pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + QueryContractsByCreatorResponse is the response type for the + Query/ContractsByCreator RPC method. + cosmwasm.wasm.v1.QueryParamsResponse: + type: object + properties: + params: + description: params defines the parameters of the module. + type: object + properties: + code_upload_access: + type: object + properties: + permission: + type: string + enum: + - ACCESS_TYPE_UNSPECIFIED + - ACCESS_TYPE_NOBODY + - ACCESS_TYPE_ONLY_ADDRESS + - ACCESS_TYPE_EVERYBODY + - ACCESS_TYPE_ANY_OF_ADDRESSES + default: ACCESS_TYPE_UNSPECIFIED + description: >- + - ACCESS_TYPE_UNSPECIFIED: AccessTypeUnspecified placeholder + for empty value + - ACCESS_TYPE_NOBODY: AccessTypeNobody forbidden + - ACCESS_TYPE_ONLY_ADDRESS: AccessTypeOnlyAddress restricted to a single address + Deprecated: use AccessTypeAnyOfAddresses instead + - ACCESS_TYPE_EVERYBODY: AccessTypeEverybody unrestricted + - ACCESS_TYPE_ANY_OF_ADDRESSES: AccessTypeAnyOfAddresses allow any of the addresses + title: AccessType permission types + address: + type: string + title: |- + Address + Deprecated: replaced by addresses + addresses: + type: array + items: + type: string + description: AccessConfig access control type. + instantiate_default_permission: + type: string + enum: + - ACCESS_TYPE_UNSPECIFIED + - ACCESS_TYPE_NOBODY + - ACCESS_TYPE_ONLY_ADDRESS + - ACCESS_TYPE_EVERYBODY + - ACCESS_TYPE_ANY_OF_ADDRESSES + default: ACCESS_TYPE_UNSPECIFIED + description: >- + - ACCESS_TYPE_UNSPECIFIED: AccessTypeUnspecified placeholder for + empty value + - ACCESS_TYPE_NOBODY: AccessTypeNobody forbidden + - ACCESS_TYPE_ONLY_ADDRESS: AccessTypeOnlyAddress restricted to a single address + Deprecated: use AccessTypeAnyOfAddresses instead + - ACCESS_TYPE_EVERYBODY: AccessTypeEverybody unrestricted + - ACCESS_TYPE_ANY_OF_ADDRESSES: AccessTypeAnyOfAddresses allow any of the addresses + title: AccessType permission types + description: QueryParamsResponse is the response type for the Query/Params RPC method. + cosmwasm.wasm.v1.QueryPinnedCodesResponse: + type: object + properties: + code_ids: + type: array + items: + type: string + format: uint64 + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + title: |- + QueryPinnedCodesResponse is the response type for the + Query/PinnedCodes RPC method + cosmwasm.wasm.v1.QueryRawContractStateResponse: + type: object + properties: + data: + type: string + format: byte + title: Data contains the raw store data + title: |- + QueryRawContractStateResponse is the response type for the + Query/RawContractState RPC method + cosmwasm.wasm.v1.QuerySmartContractStateResponse: + type: object + properties: + data: + type: string + format: byte + title: Data contains the json data returned from the smart contract + title: |- + QuerySmartContractStateResponse is the response type for the + Query/SmartContractState RPC method + cosmos.feegrant.v1beta1.Grant: + type: object + properties: + granter: + type: string + description: granter is the address of the user granting an allowance of their + funds. + grantee: + type: string + description: grantee is the address of the user being granted an allowance of + another user's funds. + allowance: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: allowance can be any of basic and filtered fee allowance. + title: Grant is stored in the KVStore to record a grant with full context + cosmos.feegrant.v1beta1.QueryAllowanceResponse: + type: object + properties: + allowance: + description: allowance is a allowance granted for grantee by granter. + type: object + properties: + granter: + type: string + description: granter is the address of the user granting an allowance of their + funds. + grantee: + type: string + description: grantee is the address of the user being granted an allowance of + another user's funds. + allowance: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: allowance can be any of basic and filtered fee allowance. + title: Grant is stored in the KVStore to record a grant with full context + description: QueryAllowanceResponse is the response type for the Query/Allowance + RPC method. + cosmos.feegrant.v1beta1.QueryAllowancesByGranterResponse: + type: object + properties: + allowances: + type: array + items: + type: object + properties: + granter: + type: string + description: granter is the address of the user granting an allowance of their + funds. + grantee: + type: string + description: grantee is the address of the user being granted an allowance of + another user's funds. + allowance: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: allowance can be any of basic and filtered fee allowance. + title: Grant is stored in the KVStore to record a grant with full context + description: allowances that have been issued by the granter. + pagination: + description: pagination defines an pagination for the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: QueryAllowancesByGranterResponse is the response type for the + Query/AllowancesByGranter RPC method. + cosmos.feegrant.v1beta1.QueryAllowancesResponse: + type: object + properties: + allowances: + type: array + items: + type: object + properties: + granter: + type: string + description: granter is the address of the user granting an allowance of their + funds. + grantee: + type: string + description: grantee is the address of the user being granted an allowance of + another user's funds. + allowance: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: allowance can be any of basic and filtered fee allowance. + title: Grant is stored in the KVStore to record a grant with full context + description: allowances are allowance's granted for grantee by granter. + pagination: + description: pagination defines an pagination for the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: QueryAllowancesResponse is the response type for the + Query/Allowances RPC method. + type: object + properties: + minimum_gas_prices: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + DecCoin defines a token with a denomination and a decimal amount. + + + NOTE: The amount field is an Dec which implements the custom method + + signatures required by gogoproto. + description: |- + QueryMinimumGasPricesResponse is the response type for the + Query/MinimumGasPrices RPC method. + cosmos.evidence.v1beta1.QueryAllEvidenceResponse: + type: object + properties: + evidence: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: evidence returns all evidences. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryAllEvidenceResponse is the response type for the Query/AllEvidence + RPC + + method. + cosmos.evidence.v1beta1.QueryEvidenceResponse: + type: object + properties: + evidence: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: evidence returns the requested evidence. + description: QueryEvidenceResponse is the response type for the Query/Evidence + RPC method. + cosmos.base.node.v1beta1.ConfigResponse: + type: object + properties: + minimum_gas_price: + type: string + description: ConfigResponse defines the response structure for the Config gRPC query. + cosmos.params.v1beta1.ParamChange: + type: object + properties: + subspace: + type: string + key: + type: string + value: + type: string + description: |- + ParamChange defines an individual parameter change, for use in + ParameterChangeProposal. + cosmos.params.v1beta1.QueryParamsResponse: + type: object + properties: + param: + description: param defines the queried parameter. + type: object + properties: + subspace: + type: string + key: + type: string + value: + type: string + description: QueryParamsResponse is response type for the Query/Params RPC method. + cosmos.gov.v1beta1.Deposit: + type: object + properties: + proposal_id: + type: string + format: uint64 + depositor: + type: string + amount: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + description: |- + Deposit defines an amount deposited by an account address to an active + proposal. + cosmos.gov.v1beta1.DepositParams: + type: object + properties: + min_deposit: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + description: Minimum deposit for a proposal to enter voting period. + max_deposit_period: + type: string + description: >- + Maximum period for Atom holders to deposit on a proposal. Initial + value: 2 + months. + description: DepositParams defines the params for deposits on governance proposals. + cosmos.gov.v1beta1.Proposal: + type: object + properties: + proposal_id: + type: string + format: uint64 + content: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + status: + type: string + enum: + - PROPOSAL_STATUS_UNSPECIFIED + - PROPOSAL_STATUS_DEPOSIT_PERIOD + - PROPOSAL_STATUS_VOTING_PERIOD + - PROPOSAL_STATUS_PASSED + - PROPOSAL_STATUS_REJECTED + - PROPOSAL_STATUS_FAILED + default: PROPOSAL_STATUS_UNSPECIFIED + description: >- + ProposalStatus enumerates the valid statuses of a proposal. + + - PROPOSAL_STATUS_UNSPECIFIED: PROPOSAL_STATUS_UNSPECIFIED defines the default propopsal status. + - PROPOSAL_STATUS_DEPOSIT_PERIOD: PROPOSAL_STATUS_DEPOSIT_PERIOD defines a proposal status during the deposit + period. + - PROPOSAL_STATUS_VOTING_PERIOD: PROPOSAL_STATUS_VOTING_PERIOD defines a proposal status during the voting + period. + - PROPOSAL_STATUS_PASSED: PROPOSAL_STATUS_PASSED defines a proposal status of a proposal that has + passed. + - PROPOSAL_STATUS_REJECTED: PROPOSAL_STATUS_REJECTED defines a proposal status of a proposal that has + been rejected. + - PROPOSAL_STATUS_FAILED: PROPOSAL_STATUS_FAILED defines a proposal status of a proposal that has + failed. + final_tally_result: + type: object + properties: + yes: + type: string + abstain: + type: string + no: + type: string + no_with_veto: + type: string + description: TallyResult defines a standard tally for a governance proposal. + submit_time: + type: string + format: date-time + deposit_end_time: + type: string + format: date-time + total_deposit: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + voting_start_time: + type: string + format: date-time + voting_end_time: + type: string + format: date-time + description: Proposal defines the core field members of a governance proposal. + cosmos.gov.v1beta1.ProposalStatus: + type: string + enum: + - PROPOSAL_STATUS_UNSPECIFIED + - PROPOSAL_STATUS_DEPOSIT_PERIOD + - PROPOSAL_STATUS_VOTING_PERIOD + - PROPOSAL_STATUS_PASSED + - PROPOSAL_STATUS_REJECTED + - PROPOSAL_STATUS_FAILED + default: PROPOSAL_STATUS_UNSPECIFIED + description: >- + ProposalStatus enumerates the valid statuses of a proposal. + + - PROPOSAL_STATUS_UNSPECIFIED: PROPOSAL_STATUS_UNSPECIFIED defines the default propopsal status. + - PROPOSAL_STATUS_DEPOSIT_PERIOD: PROPOSAL_STATUS_DEPOSIT_PERIOD defines a proposal status during the deposit + period. + - PROPOSAL_STATUS_VOTING_PERIOD: PROPOSAL_STATUS_VOTING_PERIOD defines a proposal status during the voting + period. + - PROPOSAL_STATUS_PASSED: PROPOSAL_STATUS_PASSED defines a proposal status of a proposal that has + passed. + - PROPOSAL_STATUS_REJECTED: PROPOSAL_STATUS_REJECTED defines a proposal status of a proposal that has + been rejected. + - PROPOSAL_STATUS_FAILED: PROPOSAL_STATUS_FAILED defines a proposal status of a proposal that has + failed. + cosmos.gov.v1beta1.QueryDepositResponse: + type: object + properties: + deposit: + type: object + properties: + proposal_id: + type: string + format: uint64 + depositor: + type: string + amount: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + description: >- + Deposit defines an amount deposited by an account address to an + active + + proposal. + description: QueryDepositResponse is the response type for the Query/Deposit RPC + method. + cosmos.gov.v1beta1.QueryDepositsResponse: + type: object + properties: + deposits: + type: array + items: + type: object + properties: + proposal_id: + type: string + format: uint64 + depositor: + type: string + amount: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + description: >- + Deposit defines an amount deposited by an account address to an + active + + proposal. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: QueryDepositsResponse is the response type for the Query/Deposits + RPC method. + cosmos.gov.v1beta1.QueryParamsResponse: + type: object + properties: + voting_params: + description: voting_params defines the parameters related to voting. + type: object + properties: + voting_period: + type: string + description: Length of the voting period. + deposit_params: + description: deposit_params defines the parameters related to deposit. + type: object + properties: + min_deposit: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + description: Minimum deposit for a proposal to enter voting period. + max_deposit_period: + type: string + description: >- + Maximum period for Atom holders to deposit on a proposal. + Initial value: 2 + months. + tally_params: + description: tally_params defines the parameters related to tally. + type: object + properties: + quorum: + type: string + format: byte + description: >- + Minimum percentage of total stake needed to vote for a result to + be + considered valid. + threshold: + type: string + format: byte + description: "Minimum proportion of Yes votes for proposal to pass. Default + value: 0.5." + veto_threshold: + type: string + format: byte + description: >- + Minimum value of Veto votes to Total votes ratio for proposal to + be + vetoed. Default value: 1/3. + description: QueryParamsResponse is the response type for the Query/Params RPC method. + cosmos.gov.v1beta1.QueryProposalResponse: + type: object + properties: + proposal: + type: object + properties: + proposal_id: + type: string + format: uint64 + content: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + status: + type: string + enum: + - PROPOSAL_STATUS_UNSPECIFIED + - PROPOSAL_STATUS_DEPOSIT_PERIOD + - PROPOSAL_STATUS_VOTING_PERIOD + - PROPOSAL_STATUS_PASSED + - PROPOSAL_STATUS_REJECTED + - PROPOSAL_STATUS_FAILED + default: PROPOSAL_STATUS_UNSPECIFIED + description: >- + ProposalStatus enumerates the valid statuses of a proposal. + + - PROPOSAL_STATUS_UNSPECIFIED: PROPOSAL_STATUS_UNSPECIFIED defines the default propopsal status. + - PROPOSAL_STATUS_DEPOSIT_PERIOD: PROPOSAL_STATUS_DEPOSIT_PERIOD defines a proposal status during the deposit + period. + - PROPOSAL_STATUS_VOTING_PERIOD: PROPOSAL_STATUS_VOTING_PERIOD defines a proposal status during the voting + period. + - PROPOSAL_STATUS_PASSED: PROPOSAL_STATUS_PASSED defines a proposal status of a proposal that has + passed. + - PROPOSAL_STATUS_REJECTED: PROPOSAL_STATUS_REJECTED defines a proposal status of a proposal that has + been rejected. + - PROPOSAL_STATUS_FAILED: PROPOSAL_STATUS_FAILED defines a proposal status of a proposal that has + failed. + final_tally_result: + type: object + properties: + yes: + type: string + abstain: + type: string + no: + type: string + no_with_veto: + type: string + description: TallyResult defines a standard tally for a governance proposal. + submit_time: + type: string + format: date-time + deposit_end_time: + type: string + format: date-time + total_deposit: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + voting_start_time: + type: string + format: date-time + voting_end_time: + type: string + format: date-time + description: Proposal defines the core field members of a governance proposal. + description: QueryProposalResponse is the response type for the Query/Proposal + RPC method. + cosmos.gov.v1beta1.QueryProposalsResponse: + type: object + properties: + proposals: + type: array + items: + type: object + properties: + proposal_id: + type: string + format: uint64 + content: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + status: + type: string + enum: + - PROPOSAL_STATUS_UNSPECIFIED + - PROPOSAL_STATUS_DEPOSIT_PERIOD + - PROPOSAL_STATUS_VOTING_PERIOD + - PROPOSAL_STATUS_PASSED + - PROPOSAL_STATUS_REJECTED + - PROPOSAL_STATUS_FAILED + default: PROPOSAL_STATUS_UNSPECIFIED + description: >- + ProposalStatus enumerates the valid statuses of a proposal. + + - PROPOSAL_STATUS_UNSPECIFIED: PROPOSAL_STATUS_UNSPECIFIED defines the default propopsal status. + - PROPOSAL_STATUS_DEPOSIT_PERIOD: PROPOSAL_STATUS_DEPOSIT_PERIOD defines a proposal status during the deposit + period. + - PROPOSAL_STATUS_VOTING_PERIOD: PROPOSAL_STATUS_VOTING_PERIOD defines a proposal status during the voting + period. + - PROPOSAL_STATUS_PASSED: PROPOSAL_STATUS_PASSED defines a proposal status of a proposal that has + passed. + - PROPOSAL_STATUS_REJECTED: PROPOSAL_STATUS_REJECTED defines a proposal status of a proposal that has + been rejected. + - PROPOSAL_STATUS_FAILED: PROPOSAL_STATUS_FAILED defines a proposal status of a proposal that has + failed. + final_tally_result: + type: object + properties: + yes: + type: string + abstain: + type: string + no: + type: string + no_with_veto: + type: string + description: TallyResult defines a standard tally for a governance proposal. + submit_time: + type: string + format: date-time + deposit_end_time: + type: string + format: date-time + total_deposit: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom method + + signatures required by gogoproto. + voting_start_time: + type: string + format: date-time + voting_end_time: + type: string + format: date-time + description: Proposal defines the core field members of a governance proposal. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + QueryProposalsResponse is the response type for the Query/Proposals RPC + method. + cosmos.gov.v1beta1.QueryTallyResultResponse: + type: object + properties: + tally: + type: object + properties: + yes: + type: string + abstain: + type: string + no: + type: string + no_with_veto: + type: string + description: TallyResult defines a standard tally for a governance proposal. + description: QueryTallyResultResponse is the response type for the Query/Tally + RPC method. + cosmos.gov.v1beta1.QueryVoteResponse: + type: object + properties: + vote: + type: object + properties: + proposal_id: + type: string + format: uint64 + voter: + type: string + option: + description: >- + Deprecated: Prefer to use `options` instead. This field is set + in queries + + if and only if `len(options) == 1` and that option has weight 1. In all + + other cases, this field will default to VOTE_OPTION_UNSPECIFIED. + type: string + enum: + - VOTE_OPTION_UNSPECIFIED + - VOTE_OPTION_YES + - VOTE_OPTION_ABSTAIN + - VOTE_OPTION_NO + - VOTE_OPTION_NO_WITH_VETO + default: VOTE_OPTION_UNSPECIFIED + options: + type: array + items: + type: object + properties: + option: + type: string + enum: + - VOTE_OPTION_UNSPECIFIED + - VOTE_OPTION_YES + - VOTE_OPTION_ABSTAIN + - VOTE_OPTION_NO + - VOTE_OPTION_NO_WITH_VETO + default: VOTE_OPTION_UNSPECIFIED + description: >- + VoteOption enumerates the valid vote options for a given + governance proposal. + + - VOTE_OPTION_UNSPECIFIED: VOTE_OPTION_UNSPECIFIED defines a no-op vote option. + - VOTE_OPTION_YES: VOTE_OPTION_YES defines a yes vote option. + - VOTE_OPTION_ABSTAIN: VOTE_OPTION_ABSTAIN defines an abstain vote option. + - VOTE_OPTION_NO: VOTE_OPTION_NO defines a no vote option. + - VOTE_OPTION_NO_WITH_VETO: VOTE_OPTION_NO_WITH_VETO defines a no with veto vote option. + weight: + type: string + description: |- + WeightedVoteOption defines a unit of vote for vote split. + + Since: cosmos-sdk 0.43 + title: "Since: cosmos-sdk 0.43" + description: |- + Vote defines a vote on a governance proposal. + A Vote consists of a proposal ID, the voter, and the vote option. + description: QueryVoteResponse is the response type for the Query/Vote RPC method. + cosmos.gov.v1beta1.QueryVotesResponse: + type: object + properties: + votes: + type: array + items: + type: object + properties: + proposal_id: + type: string + format: uint64 + voter: + type: string + option: + description: >- + Deprecated: Prefer to use `options` instead. This field is set + in queries + + if and only if `len(options) == 1` and that option has weight 1. In all + + other cases, this field will default to VOTE_OPTION_UNSPECIFIED. + type: string + enum: + - VOTE_OPTION_UNSPECIFIED + - VOTE_OPTION_YES + - VOTE_OPTION_ABSTAIN + - VOTE_OPTION_NO + - VOTE_OPTION_NO_WITH_VETO + default: VOTE_OPTION_UNSPECIFIED + options: + type: array + items: + type: object + properties: + option: + type: string + enum: + - VOTE_OPTION_UNSPECIFIED + - VOTE_OPTION_YES + - VOTE_OPTION_ABSTAIN + - VOTE_OPTION_NO + - VOTE_OPTION_NO_WITH_VETO + default: VOTE_OPTION_UNSPECIFIED + description: >- + VoteOption enumerates the valid vote options for a given + governance proposal. + + - VOTE_OPTION_UNSPECIFIED: VOTE_OPTION_UNSPECIFIED defines a no-op vote option. + - VOTE_OPTION_YES: VOTE_OPTION_YES defines a yes vote option. + - VOTE_OPTION_ABSTAIN: VOTE_OPTION_ABSTAIN defines an abstain vote option. + - VOTE_OPTION_NO: VOTE_OPTION_NO defines a no vote option. + - VOTE_OPTION_NO_WITH_VETO: VOTE_OPTION_NO_WITH_VETO defines a no with veto vote option. + weight: + type: string + description: |- + WeightedVoteOption defines a unit of vote for vote split. + + Since: cosmos-sdk 0.43 + title: "Since: cosmos-sdk 0.43" + description: |- + Vote defines a vote on a governance proposal. + A Vote consists of a proposal ID, the voter, and the vote option. + description: votes defined the queried votes. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: QueryVotesResponse is the response type for the Query/Votes RPC method. + cosmos.gov.v1beta1.TallyParams: + type: object + properties: + quorum: + type: string + format: byte + description: |- + Minimum percentage of total stake needed to vote for a result to be + considered valid. + threshold: + type: string + format: byte + description: "Minimum proportion of Yes votes for proposal to pass. Default + value: 0.5." + veto_threshold: + type: string + format: byte + description: |- + Minimum value of Veto votes to Total votes ratio for proposal to be + vetoed. Default value: 1/3. + description: TallyParams defines the params for tallying votes on governance + proposals. + cosmos.gov.v1beta1.TallyResult: + type: object + properties: + yes: + type: string + abstain: + type: string + no: + type: string + no_with_veto: + type: string + description: TallyResult defines a standard tally for a governance proposal. + cosmos.gov.v1beta1.Vote: + type: object + properties: + proposal_id: + type: string + format: uint64 + voter: + type: string + option: + description: >- + Deprecated: Prefer to use `options` instead. This field is set in + queries + + if and only if `len(options) == 1` and that option has weight 1. In all + + other cases, this field will default to VOTE_OPTION_UNSPECIFIED. + type: string + enum: + - VOTE_OPTION_UNSPECIFIED + - VOTE_OPTION_YES + - VOTE_OPTION_ABSTAIN + - VOTE_OPTION_NO + - VOTE_OPTION_NO_WITH_VETO + default: VOTE_OPTION_UNSPECIFIED + options: + type: array + items: + type: object + properties: + option: + type: string + enum: + - VOTE_OPTION_UNSPECIFIED + - VOTE_OPTION_YES + - VOTE_OPTION_ABSTAIN + - VOTE_OPTION_NO + - VOTE_OPTION_NO_WITH_VETO + default: VOTE_OPTION_UNSPECIFIED + description: >- + VoteOption enumerates the valid vote options for a given + governance proposal. + + - VOTE_OPTION_UNSPECIFIED: VOTE_OPTION_UNSPECIFIED defines a no-op vote option. + - VOTE_OPTION_YES: VOTE_OPTION_YES defines a yes vote option. + - VOTE_OPTION_ABSTAIN: VOTE_OPTION_ABSTAIN defines an abstain vote option. + - VOTE_OPTION_NO: VOTE_OPTION_NO defines a no vote option. + - VOTE_OPTION_NO_WITH_VETO: VOTE_OPTION_NO_WITH_VETO defines a no with veto vote option. + weight: + type: string + description: |- + WeightedVoteOption defines a unit of vote for vote split. + + Since: cosmos-sdk 0.43 + title: "Since: cosmos-sdk 0.43" + description: |- + Vote defines a vote on a governance proposal. + A Vote consists of a proposal ID, the voter, and the vote option. + cosmos.gov.v1beta1.VoteOption: + type: string + enum: + - VOTE_OPTION_UNSPECIFIED + - VOTE_OPTION_YES + - VOTE_OPTION_ABSTAIN + - VOTE_OPTION_NO + - VOTE_OPTION_NO_WITH_VETO + default: VOTE_OPTION_UNSPECIFIED + description: >- + VoteOption enumerates the valid vote options for a given governance + proposal. + + - VOTE_OPTION_UNSPECIFIED: VOTE_OPTION_UNSPECIFIED defines a no-op vote option. + - VOTE_OPTION_YES: VOTE_OPTION_YES defines a yes vote option. + - VOTE_OPTION_ABSTAIN: VOTE_OPTION_ABSTAIN defines an abstain vote option. + - VOTE_OPTION_NO: VOTE_OPTION_NO defines a no vote option. + - VOTE_OPTION_NO_WITH_VETO: VOTE_OPTION_NO_WITH_VETO defines a no with veto vote option. + cosmos.gov.v1beta1.VotingParams: + type: object + properties: + voting_period: + type: string + description: Length of the voting period. + description: VotingParams defines the params for voting on governance proposals. + cosmos.gov.v1beta1.WeightedVoteOption: + type: object + properties: + option: + type: string + enum: + - VOTE_OPTION_UNSPECIFIED + - VOTE_OPTION_YES + - VOTE_OPTION_ABSTAIN + - VOTE_OPTION_NO + - VOTE_OPTION_NO_WITH_VETO + default: VOTE_OPTION_UNSPECIFIED + description: >- + VoteOption enumerates the valid vote options for a given governance + proposal. + + - VOTE_OPTION_UNSPECIFIED: VOTE_OPTION_UNSPECIFIED defines a no-op vote option. + - VOTE_OPTION_YES: VOTE_OPTION_YES defines a yes vote option. + - VOTE_OPTION_ABSTAIN: VOTE_OPTION_ABSTAIN defines an abstain vote option. + - VOTE_OPTION_NO: VOTE_OPTION_NO defines a no vote option. + - VOTE_OPTION_NO_WITH_VETO: VOTE_OPTION_NO_WITH_VETO defines a no with veto vote option. + weight: + type: string + description: |- + WeightedVoteOption defines a unit of vote for vote split. + + Since: cosmos-sdk 0.43 + type: object + properties: + contract_addresses: + type: array + items: + type: string + title: >- + contract_addresses is the slice of registered contract addresses for + a + + withdrawer + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + QueryWithdrawerFeeSharesResponse is the response type for the + Query/WithdrawerFeeShares RPC method. + cosmos.slashing.v1beta1.Params: + type: object + properties: + signed_blocks_window: + type: string + format: int64 + min_signed_per_window: + type: string + format: byte + downtime_jail_duration: + type: string + slash_fraction_double_sign: + type: string + format: byte + slash_fraction_downtime: + type: string + format: byte + description: Params represents the parameters used for by the slashing module. + cosmos.slashing.v1beta1.QueryParamsResponse: + type: object + properties: + params: + type: object + properties: + signed_blocks_window: + type: string + format: int64 + min_signed_per_window: + type: string + format: byte + downtime_jail_duration: + type: string + slash_fraction_double_sign: + type: string + format: byte + slash_fraction_downtime: + type: string + format: byte + description: Params represents the parameters used for by the slashing module. + title: QueryParamsResponse is the response type for the Query/Params RPC method + cosmos.slashing.v1beta1.QuerySigningInfoResponse: + type: object + properties: + val_signing_info: + type: object + properties: + address: + type: string + start_height: + type: string + format: int64 + title: Height at which validator was first a candidate OR was unjailed + index_offset: + type: string + format: int64 + description: >- + Index which is incremented each time the validator was a bonded + + in a block and may have signed a precommit or not. This in conjunction with the + + `SignedBlocksWindow` param determines the index in the `MissedBlocksBitArray`. + jailed_until: + type: string + format: date-time + description: Timestamp until which the validator is jailed due to liveness + downtime. + tombstoned: + type: boolean + description: >- + Whether or not a validator has been tombstoned (killed out of + validator set). It is set + + once the validator commits an equivocation or for any other configured misbehiavor. + missed_blocks_counter: + type: string + format: int64 + description: >- + A counter kept to avoid unnecessary array reads. + + Note that `Sum(MissedBlocksBitArray)` always equals `MissedBlocksCounter`. + description: >- + ValidatorSigningInfo defines a validator's signing info for + monitoring their + + liveness activity. + title: val_signing_info is the signing info of requested val cons address + title: >- + QuerySigningInfoResponse is the response type for the Query/SigningInfo + RPC + + method + cosmos.slashing.v1beta1.QuerySigningInfosResponse: + type: object + properties: + info: + type: array + items: + type: object + properties: + address: + type: string + start_height: + type: string + format: int64 + title: Height at which validator was first a candidate OR was unjailed + index_offset: + type: string + format: int64 + description: >- + Index which is incremented each time the validator was a + bonded + + in a block and may have signed a precommit or not. This in conjunction with the + + `SignedBlocksWindow` param determines the index in the `MissedBlocksBitArray`. + jailed_until: + type: string + format: date-time + description: Timestamp until which the validator is jailed due to liveness + downtime. + tombstoned: + type: boolean + description: >- + Whether or not a validator has been tombstoned (killed out of + validator set). It is set + + once the validator commits an equivocation or for any other configured misbehiavor. + missed_blocks_counter: + type: string + format: int64 + description: >- + A counter kept to avoid unnecessary array reads. + + Note that `Sum(MissedBlocksBitArray)` always equals `MissedBlocksCounter`. + description: >- + ValidatorSigningInfo defines a validator's signing info for + monitoring their + + liveness activity. + title: info is the signing info of all validators + pagination: + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + PageResponse is to be embedded in gRPC response messages where the + corresponding request message has used PageRequest. + + message SomeResponse { + repeated Bar results = 1; + PageResponse page = 2; + } + title: >- + QuerySigningInfosResponse is the response type for the + Query/SigningInfos RPC + + method + cosmos.slashing.v1beta1.ValidatorSigningInfo: + type: object + properties: + address: + type: string + start_height: + type: string + format: int64 + title: Height at which validator was first a candidate OR was unjailed + index_offset: + type: string + format: int64 + description: >- + Index which is incremented each time the validator was a bonded + + in a block and may have signed a precommit or not. This in conjunction with the + + `SignedBlocksWindow` param determines the index in the `MissedBlocksBitArray`. + jailed_until: + type: string + format: date-time + description: Timestamp until which the validator is jailed due to liveness + downtime. + tombstoned: + type: boolean + description: >- + Whether or not a validator has been tombstoned (killed out of + validator set). It is set + + once the validator commits an equivocation or for any other configured misbehiavor. + missed_blocks_counter: + type: string + format: int64 + description: >- + A counter kept to avoid unnecessary array reads. + + Note that `Sum(MissedBlocksBitArray)` always equals `MissedBlocksCounter`. + description: >- + ValidatorSigningInfo defines a validator's signing info for monitoring + their + + liveness activity. + cosmos.upgrade.v1beta1.ModuleVersion: + type: object + properties: + name: + type: string + title: name of the app module + version: + type: string + format: uint64 + title: consensus version of the app module + description: |- + ModuleVersion specifies a module and its consensus version. + + Since: cosmos-sdk 0.43 + cosmos.upgrade.v1beta1.Plan: + type: object + properties: + name: + type: string + description: >- + Sets the name for the upgrade. This name will be used by the + upgraded + + version of the software to apply any special "on-upgrade" commands during + + the first BeginBlock method after the upgrade is applied. It is also used + + to detect whether a software version can handle a given upgrade. If no + + upgrade handler with this name has been set in the software, it will be + + assumed that the software is out-of-date when the upgrade Time or Height is + + reached and the software will exit. + time: + type: string + format: date-time + description: >- + Deprecated: Time based upgrades have been deprecated. Time based + upgrade logic + + has been removed from the SDK. + + If this field is not empty, an error will be thrown. + height: + type: string + format: int64 + description: |- + The height at which the upgrade must be performed. + Only used if Time is not set. + info: + type: string + title: |- + Any application specific upgrade info to be included on-chain + such as a git commit that validators could automatically upgrade to + upgraded_client_state: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + Deprecated: UpgradedClientState field has been deprecated. IBC + upgrade logic has been + + moved to the IBC module in the sub module 02-client. + + If this field is not empty, an error will be thrown. + description: Plan specifies information about a planned upgrade and when it + should occur. + cosmos.upgrade.v1beta1.QueryAppliedPlanResponse: + type: object + properties: + height: + type: string + format: int64 + description: height is the block height at which the plan was applied. + description: >- + QueryAppliedPlanResponse is the response type for the Query/AppliedPlan + RPC + + method. + cosmos.upgrade.v1beta1.QueryCurrentPlanResponse: + type: object + properties: + plan: + description: plan is the current upgrade plan. + type: object + properties: + name: + type: string + description: >- + Sets the name for the upgrade. This name will be used by the + upgraded + + version of the software to apply any special "on-upgrade" commands during + + the first BeginBlock method after the upgrade is applied. It is also used + + to detect whether a software version can handle a given upgrade. If no + + upgrade handler with this name has been set in the software, it will be + + assumed that the software is out-of-date when the upgrade Time or Height is + + reached and the software will exit. + time: + type: string + format: date-time + description: >- + Deprecated: Time based upgrades have been deprecated. Time based + upgrade logic + + has been removed from the SDK. + + If this field is not empty, an error will be thrown. + height: + type: string + format: int64 + description: |- + The height at which the upgrade must be performed. + Only used if Time is not set. + info: + type: string + title: >- + Any application specific upgrade info to be included on-chain + + such as a git commit that validators could automatically upgrade to + upgraded_client_state: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + Deprecated: UpgradedClientState field has been deprecated. IBC + upgrade logic has been + + moved to the IBC module in the sub module 02-client. + + If this field is not empty, an error will be thrown. + description: >- + QueryCurrentPlanResponse is the response type for the Query/CurrentPlan + RPC + + method. + cosmos.upgrade.v1beta1.QueryModuleVersionsResponse: + type: object + properties: + module_versions: + type: array + items: + type: object + properties: + name: + type: string + title: name of the app module + version: + type: string + format: uint64 + title: consensus version of the app module + description: |- + ModuleVersion specifies a module and its consensus version. + + Since: cosmos-sdk 0.43 + description: module_versions is a list of module names with their consensus + versions. + description: >- + QueryModuleVersionsResponse is the response type for the + Query/ModuleVersions + + RPC method. + + + Since: cosmos-sdk 0.43 + cosmos.upgrade.v1beta1.QueryUpgradedConsensusStateResponse: + type: object + properties: + upgraded_consensus_state: + type: string + format: byte + title: "Since: cosmos-sdk 0.43" + description: >- + QueryUpgradedConsensusStateResponse is the response type for the + Query/UpgradedConsensusState + + RPC method. + cosmos.authz.v1beta1.Grant: + type: object + properties: + authorization: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + expiration: + type: string + format: date-time + description: |- + Grant gives permissions to execute + the provide method with expiration time. + cosmos.authz.v1beta1.GrantAuthorization: + type: object + properties: + granter: + type: string + grantee: + type: string + authorization: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + expiration: + type: string + format: date-time + description: "Since: cosmos-sdk 0.45.2" + title: >- + GrantAuthorization extends a grant with both the addresses of the + grantee and granter. + + It is used in genesis.proto and query.proto + cosmos.authz.v1beta1.QueryGranteeGrantsResponse: + type: object + properties: + grants: + type: array + items: + type: object + properties: + granter: + type: string + grantee: + type: string + authorization: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + expiration: + type: string + format: date-time + description: "Since: cosmos-sdk 0.45.2" + title: >- + GrantAuthorization extends a grant with both the addresses of the + grantee and granter. + + It is used in genesis.proto and query.proto + description: grants is a list of grants granted to the grantee. + pagination: + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + PageResponse is to be embedded in gRPC response messages where the + corresponding request message has used PageRequest. + + message SomeResponse { + repeated Bar results = 1; + PageResponse page = 2; + } + description: QueryGranteeGrantsResponse is the response type for the + Query/GranteeGrants RPC method. + cosmos.authz.v1beta1.QueryGranterGrantsResponse: + type: object + properties: + grants: + type: array + items: + type: object + properties: + granter: + type: string + grantee: + type: string + authorization: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + expiration: + type: string + format: date-time + description: "Since: cosmos-sdk 0.45.2" + title: >- + GrantAuthorization extends a grant with both the addresses of the + grantee and granter. + + It is used in genesis.proto and query.proto + description: grants is a list of grants granted by the granter. + pagination: + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + PageResponse is to be embedded in gRPC response messages where the + corresponding request message has used PageRequest. + + message SomeResponse { + repeated Bar results = 1; + PageResponse page = 2; + } + description: QueryGranterGrantsResponse is the response type for the + Query/GranterGrants RPC method. + cosmos.authz.v1beta1.QueryGrantsResponse: + type: object + properties: + grants: + type: array + items: + type: object + properties: + authorization: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + expiration: + type: string + format: date-time + description: |- + Grant gives permissions to execute + the provide method with expiration time. + description: authorizations is a list of grants granted for grantee by granter. + pagination: + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + PageResponse is to be embedded in gRPC response messages where the + corresponding request message has used PageRequest. + + message SomeResponse { + repeated Bar results = 1; + PageResponse page = 2; + } + description: QueryGrantsResponse is the response type for the + Query/Authorizations RPC method. + type: object + properties: + params: + description: params defines the parameters of the module. + type: object + properties: + mint_denom: + type: string + title: type of coin to mint + blocks_per_year: + type: string + format: uint64 + title: expected blocks per year + description: QueryParamsResponse is the response type for the Query/Params RPC method. diff --git a/docs/swagger.yml b/docs/swagger.yml new file mode 100644 index 0000000..656609e --- /dev/null +++ b/docs/swagger.yml @@ -0,0 +1,27029 @@ +swagger: '2.0' +info: + title: Juno network + version: v15 +consumes: + - application/json +produces: + - application/json +paths: + /cosmos/auth/v1beta1/accounts: + get: + summary: Accounts returns all the existing accounts + description: 'Since: cosmos-sdk 0.43' + operationId: Accounts_3VRJG + responses: + '200': + description: A successful response. + schema: + type: object + properties: + accounts: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: accounts are the existing accounts + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryAccountsResponse is the response type for the Query/Accounts + RPC method. + + + Since: cosmos-sdk 0.43 + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /cosmos/auth/v1beta1/accounts/{address}: + get: + summary: Account returns account details based on address. + operationId: Account_4751S + responses: + '200': + description: A successful response. + schema: + type: object + properties: + account: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: account defines the account of the corresponding address. + description: >- + QueryAccountResponse is the response type for the Query/Account + RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: address + description: address defines the address to query for. + in: path + required: true + type: string + tags: + - gRPC Gateway API + /cosmos/auth/v1beta1/module_accounts/{name}: + get: + summary: ModuleAccountByName returns the module account info by module name + operationId: ModuleAccountByName_GQLMA + responses: + '200': + description: A successful response. + schema: + type: object + properties: + account: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + QueryModuleAccountByNameResponse is the response type for the + Query/ModuleAccountByName RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: name + in: path + required: true + type: string + tags: + - gRPC Gateway API + /cosmos/auth/v1beta1/params: + get: + summary: Params queries all parameters. + operationId: Params_ZQGZI + responses: + '200': + description: A successful response. + schema: + type: object + properties: + params: + description: params defines the parameters of the module. + type: object + properties: + max_memo_characters: + type: string + format: uint64 + tx_sig_limit: + type: string + format: uint64 + tx_size_cost_per_byte: + type: string + format: uint64 + sig_verify_cost_ed25519: + type: string + format: uint64 + sig_verify_cost_secp256k1: + type: string + format: uint64 + description: >- + QueryParamsResponse is the response type for the Query/Params RPC + method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + /cosmos/bank/v1beta1/balances/{address}: + get: + summary: AllBalances queries the balance of all coins for a single account. + operationId: AllBalances_TCIFU + responses: + '200': + description: A successful response. + schema: + type: object + properties: + balances: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom + method + + signatures required by gogoproto. + description: balances is the balances of all the coins. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryAllBalancesResponse is the response type for the + Query/AllBalances RPC + + method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: address + description: address is the address to query balances for. + in: path + required: true + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /cosmos/bank/v1beta1/balances/{address}/by_denom: + get: + summary: Balance queries the balance of a single coin for a single account. + operationId: Balance_HBAVH + responses: + '200': + description: A successful response. + schema: + type: object + properties: + balance: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom + method + + signatures required by gogoproto. + description: >- + QueryBalanceResponse is the response type for the Query/Balance + RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: address + description: address is the address to query balances for. + in: path + required: true + type: string + - name: denom + description: denom is the coin denom to query balances for. + in: query + required: false + type: string + tags: + - gRPC Gateway API + /cosmos/bank/v1beta1/denoms_metadata: + get: + summary: >- + DenomsMetadata queries the client metadata for all registered coin + denominations. + operationId: DenomsMetadata_TKG35 + responses: + '200': + description: A successful response. + schema: + type: object + properties: + metadatas: + type: array + items: + type: object + properties: + description: + type: string + denom_units: + type: array + items: + type: object + properties: + denom: + type: string + description: >- + denom represents the string name of the given + denom unit (e.g uatom). + exponent: + type: integer + format: int64 + description: >- + 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). + aliases: + type: array + items: + type: string + title: >- + aliases is a list of string aliases for the given + denom + description: |- + DenomUnit represents a struct that describes a given + denomination unit of the basic token. + title: >- + denom_units represents the list of DenomUnit's for a + given coin + base: + type: string + description: >- + base represents the base denom (should be the DenomUnit + with exponent = 0). + display: + type: string + description: |- + display indicates the suggested denom that should be + displayed in clients. + name: + type: string + description: 'Since: cosmos-sdk 0.43' + title: 'name defines the name of the token (eg: Cosmos Atom)' + symbol: + type: string + description: >- + symbol is the token symbol usually shown on exchanges + (eg: ATOM). This can + + be the same as the display. + + + Since: cosmos-sdk 0.43 + description: |- + Metadata represents a struct that describes + a basic token. + description: >- + metadata provides the client information for all the + registered tokens. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryDenomsMetadataResponse is the response type for the + Query/DenomsMetadata RPC + + method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /cosmos/bank/v1beta1/denoms_metadata/{denom}: + get: + summary: DenomsMetadata queries the client metadata of a given coin denomination. + operationId: DenomMetadata_4OBWZ + responses: + '200': + description: A successful response. + schema: + type: object + properties: + metadata: + type: object + properties: + description: + type: string + denom_units: + type: array + items: + type: object + properties: + denom: + type: string + description: >- + denom represents the string name of the given denom + unit (e.g uatom). + exponent: + type: integer + format: int64 + description: >- + 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). + aliases: + type: array + items: + type: string + title: >- + aliases is a list of string aliases for the given + denom + description: |- + DenomUnit represents a struct that describes a given + denomination unit of the basic token. + title: >- + denom_units represents the list of DenomUnit's for a given + coin + base: + type: string + description: >- + base represents the base denom (should be the DenomUnit + with exponent = 0). + display: + type: string + description: |- + display indicates the suggested denom that should be + displayed in clients. + name: + type: string + description: 'Since: cosmos-sdk 0.43' + title: 'name defines the name of the token (eg: Cosmos Atom)' + symbol: + type: string + description: >- + symbol is the token symbol usually shown on exchanges (eg: + ATOM). This can + + be the same as the display. + + + Since: cosmos-sdk 0.43 + description: |- + Metadata represents a struct that describes + a basic token. + description: >- + QueryDenomMetadataResponse is the response type for the + Query/DenomMetadata RPC + + method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: denom + description: denom is the coin denom to query the metadata for. + in: path + required: true + type: string + tags: + - gRPC Gateway API + /cosmos/bank/v1beta1/params: + get: + summary: Params queries the parameters of x/bank module. + operationId: Params_BLVD9 + responses: + '200': + description: A successful response. + schema: + type: object + properties: + params: + type: object + properties: + send_enabled: + type: array + items: + type: object + properties: + denom: + type: string + enabled: + type: boolean + description: >- + SendEnabled maps coin denom to a send_enabled status + (whether a denom is + + sendable). + default_send_enabled: + type: boolean + description: Params defines the parameters for the bank module. + description: >- + QueryParamsResponse defines the response type for querying x/bank + parameters. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + /cosmos/bank/v1beta1/spendable_balances/{address}: + get: + summary: |- + SpendableBalances queries the spenable balance of all coins for a single + account. + operationId: SpendableBalances_5RIPQ + responses: + '200': + description: A successful response. + schema: + type: object + properties: + balances: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom + method + + signatures required by gogoproto. + description: balances is the spendable balances of all the coins. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QuerySpendableBalancesResponse defines the gRPC response structure + for querying + + an account's spendable balances. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: address + description: address is the address to query spendable balances for. + in: path + required: true + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /cosmos/bank/v1beta1/supply: + get: + summary: TotalSupply queries the total supply of all coins. + operationId: TotalSupply_E1EZ0 + responses: + '200': + description: A successful response. + schema: + type: object + properties: + supply: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom + method + + signatures required by gogoproto. + title: supply is the supply of the coins + pagination: + description: |- + pagination defines the pagination in the response. + + Since: cosmos-sdk 0.43 + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + title: >- + QueryTotalSupplyResponse is the response type for the + Query/TotalSupply RPC + + method + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /cosmos/bank/v1beta1/supply/{denom}: + get: + summary: SupplyOf queries the supply of a single coin. + operationId: SupplyOf_PWKWO + responses: + '200': + description: A successful response. + schema: + type: object + properties: + amount: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom + method + + signatures required by gogoproto. + description: >- + QuerySupplyOfResponse is the response type for the Query/SupplyOf + RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: denom + description: denom is the coin denom to query balances for. + in: path + required: true + type: string + tags: + - gRPC Gateway API + /cosmos/staking/v1beta1/delegations/{delegator_addr}: + get: + summary: >- + DelegatorDelegations queries all delegations of a given delegator + address. + operationId: DelegatorDelegations_JOZMT + responses: + '200': + description: A successful response. + schema: + type: object + properties: + delegation_responses: + type: array + items: + type: object + properties: + delegation: + type: object + properties: + delegator_address: + type: string + description: >- + delegator_address is the bech32-encoded address of + the delegator. + validator_address: + type: string + description: >- + validator_address is the bech32-encoded address of + the validator. + shares: + type: string + description: shares define the delegation shares received. + description: >- + Delegation represents the bond with tokens held by an + account. It is + + owned by one delegator, and is associated with the + voting power of one + + validator. + balance: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the + custom method + + signatures required by gogoproto. + description: >- + DelegationResponse is equivalent to Delegation except that + it contains a + + balance in addition to shares which is more suitable for + client responses. + description: >- + delegation_responses defines all the delegations' info of a + delegator. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + QueryDelegatorDelegationsResponse is response type for the + Query/DelegatorDelegations RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: delegator_addr + description: delegator_addr defines the delegator address to query for. + in: path + required: true + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /cosmos/staking/v1beta1/delegators/{delegator_addr}/redelegations: + get: + summary: Redelegations queries redelegations of given address. + operationId: Redelegations_14VGU + responses: + '200': + description: A successful response. + schema: + type: object + properties: + redelegation_responses: + type: array + items: + type: object + properties: + redelegation: + type: object + properties: + delegator_address: + type: string + description: >- + delegator_address is the bech32-encoded address of + the delegator. + validator_src_address: + type: string + description: >- + validator_src_address is the validator redelegation + source operator address. + validator_dst_address: + type: string + description: >- + validator_dst_address is the validator redelegation + destination operator address. + entries: + type: array + items: + type: object + properties: + creation_height: + type: string + format: int64 + description: >- + creation_height defines the height which the + redelegation took place. + completion_time: + type: string + format: date-time + description: >- + completion_time defines the unix time for + redelegation completion. + initial_balance: + type: string + description: >- + initial_balance defines the initial balance + when redelegation started. + shares_dst: + type: string + description: >- + shares_dst is the amount of + destination-validator shares created by + redelegation. + description: >- + RedelegationEntry defines a redelegation object + with relevant metadata. + description: entries are the redelegation entries. + description: >- + Redelegation contains the list of a particular + delegator's redelegating bonds + + from a particular source validator to a particular + destination validator. + entries: + type: array + items: + type: object + properties: + redelegation_entry: + type: object + properties: + creation_height: + type: string + format: int64 + description: >- + creation_height defines the height which the + redelegation took place. + completion_time: + type: string + format: date-time + description: >- + completion_time defines the unix time for + redelegation completion. + initial_balance: + type: string + description: >- + initial_balance defines the initial balance + when redelegation started. + shares_dst: + type: string + description: >- + shares_dst is the amount of + destination-validator shares created by + redelegation. + description: >- + RedelegationEntry defines a redelegation object + with relevant metadata. + balance: + type: string + description: >- + RedelegationEntryResponse is equivalent to a + RedelegationEntry except that it + + contains a balance in addition to shares which is more + suitable for client + + responses. + description: >- + RedelegationResponse is equivalent to a Redelegation except + that its entries + + contain a balance in addition to shares which is more + suitable for client + + responses. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryRedelegationsResponse is response type for the + Query/Redelegations RPC + + method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: delegator_addr + description: delegator_addr defines the delegator address to query for. + in: path + required: true + type: string + - name: src_validator_addr + description: src_validator_addr defines the validator address to redelegate from. + in: query + required: false + type: string + - name: dst_validator_addr + description: dst_validator_addr defines the validator address to redelegate to. + in: query + required: false + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /cosmos/staking/v1beta1/delegators/{delegator_addr}/unbonding_delegations: + get: + summary: >- + DelegatorUnbondingDelegations queries all unbonding delegations of a + given + + delegator address. + operationId: DelegatorUnbondingDelegations_E3804 + responses: + '200': + description: A successful response. + schema: + type: object + properties: + unbonding_responses: + type: array + items: + type: object + properties: + delegator_address: + type: string + description: >- + delegator_address is the bech32-encoded address of the + delegator. + validator_address: + type: string + description: >- + validator_address is the bech32-encoded address of the + validator. + entries: + type: array + items: + type: object + properties: + creation_height: + type: string + format: int64 + description: >- + creation_height is the height which the unbonding + took place. + completion_time: + type: string + format: date-time + description: >- + completion_time is the unix time for unbonding + completion. + initial_balance: + type: string + description: >- + initial_balance defines the tokens initially + scheduled to receive at completion. + balance: + type: string + description: >- + balance defines the tokens to receive at + completion. + description: >- + UnbondingDelegationEntry defines an unbonding object + with relevant metadata. + description: entries are the unbonding delegation entries. + description: >- + UnbondingDelegation stores all of a single delegator's + unbonding bonds + + for a single validator in an time-ordered list. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryUnbondingDelegatorDelegationsResponse is response type for + the + + Query/UnbondingDelegatorDelegations RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: delegator_addr + description: delegator_addr defines the delegator address to query for. + in: path + required: true + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /cosmos/staking/v1beta1/delegators/{delegator_addr}/validators: + get: + summary: |- + DelegatorValidators queries all validators info for given delegator + address. + operationId: DelegatorValidators_FFS5U + responses: + '200': + description: A successful response. + schema: + type: object + properties: + validators: + type: array + items: + type: object + properties: + operator_address: + type: string + description: >- + operator_address defines the address of the validator's + operator; bech encoded in JSON. + consensus_pubkey: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + consensus_pubkey is the consensus public key of the + validator, as a Protobuf Any. + jailed: + type: boolean + description: >- + jailed defined whether the validator has been jailed + from bonded status or not. + status: + description: >- + status is the validator status + (bonded/unbonding/unbonded). + type: string + enum: + - BOND_STATUS_UNSPECIFIED + - BOND_STATUS_UNBONDED + - BOND_STATUS_UNBONDING + - BOND_STATUS_BONDED + default: BOND_STATUS_UNSPECIFIED + tokens: + type: string + description: >- + tokens define the delegated tokens (incl. + self-delegation). + delegator_shares: + type: string + description: >- + delegator_shares defines total shares issued to a + validator's delegators. + description: + description: >- + description defines the description terms for the + validator. + type: object + properties: + moniker: + type: string + description: >- + moniker defines a human-readable name for the + validator. + identity: + type: string + description: >- + identity defines an optional identity signature (ex. + UPort or Keybase). + website: + type: string + description: website defines an optional website link. + security_contact: + type: string + description: >- + security_contact defines an optional email for + security contact. + details: + type: string + description: details define other optional details. + unbonding_height: + type: string + format: int64 + description: >- + unbonding_height defines, if unbonding, the height at + which this validator has begun unbonding. + unbonding_time: + type: string + format: date-time + description: >- + unbonding_time defines, if unbonding, the min time for + the validator to complete unbonding. + commission: + description: commission defines the commission parameters. + type: object + properties: + commission_rates: + description: >- + commission_rates defines the initial commission + rates to be used for creating a validator. + type: object + properties: + rate: + type: string + description: >- + rate is the commission rate charged to + delegators, as a fraction. + max_rate: + type: string + description: >- + max_rate defines the maximum commission rate + which validator can ever charge, as a fraction. + max_change_rate: + type: string + description: >- + max_change_rate defines the maximum daily + increase of the validator commission, as a + fraction. + update_time: + type: string + format: date-time + description: >- + update_time is the last time the commission rate was + changed. + min_self_delegation: + type: string + description: >- + min_self_delegation is the validator's self declared + minimum self delegation. + description: >- + Validator defines a validator, together with the total + amount of the + + Validator's bond shares and their exchange rate to coins. + Slashing results in + + a decrease in the exchange rate, allowing correct + calculation of future + + undelegations without iterating over delegators. When coins + are delegated to + + this validator, the validator is credited with a delegation + whose number of + + bond shares is based on the amount of coins delegated + divided by the current + + exchange rate. Voting power can be calculated as total + bonded shares + + multiplied by exchange rate. + description: validators defines the the validators' info of a delegator. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + QueryDelegatorValidatorsResponse is response type for the + Query/DelegatorValidators RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: delegator_addr + description: delegator_addr defines the delegator address to query for. + in: path + required: true + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /cosmos/staking/v1beta1/delegators/{delegator_addr}/validators/{validator_addr}: + get: + summary: |- + DelegatorValidator queries validator info for given delegator validator + pair. + operationId: DelegatorValidator_0SMKH + responses: + '200': + description: A successful response. + schema: + type: object + properties: + validator: + type: object + properties: + operator_address: + type: string + description: >- + operator_address defines the address of the validator's + operator; bech encoded in JSON. + consensus_pubkey: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + consensus_pubkey is the consensus public key of the + validator, as a Protobuf Any. + jailed: + type: boolean + description: >- + jailed defined whether the validator has been jailed from + bonded status or not. + status: + description: >- + status is the validator status + (bonded/unbonding/unbonded). + type: string + enum: + - BOND_STATUS_UNSPECIFIED + - BOND_STATUS_UNBONDED + - BOND_STATUS_UNBONDING + - BOND_STATUS_BONDED + default: BOND_STATUS_UNSPECIFIED + tokens: + type: string + description: >- + tokens define the delegated tokens (incl. + self-delegation). + delegator_shares: + type: string + description: >- + delegator_shares defines total shares issued to a + validator's delegators. + description: + description: >- + description defines the description terms for the + validator. + type: object + properties: + moniker: + type: string + description: >- + moniker defines a human-readable name for the + validator. + identity: + type: string + description: >- + identity defines an optional identity signature (ex. + UPort or Keybase). + website: + type: string + description: website defines an optional website link. + security_contact: + type: string + description: >- + security_contact defines an optional email for + security contact. + details: + type: string + description: details define other optional details. + unbonding_height: + type: string + format: int64 + description: >- + unbonding_height defines, if unbonding, the height at + which this validator has begun unbonding. + unbonding_time: + type: string + format: date-time + description: >- + unbonding_time defines, if unbonding, the min time for the + validator to complete unbonding. + commission: + description: commission defines the commission parameters. + type: object + properties: + commission_rates: + description: >- + commission_rates defines the initial commission rates + to be used for creating a validator. + type: object + properties: + rate: + type: string + description: >- + rate is the commission rate charged to delegators, + as a fraction. + max_rate: + type: string + description: >- + max_rate defines the maximum commission rate which + validator can ever charge, as a fraction. + max_change_rate: + type: string + description: >- + max_change_rate defines the maximum daily increase + of the validator commission, as a fraction. + update_time: + type: string + format: date-time + description: >- + update_time is the last time the commission rate was + changed. + min_self_delegation: + type: string + description: >- + min_self_delegation is the validator's self declared + minimum self delegation. + description: >- + Validator defines a validator, together with the total amount + of the + + Validator's bond shares and their exchange rate to coins. + Slashing results in + + a decrease in the exchange rate, allowing correct calculation + of future + + undelegations without iterating over delegators. When coins + are delegated to + + this validator, the validator is credited with a delegation + whose number of + + bond shares is based on the amount of coins delegated divided + by the current + + exchange rate. Voting power can be calculated as total bonded + shares + + multiplied by exchange rate. + description: |- + QueryDelegatorValidatorResponse response type for the + Query/DelegatorValidator RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: delegator_addr + description: delegator_addr defines the delegator address to query for. + in: path + required: true + type: string + - name: validator_addr + description: validator_addr defines the validator address to query for. + in: path + required: true + type: string + tags: + - gRPC Gateway API + /cosmos/staking/v1beta1/historical_info/{height}: + get: + summary: HistoricalInfo queries the historical info for given height. + operationId: HistoricalInfo_O3FQL + responses: + '200': + description: A successful response. + schema: + type: object + properties: + hist: + description: hist defines the historical info at the given height. + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for processing + a block in the blockchain, + + including all blockchain data structures and the rules + of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + valset: + type: array + items: + type: object + properties: + operator_address: + type: string + description: >- + operator_address defines the address of the + validator's operator; bech encoded in JSON. + consensus_pubkey: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + consensus_pubkey is the consensus public key of the + validator, as a Protobuf Any. + jailed: + type: boolean + description: >- + jailed defined whether the validator has been jailed + from bonded status or not. + status: + description: >- + status is the validator status + (bonded/unbonding/unbonded). + type: string + enum: + - BOND_STATUS_UNSPECIFIED + - BOND_STATUS_UNBONDED + - BOND_STATUS_UNBONDING + - BOND_STATUS_BONDED + default: BOND_STATUS_UNSPECIFIED + tokens: + type: string + description: >- + tokens define the delegated tokens (incl. + self-delegation). + delegator_shares: + type: string + description: >- + delegator_shares defines total shares issued to a + validator's delegators. + description: + description: >- + description defines the description terms for the + validator. + type: object + properties: + moniker: + type: string + description: >- + moniker defines a human-readable name for the + validator. + identity: + type: string + description: >- + identity defines an optional identity signature + (ex. UPort or Keybase). + website: + type: string + description: website defines an optional website link. + security_contact: + type: string + description: >- + security_contact defines an optional email for + security contact. + details: + type: string + description: details define other optional details. + unbonding_height: + type: string + format: int64 + description: >- + unbonding_height defines, if unbonding, the height + at which this validator has begun unbonding. + unbonding_time: + type: string + format: date-time + description: >- + unbonding_time defines, if unbonding, the min time + for the validator to complete unbonding. + commission: + description: commission defines the commission parameters. + type: object + properties: + commission_rates: + description: >- + commission_rates defines the initial commission + rates to be used for creating a validator. + type: object + properties: + rate: + type: string + description: >- + rate is the commission rate charged to + delegators, as a fraction. + max_rate: + type: string + description: >- + max_rate defines the maximum commission rate + which validator can ever charge, as a + fraction. + max_change_rate: + type: string + description: >- + max_change_rate defines the maximum daily + increase of the validator commission, as a + fraction. + update_time: + type: string + format: date-time + description: >- + update_time is the last time the commission rate + was changed. + min_self_delegation: + type: string + description: >- + min_self_delegation is the validator's self declared + minimum self delegation. + description: >- + Validator defines a validator, together with the total + amount of the + + Validator's bond shares and their exchange rate to + coins. Slashing results in + + a decrease in the exchange rate, allowing correct + calculation of future + + undelegations without iterating over delegators. When + coins are delegated to + + this validator, the validator is credited with a + delegation whose number of + + bond shares is based on the amount of coins delegated + divided by the current + + exchange rate. Voting power can be calculated as total + bonded shares + + multiplied by exchange rate. + description: >- + QueryHistoricalInfoResponse is response type for the + Query/HistoricalInfo RPC + + method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: height + description: height defines at which height to query the historical info. + in: path + required: true + type: string + format: int64 + tags: + - gRPC Gateway API + /cosmos/staking/v1beta1/params: + get: + summary: Parameters queries the staking parameters. + operationId: Params_TU2U5 + responses: + '200': + description: A successful response. + schema: + type: object + properties: + params: + description: params holds all the parameters of this module. + type: object + properties: + unbonding_time: + type: string + description: unbonding_time is the time duration of unbonding. + max_validators: + type: integer + format: int64 + description: max_validators is the maximum number of validators. + max_entries: + type: integer + format: int64 + description: >- + max_entries is the max entries for either unbonding + delegation or redelegation (per pair/trio). + historical_entries: + type: integer + format: int64 + description: >- + historical_entries is the number of historical entries to + persist. + bond_denom: + type: string + description: bond_denom defines the bondable coin denomination. + description: >- + QueryParamsResponse is response type for the Query/Params RPC + method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + /cosmos/staking/v1beta1/pool: + get: + summary: Pool queries the pool info. + operationId: Pool_FDYA0 + responses: + '200': + description: A successful response. + schema: + type: object + properties: + pool: + description: pool defines the pool info. + type: object + properties: + not_bonded_tokens: + type: string + bonded_tokens: + type: string + description: QueryPoolResponse is response type for the Query/Pool RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + /cosmos/staking/v1beta1/validators: + get: + summary: Validators queries all validators that match the given status. + operationId: Validators_O6IYI + responses: + '200': + description: A successful response. + schema: + type: object + properties: + validators: + type: array + items: + type: object + properties: + operator_address: + type: string + description: >- + operator_address defines the address of the validator's + operator; bech encoded in JSON. + consensus_pubkey: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + consensus_pubkey is the consensus public key of the + validator, as a Protobuf Any. + jailed: + type: boolean + description: >- + jailed defined whether the validator has been jailed + from bonded status or not. + status: + description: >- + status is the validator status + (bonded/unbonding/unbonded). + type: string + enum: + - BOND_STATUS_UNSPECIFIED + - BOND_STATUS_UNBONDED + - BOND_STATUS_UNBONDING + - BOND_STATUS_BONDED + default: BOND_STATUS_UNSPECIFIED + tokens: + type: string + description: >- + tokens define the delegated tokens (incl. + self-delegation). + delegator_shares: + type: string + description: >- + delegator_shares defines total shares issued to a + validator's delegators. + description: + description: >- + description defines the description terms for the + validator. + type: object + properties: + moniker: + type: string + description: >- + moniker defines a human-readable name for the + validator. + identity: + type: string + description: >- + identity defines an optional identity signature (ex. + UPort or Keybase). + website: + type: string + description: website defines an optional website link. + security_contact: + type: string + description: >- + security_contact defines an optional email for + security contact. + details: + type: string + description: details define other optional details. + unbonding_height: + type: string + format: int64 + description: >- + unbonding_height defines, if unbonding, the height at + which this validator has begun unbonding. + unbonding_time: + type: string + format: date-time + description: >- + unbonding_time defines, if unbonding, the min time for + the validator to complete unbonding. + commission: + description: commission defines the commission parameters. + type: object + properties: + commission_rates: + description: >- + commission_rates defines the initial commission + rates to be used for creating a validator. + type: object + properties: + rate: + type: string + description: >- + rate is the commission rate charged to + delegators, as a fraction. + max_rate: + type: string + description: >- + max_rate defines the maximum commission rate + which validator can ever charge, as a fraction. + max_change_rate: + type: string + description: >- + max_change_rate defines the maximum daily + increase of the validator commission, as a + fraction. + update_time: + type: string + format: date-time + description: >- + update_time is the last time the commission rate was + changed. + min_self_delegation: + type: string + description: >- + min_self_delegation is the validator's self declared + minimum self delegation. + description: >- + Validator defines a validator, together with the total + amount of the + + Validator's bond shares and their exchange rate to coins. + Slashing results in + + a decrease in the exchange rate, allowing correct + calculation of future + + undelegations without iterating over delegators. When coins + are delegated to + + this validator, the validator is credited with a delegation + whose number of + + bond shares is based on the amount of coins delegated + divided by the current + + exchange rate. Voting power can be calculated as total + bonded shares + + multiplied by exchange rate. + description: validators contains all the queried validators. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + title: >- + QueryValidatorsResponse is response type for the Query/Validators + RPC method + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: status + description: status enables to query for validators matching a given status. + in: query + required: false + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /cosmos/staking/v1beta1/validators/{validator_addr}: + get: + summary: Validator queries validator info for given validator address. + operationId: Validator_R6NYA + responses: + '200': + description: A successful response. + schema: + type: object + properties: + validator: + type: object + properties: + operator_address: + type: string + description: >- + operator_address defines the address of the validator's + operator; bech encoded in JSON. + consensus_pubkey: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + consensus_pubkey is the consensus public key of the + validator, as a Protobuf Any. + jailed: + type: boolean + description: >- + jailed defined whether the validator has been jailed from + bonded status or not. + status: + description: >- + status is the validator status + (bonded/unbonding/unbonded). + type: string + enum: + - BOND_STATUS_UNSPECIFIED + - BOND_STATUS_UNBONDED + - BOND_STATUS_UNBONDING + - BOND_STATUS_BONDED + default: BOND_STATUS_UNSPECIFIED + tokens: + type: string + description: >- + tokens define the delegated tokens (incl. + self-delegation). + delegator_shares: + type: string + description: >- + delegator_shares defines total shares issued to a + validator's delegators. + description: + description: >- + description defines the description terms for the + validator. + type: object + properties: + moniker: + type: string + description: >- + moniker defines a human-readable name for the + validator. + identity: + type: string + description: >- + identity defines an optional identity signature (ex. + UPort or Keybase). + website: + type: string + description: website defines an optional website link. + security_contact: + type: string + description: >- + security_contact defines an optional email for + security contact. + details: + type: string + description: details define other optional details. + unbonding_height: + type: string + format: int64 + description: >- + unbonding_height defines, if unbonding, the height at + which this validator has begun unbonding. + unbonding_time: + type: string + format: date-time + description: >- + unbonding_time defines, if unbonding, the min time for the + validator to complete unbonding. + commission: + description: commission defines the commission parameters. + type: object + properties: + commission_rates: + description: >- + commission_rates defines the initial commission rates + to be used for creating a validator. + type: object + properties: + rate: + type: string + description: >- + rate is the commission rate charged to delegators, + as a fraction. + max_rate: + type: string + description: >- + max_rate defines the maximum commission rate which + validator can ever charge, as a fraction. + max_change_rate: + type: string + description: >- + max_change_rate defines the maximum daily increase + of the validator commission, as a fraction. + update_time: + type: string + format: date-time + description: >- + update_time is the last time the commission rate was + changed. + min_self_delegation: + type: string + description: >- + min_self_delegation is the validator's self declared + minimum self delegation. + description: >- + Validator defines a validator, together with the total amount + of the + + Validator's bond shares and their exchange rate to coins. + Slashing results in + + a decrease in the exchange rate, allowing correct calculation + of future + + undelegations without iterating over delegators. When coins + are delegated to + + this validator, the validator is credited with a delegation + whose number of + + bond shares is based on the amount of coins delegated divided + by the current + + exchange rate. Voting power can be calculated as total bonded + shares + + multiplied by exchange rate. + title: >- + QueryValidatorResponse is response type for the Query/Validator + RPC method + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: validator_addr + description: validator_addr defines the validator address to query for. + in: path + required: true + type: string + tags: + - gRPC Gateway API + /cosmos/staking/v1beta1/validators/{validator_addr}/delegations: + get: + summary: ValidatorDelegations queries delegate info for given validator. + operationId: ValidatorDelegations_I8DQT + responses: + '200': + description: A successful response. + schema: + type: object + properties: + delegation_responses: + type: array + items: + type: object + properties: + delegation: + type: object + properties: + delegator_address: + type: string + description: >- + delegator_address is the bech32-encoded address of + the delegator. + validator_address: + type: string + description: >- + validator_address is the bech32-encoded address of + the validator. + shares: + type: string + description: shares define the delegation shares received. + description: >- + Delegation represents the bond with tokens held by an + account. It is + + owned by one delegator, and is associated with the + voting power of one + + validator. + balance: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the + custom method + + signatures required by gogoproto. + description: >- + DelegationResponse is equivalent to Delegation except that + it contains a + + balance in addition to shares which is more suitable for + client responses. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + title: |- + QueryValidatorDelegationsResponse is response type for the + Query/ValidatorDelegations RPC method + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: validator_addr + description: validator_addr defines the validator address to query for. + in: path + required: true + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /cosmos/staking/v1beta1/validators/{validator_addr}/delegations/{delegator_addr}: + get: + summary: Delegation queries delegate info for given validator delegator pair. + operationId: Delegation_SRG3Q + responses: + '200': + description: A successful response. + schema: + type: object + properties: + delegation_response: + type: object + properties: + delegation: + type: object + properties: + delegator_address: + type: string + description: >- + delegator_address is the bech32-encoded address of the + delegator. + validator_address: + type: string + description: >- + validator_address is the bech32-encoded address of the + validator. + shares: + type: string + description: shares define the delegation shares received. + description: >- + Delegation represents the bond with tokens held by an + account. It is + + owned by one delegator, and is associated with the voting + power of one + + validator. + balance: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the + custom method + + signatures required by gogoproto. + description: >- + DelegationResponse is equivalent to Delegation except that it + contains a + + balance in addition to shares which is more suitable for + client responses. + description: >- + QueryDelegationResponse is response type for the Query/Delegation + RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: validator_addr + description: validator_addr defines the validator address to query for. + in: path + required: true + type: string + - name: delegator_addr + description: delegator_addr defines the delegator address to query for. + in: path + required: true + type: string + tags: + - gRPC Gateway API + /cosmos/staking/v1beta1/validators/{validator_addr}/delegations/{delegator_addr}/unbonding_delegation: + get: + summary: |- + UnbondingDelegation queries unbonding info for given validator delegator + pair. + operationId: UnbondingDelegation_TWCOS + responses: + '200': + description: A successful response. + schema: + type: object + properties: + unbond: + type: object + properties: + delegator_address: + type: string + description: >- + delegator_address is the bech32-encoded address of the + delegator. + validator_address: + type: string + description: >- + validator_address is the bech32-encoded address of the + validator. + entries: + type: array + items: + type: object + properties: + creation_height: + type: string + format: int64 + description: >- + creation_height is the height which the unbonding + took place. + completion_time: + type: string + format: date-time + description: >- + completion_time is the unix time for unbonding + completion. + initial_balance: + type: string + description: >- + initial_balance defines the tokens initially + scheduled to receive at completion. + balance: + type: string + description: balance defines the tokens to receive at completion. + description: >- + UnbondingDelegationEntry defines an unbonding object + with relevant metadata. + description: entries are the unbonding delegation entries. + description: >- + UnbondingDelegation stores all of a single delegator's + unbonding bonds + + for a single validator in an time-ordered list. + description: >- + QueryDelegationResponse is response type for the + Query/UnbondingDelegation + + RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: validator_addr + description: validator_addr defines the validator address to query for. + in: path + required: true + type: string + - name: delegator_addr + description: delegator_addr defines the delegator address to query for. + in: path + required: true + type: string + tags: + - gRPC Gateway API + /cosmos/staking/v1beta1/validators/{validator_addr}/unbonding_delegations: + get: + summary: >- + ValidatorUnbondingDelegations queries unbonding delegations of a + validator. + operationId: ValidatorUnbondingDelegations_94HKV + responses: + '200': + description: A successful response. + schema: + type: object + properties: + unbonding_responses: + type: array + items: + type: object + properties: + delegator_address: + type: string + description: >- + delegator_address is the bech32-encoded address of the + delegator. + validator_address: + type: string + description: >- + validator_address is the bech32-encoded address of the + validator. + entries: + type: array + items: + type: object + properties: + creation_height: + type: string + format: int64 + description: >- + creation_height is the height which the unbonding + took place. + completion_time: + type: string + format: date-time + description: >- + completion_time is the unix time for unbonding + completion. + initial_balance: + type: string + description: >- + initial_balance defines the tokens initially + scheduled to receive at completion. + balance: + type: string + description: >- + balance defines the tokens to receive at + completion. + description: >- + UnbondingDelegationEntry defines an unbonding object + with relevant metadata. + description: entries are the unbonding delegation entries. + description: >- + UnbondingDelegation stores all of a single delegator's + unbonding bonds + + for a single validator in an time-ordered list. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryValidatorUnbondingDelegationsResponse is response type for + the + + Query/ValidatorUnbondingDelegations RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: validator_addr + description: validator_addr defines the validator address to query for. + in: path + required: true + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /cosmos/base/tendermint/v1beta1/blocks/latest: + get: + summary: GetLatestBlock returns the latest block. + operationId: GetLatestBlock_4NXGP + responses: + '200': + description: A successful response. + schema: + type: object + properties: + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + block: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for processing + a block in the blockchain, + + including all blockchain data structures and the rules + of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + data: + type: object + properties: + txs: + type: array + items: + type: string + format: byte + description: >- + Txs that will be applied by state @ block.Height+1. + + NOTE: not all txs here are valid. We're just agreeing + on the order first. + + This means that block.AppHash does not include these + txs. + title: >- + Data contains the set of transactions included in the + block + evidence: + type: object + properties: + evidence: + type: array + items: + type: object + properties: + duplicate_vote_evidence: + type: object + properties: + vote_a: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: >- + SignedMsgType is a type of signed + message in the consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or + commit vote from validators for + + consensus. + vote_b: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: >- + SignedMsgType is a type of signed + message in the consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or + commit vote from validators for + + consensus. + total_voting_power: + type: string + format: int64 + validator_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: >- + DuplicateVoteEvidence contains evidence of a + validator signed two conflicting votes. + light_client_attack_evidence: + type: object + properties: + conflicting_block: + type: object + properties: + signed_header: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules + for processing a block in the + blockchain, + + including all blockchain data structures + and the rules of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: >- + hashes from the app output from the prev + block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: >- + Header defines the structure of a block + header. + commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: >- + BlockIdFlag indicates which BlcokID the + signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: >- + CommitSig is a part of the Vote included + in a Commit. + description: >- + Commit contains the evidence that a + block was committed by a set of + validators. + validator_set: + type: object + properties: + validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: >- + PublicKey defines the keys available for + use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + proposer: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: >- + PublicKey defines the keys available for + use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + common_height: + type: string + format: int64 + byzantine_validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: >- + PublicKey defines the keys available for + use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: >- + LightClientAttackEvidence contains evidence of a + set of validators attempting to mislead a light + client. + last_commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: >- + BlockIdFlag indicates which BlcokID the + signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: >- + CommitSig is a part of the Vote included in a + Commit. + description: >- + Commit contains the evidence that a block was committed by + a set of validators. + description: >- + GetLatestBlockResponse is the response type for the + Query/GetLatestBlock RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + /cosmos/base/tendermint/v1beta1/blocks/{height}: + get: + summary: GetBlockByHeight queries block for given height. + operationId: GetBlockByHeight_HXFY4 + responses: + '200': + description: A successful response. + schema: + type: object + properties: + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + block: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for processing + a block in the blockchain, + + including all blockchain data structures and the rules + of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + data: + type: object + properties: + txs: + type: array + items: + type: string + format: byte + description: >- + Txs that will be applied by state @ block.Height+1. + + NOTE: not all txs here are valid. We're just agreeing + on the order first. + + This means that block.AppHash does not include these + txs. + title: >- + Data contains the set of transactions included in the + block + evidence: + type: object + properties: + evidence: + type: array + items: + type: object + properties: + duplicate_vote_evidence: + type: object + properties: + vote_a: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: >- + SignedMsgType is a type of signed + message in the consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or + commit vote from validators for + + consensus. + vote_b: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: >- + SignedMsgType is a type of signed + message in the consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or + commit vote from validators for + + consensus. + total_voting_power: + type: string + format: int64 + validator_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: >- + DuplicateVoteEvidence contains evidence of a + validator signed two conflicting votes. + light_client_attack_evidence: + type: object + properties: + conflicting_block: + type: object + properties: + signed_header: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules + for processing a block in the + blockchain, + + including all blockchain data structures + and the rules of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: >- + hashes from the app output from the prev + block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: >- + Header defines the structure of a block + header. + commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: >- + BlockIdFlag indicates which BlcokID the + signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: >- + CommitSig is a part of the Vote included + in a Commit. + description: >- + Commit contains the evidence that a + block was committed by a set of + validators. + validator_set: + type: object + properties: + validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: >- + PublicKey defines the keys available for + use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + proposer: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: >- + PublicKey defines the keys available for + use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + common_height: + type: string + format: int64 + byzantine_validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: >- + PublicKey defines the keys available for + use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: >- + LightClientAttackEvidence contains evidence of a + set of validators attempting to mislead a light + client. + last_commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: >- + BlockIdFlag indicates which BlcokID the + signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: >- + CommitSig is a part of the Vote included in a + Commit. + description: >- + Commit contains the evidence that a block was committed by + a set of validators. + description: >- + GetBlockByHeightResponse is the response type for the + Query/GetBlockByHeight RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: height + in: path + required: true + type: string + format: int64 + tags: + - gRPC Gateway API + /cosmos/base/tendermint/v1beta1/node_info: + get: + summary: GetNodeInfo queries the current node info. + operationId: GetNodeInfo_39H2U + responses: + '200': + description: A successful response. + schema: + type: object + properties: + default_node_info: + type: object + properties: + protocol_version: + type: object + properties: + p2p: + type: string + format: uint64 + block: + type: string + format: uint64 + app: + type: string + format: uint64 + default_node_id: + type: string + listen_addr: + type: string + network: + type: string + version: + type: string + channels: + type: string + format: byte + moniker: + type: string + other: + type: object + properties: + tx_index: + type: string + rpc_address: + type: string + application_version: + type: object + properties: + name: + type: string + app_name: + type: string + version: + type: string + git_commit: + type: string + build_tags: + type: string + go_version: + type: string + build_deps: + type: array + items: + type: object + properties: + path: + type: string + title: module path + version: + type: string + title: module version + sum: + type: string + title: checksum + title: Module is the type for VersionInfo + cosmos_sdk_version: + type: string + title: 'Since: cosmos-sdk 0.43' + description: VersionInfo is the type for the GetNodeInfoResponse message. + description: >- + GetNodeInfoResponse is the request type for the Query/GetNodeInfo + RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + /cosmos/base/tendermint/v1beta1/syncing: + get: + summary: GetSyncing queries node syncing. + operationId: GetSyncing_55ZJD + responses: + '200': + description: A successful response. + schema: + type: object + properties: + syncing: + type: boolean + description: >- + GetSyncingResponse is the response type for the Query/GetSyncing + RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + /cosmos/base/tendermint/v1beta1/validatorsets/latest: + get: + summary: GetLatestValidatorSet queries latest validator-set. + operationId: GetLatestValidatorSet_WCLGL + responses: + '200': + description: A successful response. + schema: + type: object + properties: + block_height: + type: string + format: int64 + validators: + type: array + items: + type: object + properties: + address: + type: string + pub_key: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + description: Validator is the type for the validator-set. + pagination: + description: pagination defines an pagination for the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + GetLatestValidatorSetResponse is the response type for the + Query/GetValidatorSetByHeight RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /cosmos/base/tendermint/v1beta1/validatorsets/{height}: + get: + summary: GetValidatorSetByHeight queries validator-set at a given height. + operationId: GetValidatorSetByHeight_ODLV8 + responses: + '200': + description: A successful response. + schema: + type: object + properties: + block_height: + type: string + format: int64 + validators: + type: array + items: + type: object + properties: + address: + type: string + pub_key: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + description: Validator is the type for the validator-set. + pagination: + description: pagination defines an pagination for the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + GetValidatorSetByHeightResponse is the response type for the + Query/GetValidatorSetByHeight RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: height + in: path + required: true + type: string + format: int64 + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /ibc/apps/router/v1/params: + get: + summary: Params queries all parameters of the router module. + operationId: Params_TM71K + responses: + '200': + description: A successful response. + schema: + type: object + properties: + params: + description: params defines the parameters of the module. + type: object + properties: + fee_percentage: + type: string + description: >- + QueryParamsResponse is the response type for the Query/Params RPC + method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + /osmosis/tokenfactory/v1beta1/denoms/{denom}/authority_metadata: + get: + summary: |- + DenomAuthorityMetadata defines a gRPC query method for fetching + DenomAuthorityMetadata for a particular denom. + operationId: DenomAuthorityMetadata_JQDYU + responses: + '200': + description: A successful response. + schema: + type: object + properties: + authority_metadata: + type: object + properties: + admin: + type: string + title: Can be empty for no admin, or a valid osmosis address + description: >- + 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. + description: >- + QueryDenomAuthorityMetadataResponse defines the response structure + for the + + DenomAuthorityMetadata gRPC query. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: denom + in: path + required: true + type: string + tags: + - gRPC Gateway API + /osmosis/tokenfactory/v1beta1/denoms_from_creator/{creator}: + get: + summary: |- + DenomsFromCreator defines a gRPC query method for fetching all + denominations created by a specific admin/creator. + operationId: DenomsFromCreator_7DSNJ + responses: + '200': + description: A successful response. + schema: + type: object + properties: + denoms: + type: array + items: + type: string + description: >- + QueryDenomsFromCreatorRequest defines the response structure for + the + + DenomsFromCreator gRPC query. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: creator + in: path + required: true + type: string + tags: + - gRPC Gateway API + /osmosis/tokenfactory/v1beta1/params: + get: + summary: >- + Params defines a gRPC query method that returns the tokenfactory + module's + + parameters. + operationId: Params_QYV5K + responses: + '200': + description: A successful response. + schema: + type: object + properties: + params: + description: params defines the parameters of the module. + type: object + properties: + denom_creation_fee: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the + custom method + + signatures required by gogoproto. + denom_creation_gas_consume: + type: string + format: uint64 + title: >- + if denom_creation_fee is an empty array, then this field + is used to add more gas consumption + + to the base cost. + + https://github.com/CosmWasm/token-factory/issues/11 + description: >- + QueryParamsResponse is the response type for the Query/Params RPC + method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + /cosmos/distribution/v1beta1/community_pool: + get: + summary: CommunityPool queries the community pool coins. + operationId: CommunityPool_YZRL4 + responses: + '200': + description: A successful response. + schema: + type: object + properties: + pool: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + DecCoin defines a token with a denomination and a decimal + amount. + + + NOTE: The amount field is an Dec which implements the custom + method + + signatures required by gogoproto. + description: pool defines community pool's coins. + description: >- + QueryCommunityPoolResponse is the response type for the + Query/CommunityPool + + RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + /cosmos/distribution/v1beta1/delegators/{delegator_address}/rewards: + get: + summary: |- + DelegationTotalRewards queries the total rewards accrued by a each + validator. + operationId: DelegationTotalRewards_YOCPA + responses: + '200': + description: A successful response. + schema: + type: object + properties: + rewards: + type: array + items: + type: object + properties: + validator_address: + type: string + reward: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + DecCoin defines a token with a denomination and a + decimal amount. + + + NOTE: The amount field is an Dec which implements the + custom method + + signatures required by gogoproto. + description: |- + DelegationDelegatorReward represents the properties + of a delegator's delegation reward. + description: rewards defines all the rewards accrued by a delegator. + total: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + DecCoin defines a token with a denomination and a decimal + amount. + + + NOTE: The amount field is an Dec which implements the custom + method + + signatures required by gogoproto. + description: total defines the sum of all the rewards. + description: |- + QueryDelegationTotalRewardsResponse is the response type for the + Query/DelegationTotalRewards RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: delegator_address + description: delegator_address defines the delegator address to query for. + in: path + required: true + type: string + tags: + - gRPC Gateway API + /cosmos/distribution/v1beta1/delegators/{delegator_address}/rewards/{validator_address}: + get: + summary: DelegationRewards queries the total rewards accrued by a delegation. + operationId: DelegationRewards_I3GH0 + responses: + '200': + description: A successful response. + schema: + type: object + properties: + rewards: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + DecCoin defines a token with a denomination and a decimal + amount. + + + NOTE: The amount field is an Dec which implements the custom + method + + signatures required by gogoproto. + description: rewards defines the rewards accrued by a delegation. + description: |- + QueryDelegationRewardsResponse is the response type for the + Query/DelegationRewards RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: delegator_address + description: delegator_address defines the delegator address to query for. + in: path + required: true + type: string + - name: validator_address + description: validator_address defines the validator address to query for. + in: path + required: true + type: string + tags: + - gRPC Gateway API + /cosmos/distribution/v1beta1/delegators/{delegator_address}/validators: + get: + summary: DelegatorValidators queries the validators of a delegator. + operationId: DelegatorValidators_07SCO + responses: + '200': + description: A successful response. + schema: + type: object + properties: + validators: + type: array + items: + type: string + description: >- + validators defines the validators a delegator is delegating + for. + description: |- + QueryDelegatorValidatorsResponse is the response type for the + Query/DelegatorValidators RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: delegator_address + description: delegator_address defines the delegator address to query for. + in: path + required: true + type: string + tags: + - gRPC Gateway API + /cosmos/distribution/v1beta1/delegators/{delegator_address}/withdraw_address: + get: + summary: DelegatorWithdrawAddress queries withdraw address of a delegator. + operationId: DelegatorWithdrawAddress_BFZZ2 + responses: + '200': + description: A successful response. + schema: + type: object + properties: + withdraw_address: + type: string + description: withdraw_address defines the delegator address to query for. + description: |- + QueryDelegatorWithdrawAddressResponse is the response type for the + Query/DelegatorWithdrawAddress RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: delegator_address + description: delegator_address defines the delegator address to query for. + in: path + required: true + type: string + tags: + - gRPC Gateway API + /cosmos/distribution/v1beta1/params: + get: + summary: Params queries params of the distribution module. + operationId: Params_KNUQO + responses: + '200': + description: A successful response. + schema: + type: object + properties: + params: + description: params defines the parameters of the module. + type: object + properties: + community_tax: + type: string + base_proposer_reward: + type: string + bonus_proposer_reward: + type: string + withdraw_addr_enabled: + type: boolean + description: >- + QueryParamsResponse is the response type for the Query/Params RPC + method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + /cosmos/distribution/v1beta1/validators/{validator_address}/commission: + get: + summary: ValidatorCommission queries accumulated commission for a validator. + operationId: ValidatorCommission_YRRRF + responses: + '200': + description: A successful response. + schema: + type: object + properties: + commission: + description: commission defines the commision the validator received. + type: object + properties: + commission: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + DecCoin defines a token with a denomination and a + decimal amount. + + + NOTE: The amount field is an Dec which implements the + custom method + + signatures required by gogoproto. + title: |- + QueryValidatorCommissionResponse is the response type for the + Query/ValidatorCommission RPC method + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: validator_address + description: validator_address defines the validator address to query for. + in: path + required: true + type: string + tags: + - gRPC Gateway API + /cosmos/distribution/v1beta1/validators/{validator_address}/outstanding_rewards: + get: + summary: ValidatorOutstandingRewards queries rewards of a validator address. + operationId: ValidatorOutstandingRewards_JG6R4 + responses: + '200': + description: A successful response. + schema: + type: object + properties: + rewards: + type: object + properties: + rewards: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + DecCoin defines a token with a denomination and a + decimal amount. + + + NOTE: The amount field is an Dec which implements the + custom method + + signatures required by gogoproto. + description: >- + ValidatorOutstandingRewards represents outstanding + (un-withdrawn) rewards + + for a validator inexpensive to track, allows simple sanity + checks. + description: >- + QueryValidatorOutstandingRewardsResponse is the response type for + the + + Query/ValidatorOutstandingRewards RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: validator_address + description: validator_address defines the validator address to query for. + in: path + required: true + type: string + tags: + - gRPC Gateway API + /cosmos/distribution/v1beta1/validators/{validator_address}/slashes: + get: + summary: ValidatorSlashes queries slash events of a validator. + operationId: ValidatorSlashes_O4Z2G + responses: + '200': + description: A successful response. + schema: + type: object + properties: + slashes: + type: array + items: + type: object + properties: + validator_period: + type: string + format: uint64 + fraction: + type: string + description: >- + ValidatorSlashEvent represents a validator slash event. + + Height is implicit within the store key. + + This is needed to calculate appropriate amount of staking + tokens + + for delegations which are withdrawn after a slash has + occurred. + description: slashes defines the slashes the validator received. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + QueryValidatorSlashesResponse is the response type for the + Query/ValidatorSlashes RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: validator_address + description: validator_address defines the validator address to query for. + in: path + required: true + type: string + - name: starting_height + description: >- + starting_height defines the optional starting height to query the + slashes. + in: query + required: false + type: string + format: uint64 + - name: ending_height + description: >- + starting_height defines the optional ending height to query the + slashes. + in: query + required: false + type: string + format: uint64 + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /cosmos/tx/v1beta1/simulate: + post: + summary: Simulate simulates executing a transaction for estimating gas usage. + operationId: Simulate_OQQOZ + responses: + '200': + description: A successful response. + schema: + type: object + properties: + gas_info: + description: gas_info is the information about gas used in the simulation. + type: object + properties: + gas_wanted: + type: string + format: uint64 + description: >- + GasWanted is the maximum units of work we allow this tx to + perform. + gas_used: + type: string + format: uint64 + description: GasUsed is the amount of gas actually consumed. + result: + description: result is the result of the simulation. + type: object + properties: + data: + type: string + format: byte + description: >- + Data is any data returned from message or handler + execution. It MUST be + + length prefixed in order to separate data from multiple + message executions. + log: + type: string + description: >- + Log contains the log information from message or handler + execution. + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + format: byte + value: + type: string + format: byte + index: + type: boolean + description: >- + EventAttribute is a single key-value pair, + associated with an event. + description: >- + Event allows application developers to attach additional + information to + + ResponseBeginBlock, ResponseEndBlock, ResponseCheckTx + and ResponseDeliverTx. + + Later, transactions may be queried using these events. + description: >- + Events contains a slice of Event objects that were emitted + during message + + or handler execution. + description: |- + SimulateResponse is the response type for the + Service.SimulateRPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: body + in: body + required: true + schema: + type: object + properties: + tx: + description: |- + tx is the transaction to simulate. + Deprecated. Send raw tx bytes instead. + type: object + properties: + body: + title: body is the processable content of the transaction + type: object + properties: + messages: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + messages is a list of messages to be executed. The + required signers of + + those messages define the number and order of elements + in AuthInfo's + + signer_infos and Tx's signatures. Each required signer + address is added to + + the list only the first time it occurs. + + By convention, the first required signer (usually from + the first message) + + is referred to as the primary signer and pays the fee + for the whole + + transaction. + memo: + type: string + description: >- + memo is any arbitrary note/comment to be added to the + transaction. + + WARNING: in clients, any publicly exposed text should + not be called memo, + + but should be called `note` instead (see + https://github.com/cosmos/cosmos-sdk/issues/9122). + timeout_height: + type: string + format: uint64 + title: >- + timeout is the block height after which this + transaction will not + + be processed by the chain + extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be + added by chains + + when the default options are not sufficient. If any of + these are present + + and can't be handled, the transaction will be rejected + non_critical_extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be + added by chains + + when the default options are not sufficient. If any of + these are present + + and can't be handled, they will be ignored + description: >- + TxBody is the body of a transaction that all signers sign + over. + auth_info: + title: >- + auth_info is the authorization related content of the + transaction, + + specifically signers, signer modes and fee + type: object + properties: + signer_infos: + type: array + items: + type: object + properties: + public_key: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + public_key is the public key of the signer. It + is optional for accounts + + that already exist in state. If unset, the + verifier can use the required \ + + signer address for this position and lookup the + public key. + mode_info: + title: >- + mode_info describes the signing mode of the + signer and is a nested + + structure to support nested multisig pubkey's + type: object + properties: + single: + title: single represents a single signer + type: object + properties: + mode: + title: >- + mode is the signing mode of the single + signer + type: string + enum: + - SIGN_MODE_UNSPECIFIED + - SIGN_MODE_DIRECT + - SIGN_MODE_TEXTUAL + - SIGN_MODE_LEGACY_AMINO_JSON + - SIGN_MODE_EIP_191 + default: SIGN_MODE_UNSPECIFIED + description: >- + SignMode represents a signing mode with + its own security guarantees. + + - SIGN_MODE_UNSPECIFIED: SIGN_MODE_UNSPECIFIED specifies an unknown signing mode and will be + rejected + - SIGN_MODE_DIRECT: SIGN_MODE_DIRECT specifies a signing mode which uses SignDoc and is + verified with raw bytes from Tx + - SIGN_MODE_TEXTUAL: SIGN_MODE_TEXTUAL is a future signing mode that will verify some + human-readable textual representation on + top of the binary representation + + from SIGN_MODE_DIRECT + - SIGN_MODE_LEGACY_AMINO_JSON: SIGN_MODE_LEGACY_AMINO_JSON is a backwards compatibility mode which uses + Amino JSON and will be removed in the + future + - SIGN_MODE_EIP_191: SIGN_MODE_EIP_191 specifies the sign mode for EIP 191 signing on the Cosmos + SDK. Ref: + https://eips.ethereum.org/EIPS/eip-191 + + + Currently, SIGN_MODE_EIP_191 is + registered as a SignMode enum variant, + + but is not implemented on the SDK by + default. To enable EIP-191, you need + + to pass a custom `TxConfig` that has an + implementation of + + `SignModeHandler` for EIP-191. The SDK + may decide to fully support + + EIP-191 in the future. + + + Since: cosmos-sdk 0.45.2 + multi: + title: multi represents a nested multisig signer + type: object + properties: + bitarray: + title: >- + bitarray specifies which keys within the + multisig are signing + type: object + properties: + extra_bits_stored: + type: integer + format: int64 + elems: + type: string + format: byte + description: >- + CompactBitArray is an implementation of + a space efficient bit array. + + This is used to ensure that the encoded + data takes up a minimal amount of + + space after proto encoding. + + This is not thread safe, and is not + intended for concurrent usage. + mode_infos: + type: array + items: {} + title: >- + mode_infos is the corresponding modes of + the signers of the multisig + + which could include nested multisig + public keys + description: >- + ModeInfo describes the signing mode of a single + or nested multisig signer. + sequence: + type: string + format: uint64 + description: >- + sequence is the sequence of the account, which + describes the + + number of committed transactions signed by a + given address. It is used to + + prevent replay attacks. + description: >- + SignerInfo describes the public key and signing mode + of a single top-level + + signer. + description: >- + signer_infos defines the signing modes for the + required signers. The number + + and order of elements must match the required signers + from TxBody's + + messages. The first element is the primary signer and + the one which pays + + the fee. + fee: + description: >- + Fee is the fee and gas limit for the transaction. The + first signer is the + + primary signer and the one which pays the fee. The fee + can be calculated + + based on the cost of evaluating the body and doing + signature verification + + of the signers. This can be estimated via simulation. + type: object + properties: + amount: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an + amount. + + + NOTE: The amount field is an Int which + implements the custom method + + signatures required by gogoproto. + title: amount is the amount of coins to be paid as a fee + gas_limit: + type: string + format: uint64 + title: >- + gas_limit is the maximum gas that can be used in + transaction processing + + before an out of gas error occurs + payer: + type: string + description: >- + if unset, the first signer is responsible for + paying the fees. If set, the specified account + must pay the fees. + + the payer must be a tx signer (and thus have + signed this field in AuthInfo). + + setting this field does *not* change the ordering + of required signers for the transaction. + granter: + type: string + title: >- + if set, the fee payer (either the first signer or + the value of the payer field) requests that a fee + grant be used + + to pay fees instead of the fee payer's own + balance. If an appropriate fee grant does not + exist or the chain does + + not support fee grants, this will fail + description: >- + AuthInfo describes the fee and signer modes that are used + to sign a + + transaction. + signatures: + type: array + items: + type: string + format: byte + description: >- + signatures is a list of signatures that matches the length + and order of + + AuthInfo's signer_infos to allow connecting signature meta + information like + + public key and signing mode by position. + tx_bytes: + type: string + format: byte + description: |- + tx_bytes is the raw transaction. + + Since: cosmos-sdk 0.43 + description: |- + SimulateRequest is the request type for the Service.Simulate + RPC method. + tags: + - gRPC Gateway API + /cosmos/tx/v1beta1/txs: + get: + summary: GetTxsEvent fetches txs by event. + operationId: GetTxsEvent_PUNXQ + responses: + '200': + description: A successful response. + schema: + type: object + properties: + txs: + type: array + items: + type: object + properties: + body: + title: body is the processable content of the transaction + type: object + properties: + messages: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + messages is a list of messages to be executed. The + required signers of + + those messages define the number and order of + elements in AuthInfo's + + signer_infos and Tx's signatures. Each required + signer address is added to + + the list only the first time it occurs. + + By convention, the first required signer (usually + from the first message) + + is referred to as the primary signer and pays the + fee for the whole + + transaction. + memo: + type: string + description: >- + memo is any arbitrary note/comment to be added to + the transaction. + + WARNING: in clients, any publicly exposed text + should not be called memo, + + but should be called `note` instead (see + https://github.com/cosmos/cosmos-sdk/issues/9122). + timeout_height: + type: string + format: uint64 + title: >- + timeout is the block height after which this + transaction will not + + be processed by the chain + extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be + added by chains + + when the default options are not sufficient. If any + of these are present + + and can't be handled, the transaction will be + rejected + non_critical_extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be + added by chains + + when the default options are not sufficient. If any + of these are present + + and can't be handled, they will be ignored + description: >- + TxBody is the body of a transaction that all signers + sign over. + auth_info: + title: >- + auth_info is the authorization related content of the + transaction, + + specifically signers, signer modes and fee + type: object + properties: + signer_infos: + type: array + items: + type: object + properties: + public_key: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + public_key is the public key of the signer. It + is optional for accounts + + that already exist in state. If unset, the + verifier can use the required \ + + signer address for this position and lookup + the public key. + mode_info: + title: >- + mode_info describes the signing mode of the + signer and is a nested + + structure to support nested multisig pubkey's + type: object + properties: + single: + title: single represents a single signer + type: object + properties: + mode: + title: >- + mode is the signing mode of the single + signer + type: string + enum: + - SIGN_MODE_UNSPECIFIED + - SIGN_MODE_DIRECT + - SIGN_MODE_TEXTUAL + - SIGN_MODE_LEGACY_AMINO_JSON + - SIGN_MODE_EIP_191 + default: SIGN_MODE_UNSPECIFIED + description: >- + SignMode represents a signing mode with + its own security guarantees. + + - SIGN_MODE_UNSPECIFIED: SIGN_MODE_UNSPECIFIED specifies an unknown signing mode and will be + rejected + - SIGN_MODE_DIRECT: SIGN_MODE_DIRECT specifies a signing mode which uses SignDoc and is + verified with raw bytes from Tx + - SIGN_MODE_TEXTUAL: SIGN_MODE_TEXTUAL is a future signing mode that will verify some + human-readable textual representation on + top of the binary representation + + from SIGN_MODE_DIRECT + - SIGN_MODE_LEGACY_AMINO_JSON: SIGN_MODE_LEGACY_AMINO_JSON is a backwards compatibility mode which uses + Amino JSON and will be removed in the + future + - SIGN_MODE_EIP_191: SIGN_MODE_EIP_191 specifies the sign mode for EIP 191 signing on the Cosmos + SDK. Ref: + https://eips.ethereum.org/EIPS/eip-191 + + + Currently, SIGN_MODE_EIP_191 is + registered as a SignMode enum variant, + + but is not implemented on the SDK by + default. To enable EIP-191, you need + + to pass a custom `TxConfig` that has an + implementation of + + `SignModeHandler` for EIP-191. The SDK + may decide to fully support + + EIP-191 in the future. + + + Since: cosmos-sdk 0.45.2 + multi: + title: multi represents a nested multisig signer + type: object + properties: + bitarray: + title: >- + bitarray specifies which keys within the + multisig are signing + type: object + properties: + extra_bits_stored: + type: integer + format: int64 + elems: + type: string + format: byte + description: >- + CompactBitArray is an implementation of + a space efficient bit array. + + This is used to ensure that the encoded + data takes up a minimal amount of + + space after proto encoding. + + This is not thread safe, and is not + intended for concurrent usage. + mode_infos: + type: array + items: {} + title: >- + mode_infos is the corresponding modes of + the signers of the multisig + + which could include nested multisig + public keys + description: >- + ModeInfo describes the signing mode of a + single or nested multisig signer. + sequence: + type: string + format: uint64 + description: >- + sequence is the sequence of the account, which + describes the + + number of committed transactions signed by a + given address. It is used to + + prevent replay attacks. + description: >- + SignerInfo describes the public key and signing + mode of a single top-level + + signer. + description: >- + signer_infos defines the signing modes for the + required signers. The number + + and order of elements must match the required + signers from TxBody's + + messages. The first element is the primary signer + and the one which pays + + the fee. + fee: + description: >- + Fee is the fee and gas limit for the transaction. + The first signer is the + + primary signer and the one which pays the fee. The + fee can be calculated + + based on the cost of evaluating the body and doing + signature verification + + of the signers. This can be estimated via + simulation. + type: object + properties: + amount: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and + an amount. + + + NOTE: The amount field is an Int which + implements the custom method + + signatures required by gogoproto. + title: >- + amount is the amount of coins to be paid as a + fee + gas_limit: + type: string + format: uint64 + title: >- + gas_limit is the maximum gas that can be used in + transaction processing + + before an out of gas error occurs + payer: + type: string + description: >- + if unset, the first signer is responsible for + paying the fees. If set, the specified account + must pay the fees. + + the payer must be a tx signer (and thus have + signed this field in AuthInfo). + + setting this field does *not* change the + ordering of required signers for the + transaction. + granter: + type: string + title: >- + if set, the fee payer (either the first signer + or the value of the payer field) requests that a + fee grant be used + + to pay fees instead of the fee payer's own + balance. If an appropriate fee grant does not + exist or the chain does + + not support fee grants, this will fail + description: >- + AuthInfo describes the fee and signer modes that are + used to sign a + + transaction. + signatures: + type: array + items: + type: string + format: byte + description: >- + signatures is a list of signatures that matches the + length and order of + + AuthInfo's signer_infos to allow connecting signature + meta information like + + public key and signing mode by position. + description: Tx is the standard type used for broadcasting transactions. + description: txs is the list of queried transactions. + tx_responses: + type: array + items: + type: object + properties: + height: + type: string + format: int64 + title: The block height + txhash: + type: string + description: The transaction hash. + codespace: + type: string + title: Namespace for the Code + code: + type: integer + format: int64 + description: Response code. + data: + type: string + description: Result bytes, if any. + raw_log: + type: string + description: >- + The output of the application's logger (raw string). May + be + + non-deterministic. + logs: + type: array + items: + type: object + properties: + msg_index: + type: integer + format: int64 + log: + type: string + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + value: + type: string + description: >- + Attribute defines an attribute wrapper + where the key and value are + + strings instead of raw bytes. + description: >- + StringEvent defines en Event object wrapper + where all the attributes + + contain key/value pairs that are strings instead + of raw bytes. + description: >- + Events contains a slice of Event objects that were + emitted during some + + execution. + description: >- + ABCIMessageLog defines a structure containing an + indexed tx ABCI message log. + description: >- + The output of the application's logger (typed). May be + non-deterministic. + info: + type: string + description: Additional information. May be non-deterministic. + gas_wanted: + type: string + format: int64 + description: Amount of gas requested for transaction. + gas_used: + type: string + format: int64 + description: Amount of gas consumed by transaction. + tx: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: The request transaction bytes. + timestamp: + type: string + description: >- + Time of the previous block. For heights > 1, it's the + weighted median of + + the timestamps of the valid votes in the + block.LastCommit. For height == 1, + + it's genesis time. + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + format: byte + value: + type: string + format: byte + index: + type: boolean + description: >- + EventAttribute is a single key-value pair, + associated with an event. + description: >- + Event allows application developers to attach + additional information to + + ResponseBeginBlock, ResponseEndBlock, ResponseCheckTx + and ResponseDeliverTx. + + Later, transactions may be queried using these events. + description: >- + Events defines all the events emitted by processing a + transaction. Note, + + these events include those emitted by processing all the + messages and those + + emitted from the ante handler. Whereas Logs contains the + events, with + + additional metadata, emitted only by processing the + messages. + + + Since: cosmos-sdk 0.42.11, 0.44.5, 0.45 + description: >- + TxResponse defines a structure containing relevant tx data + and metadata. The + + tags are stringified and the log is JSON decoded. + description: tx_responses is the list of queried TxResponses. + pagination: + description: pagination defines a pagination for the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + GetTxsEventResponse is the response type for the + Service.TxsByEvents + + RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: events + description: events is the list of transaction event type. + in: query + required: false + type: array + items: + type: string + collectionFormat: multi + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + - name: order_by + description: |2- + - ORDER_BY_UNSPECIFIED: ORDER_BY_UNSPECIFIED specifies an unknown sorting order. OrderBy defaults to ASC in this case. + - ORDER_BY_ASC: ORDER_BY_ASC defines ascending order + - ORDER_BY_DESC: ORDER_BY_DESC defines descending order + in: query + required: false + type: string + enum: + - ORDER_BY_UNSPECIFIED + - ORDER_BY_ASC + - ORDER_BY_DESC + default: ORDER_BY_UNSPECIFIED + tags: + - gRPC Gateway API + post: + summary: BroadcastTx broadcast transaction. + operationId: BroadcastTx_2H2YD + responses: + '200': + description: A successful response. + schema: + type: object + properties: + tx_response: + type: object + properties: + height: + type: string + format: int64 + title: The block height + txhash: + type: string + description: The transaction hash. + codespace: + type: string + title: Namespace for the Code + code: + type: integer + format: int64 + description: Response code. + data: + type: string + description: Result bytes, if any. + raw_log: + type: string + description: >- + The output of the application's logger (raw string). May + be + + non-deterministic. + logs: + type: array + items: + type: object + properties: + msg_index: + type: integer + format: int64 + log: + type: string + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + value: + type: string + description: >- + Attribute defines an attribute wrapper where + the key and value are + + strings instead of raw bytes. + description: >- + StringEvent defines en Event object wrapper where + all the attributes + + contain key/value pairs that are strings instead + of raw bytes. + description: >- + Events contains a slice of Event objects that were + emitted during some + + execution. + description: >- + ABCIMessageLog defines a structure containing an indexed + tx ABCI message log. + description: >- + The output of the application's logger (typed). May be + non-deterministic. + info: + type: string + description: Additional information. May be non-deterministic. + gas_wanted: + type: string + format: int64 + description: Amount of gas requested for transaction. + gas_used: + type: string + format: int64 + description: Amount of gas consumed by transaction. + tx: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: The request transaction bytes. + timestamp: + type: string + description: >- + Time of the previous block. For heights > 1, it's the + weighted median of + + the timestamps of the valid votes in the block.LastCommit. + For height == 1, + + it's genesis time. + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + format: byte + value: + type: string + format: byte + index: + type: boolean + description: >- + EventAttribute is a single key-value pair, + associated with an event. + description: >- + Event allows application developers to attach additional + information to + + ResponseBeginBlock, ResponseEndBlock, ResponseCheckTx + and ResponseDeliverTx. + + Later, transactions may be queried using these events. + description: >- + Events defines all the events emitted by processing a + transaction. Note, + + these events include those emitted by processing all the + messages and those + + emitted from the ante handler. Whereas Logs contains the + events, with + + additional metadata, emitted only by processing the + messages. + + + Since: cosmos-sdk 0.42.11, 0.44.5, 0.45 + description: >- + TxResponse defines a structure containing relevant tx data and + metadata. The + + tags are stringified and the log is JSON decoded. + description: |- + BroadcastTxResponse is the response type for the + Service.BroadcastTx method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: body + in: body + required: true + schema: + type: object + properties: + tx_bytes: + type: string + format: byte + description: tx_bytes is the raw transaction. + mode: + type: string + enum: + - BROADCAST_MODE_UNSPECIFIED + - BROADCAST_MODE_BLOCK + - BROADCAST_MODE_SYNC + - BROADCAST_MODE_ASYNC + default: BROADCAST_MODE_UNSPECIFIED + description: >- + BroadcastMode specifies the broadcast mode for the + TxService.Broadcast RPC method. + + - BROADCAST_MODE_UNSPECIFIED: zero-value for mode ordering + - BROADCAST_MODE_BLOCK: BROADCAST_MODE_BLOCK defines a tx broadcasting mode where the client waits for + the tx to be committed in a block. + - BROADCAST_MODE_SYNC: BROADCAST_MODE_SYNC defines a tx broadcasting mode where the client waits for + a CheckTx execution response only. + - BROADCAST_MODE_ASYNC: BROADCAST_MODE_ASYNC defines a tx broadcasting mode where the client returns + immediately. + description: >- + BroadcastTxRequest is the request type for the + Service.BroadcastTxRequest + + RPC method. + tags: + - gRPC Gateway API + /cosmos/tx/v1beta1/txs/block/{height}: + get: + summary: GetBlockWithTxs fetches a block with decoded txs. + description: 'Since: cosmos-sdk 0.45.2' + operationId: GetBlockWithTxs_YQI6M + responses: + '200': + description: A successful response. + schema: + type: object + properties: + txs: + type: array + items: + type: object + properties: + body: + title: body is the processable content of the transaction + type: object + properties: + messages: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + messages is a list of messages to be executed. The + required signers of + + those messages define the number and order of + elements in AuthInfo's + + signer_infos and Tx's signatures. Each required + signer address is added to + + the list only the first time it occurs. + + By convention, the first required signer (usually + from the first message) + + is referred to as the primary signer and pays the + fee for the whole + + transaction. + memo: + type: string + description: >- + memo is any arbitrary note/comment to be added to + the transaction. + + WARNING: in clients, any publicly exposed text + should not be called memo, + + but should be called `note` instead (see + https://github.com/cosmos/cosmos-sdk/issues/9122). + timeout_height: + type: string + format: uint64 + title: >- + timeout is the block height after which this + transaction will not + + be processed by the chain + extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be + added by chains + + when the default options are not sufficient. If any + of these are present + + and can't be handled, the transaction will be + rejected + non_critical_extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be + added by chains + + when the default options are not sufficient. If any + of these are present + + and can't be handled, they will be ignored + description: >- + TxBody is the body of a transaction that all signers + sign over. + auth_info: + title: >- + auth_info is the authorization related content of the + transaction, + + specifically signers, signer modes and fee + type: object + properties: + signer_infos: + type: array + items: + type: object + properties: + public_key: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + public_key is the public key of the signer. It + is optional for accounts + + that already exist in state. If unset, the + verifier can use the required \ + + signer address for this position and lookup + the public key. + mode_info: + title: >- + mode_info describes the signing mode of the + signer and is a nested + + structure to support nested multisig pubkey's + type: object + properties: + single: + title: single represents a single signer + type: object + properties: + mode: + title: >- + mode is the signing mode of the single + signer + type: string + enum: + - SIGN_MODE_UNSPECIFIED + - SIGN_MODE_DIRECT + - SIGN_MODE_TEXTUAL + - SIGN_MODE_LEGACY_AMINO_JSON + - SIGN_MODE_EIP_191 + default: SIGN_MODE_UNSPECIFIED + description: >- + SignMode represents a signing mode with + its own security guarantees. + + - SIGN_MODE_UNSPECIFIED: SIGN_MODE_UNSPECIFIED specifies an unknown signing mode and will be + rejected + - SIGN_MODE_DIRECT: SIGN_MODE_DIRECT specifies a signing mode which uses SignDoc and is + verified with raw bytes from Tx + - SIGN_MODE_TEXTUAL: SIGN_MODE_TEXTUAL is a future signing mode that will verify some + human-readable textual representation on + top of the binary representation + + from SIGN_MODE_DIRECT + - SIGN_MODE_LEGACY_AMINO_JSON: SIGN_MODE_LEGACY_AMINO_JSON is a backwards compatibility mode which uses + Amino JSON and will be removed in the + future + - SIGN_MODE_EIP_191: SIGN_MODE_EIP_191 specifies the sign mode for EIP 191 signing on the Cosmos + SDK. Ref: + https://eips.ethereum.org/EIPS/eip-191 + + + Currently, SIGN_MODE_EIP_191 is + registered as a SignMode enum variant, + + but is not implemented on the SDK by + default. To enable EIP-191, you need + + to pass a custom `TxConfig` that has an + implementation of + + `SignModeHandler` for EIP-191. The SDK + may decide to fully support + + EIP-191 in the future. + + + Since: cosmos-sdk 0.45.2 + multi: + title: multi represents a nested multisig signer + type: object + properties: + bitarray: + title: >- + bitarray specifies which keys within the + multisig are signing + type: object + properties: + extra_bits_stored: + type: integer + format: int64 + elems: + type: string + format: byte + description: >- + CompactBitArray is an implementation of + a space efficient bit array. + + This is used to ensure that the encoded + data takes up a minimal amount of + + space after proto encoding. + + This is not thread safe, and is not + intended for concurrent usage. + mode_infos: + type: array + items: {} + title: >- + mode_infos is the corresponding modes of + the signers of the multisig + + which could include nested multisig + public keys + description: >- + ModeInfo describes the signing mode of a + single or nested multisig signer. + sequence: + type: string + format: uint64 + description: >- + sequence is the sequence of the account, which + describes the + + number of committed transactions signed by a + given address. It is used to + + prevent replay attacks. + description: >- + SignerInfo describes the public key and signing + mode of a single top-level + + signer. + description: >- + signer_infos defines the signing modes for the + required signers. The number + + and order of elements must match the required + signers from TxBody's + + messages. The first element is the primary signer + and the one which pays + + the fee. + fee: + description: >- + Fee is the fee and gas limit for the transaction. + The first signer is the + + primary signer and the one which pays the fee. The + fee can be calculated + + based on the cost of evaluating the body and doing + signature verification + + of the signers. This can be estimated via + simulation. + type: object + properties: + amount: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and + an amount. + + + NOTE: The amount field is an Int which + implements the custom method + + signatures required by gogoproto. + title: >- + amount is the amount of coins to be paid as a + fee + gas_limit: + type: string + format: uint64 + title: >- + gas_limit is the maximum gas that can be used in + transaction processing + + before an out of gas error occurs + payer: + type: string + description: >- + if unset, the first signer is responsible for + paying the fees. If set, the specified account + must pay the fees. + + the payer must be a tx signer (and thus have + signed this field in AuthInfo). + + setting this field does *not* change the + ordering of required signers for the + transaction. + granter: + type: string + title: >- + if set, the fee payer (either the first signer + or the value of the payer field) requests that a + fee grant be used + + to pay fees instead of the fee payer's own + balance. If an appropriate fee grant does not + exist or the chain does + + not support fee grants, this will fail + description: >- + AuthInfo describes the fee and signer modes that are + used to sign a + + transaction. + signatures: + type: array + items: + type: string + format: byte + description: >- + signatures is a list of signatures that matches the + length and order of + + AuthInfo's signer_infos to allow connecting signature + meta information like + + public key and signing mode by position. + description: Tx is the standard type used for broadcasting transactions. + description: txs are the transactions in the block. + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + block: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for processing + a block in the blockchain, + + including all blockchain data structures and the rules + of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + data: + type: object + properties: + txs: + type: array + items: + type: string + format: byte + description: >- + Txs that will be applied by state @ block.Height+1. + + NOTE: not all txs here are valid. We're just agreeing + on the order first. + + This means that block.AppHash does not include these + txs. + title: >- + Data contains the set of transactions included in the + block + evidence: + type: object + properties: + evidence: + type: array + items: + type: object + properties: + duplicate_vote_evidence: + type: object + properties: + vote_a: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: >- + SignedMsgType is a type of signed + message in the consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or + commit vote from validators for + + consensus. + vote_b: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: >- + SignedMsgType is a type of signed + message in the consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or + commit vote from validators for + + consensus. + total_voting_power: + type: string + format: int64 + validator_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: >- + DuplicateVoteEvidence contains evidence of a + validator signed two conflicting votes. + light_client_attack_evidence: + type: object + properties: + conflicting_block: + type: object + properties: + signed_header: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules + for processing a block in the + blockchain, + + including all blockchain data structures + and the rules of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: >- + hashes from the app output from the prev + block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: >- + Header defines the structure of a block + header. + commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: >- + BlockIdFlag indicates which BlcokID the + signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: >- + CommitSig is a part of the Vote included + in a Commit. + description: >- + Commit contains the evidence that a + block was committed by a set of + validators. + validator_set: + type: object + properties: + validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: >- + PublicKey defines the keys available for + use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + proposer: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: >- + PublicKey defines the keys available for + use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + common_height: + type: string + format: int64 + byzantine_validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: >- + PublicKey defines the keys available for + use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: >- + LightClientAttackEvidence contains evidence of a + set of validators attempting to mislead a light + client. + last_commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: >- + BlockIdFlag indicates which BlcokID the + signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: >- + CommitSig is a part of the Vote included in a + Commit. + description: >- + Commit contains the evidence that a block was committed by + a set of validators. + pagination: + description: pagination defines a pagination for the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + GetBlockWithTxsResponse is the response type for the + Service.GetBlockWithTxs method. + + + Since: cosmos-sdk 0.45.2 + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: height + description: height is the height of the block to query. + in: path + required: true + type: string + format: int64 + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /cosmos/tx/v1beta1/txs/{hash}: + get: + summary: GetTx fetches a tx by hash. + operationId: GetTx_M9HVX + responses: + '200': + description: A successful response. + schema: + type: object + properties: + tx: + type: object + properties: + body: + title: body is the processable content of the transaction + type: object + properties: + messages: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + messages is a list of messages to be executed. The + required signers of + + those messages define the number and order of elements + in AuthInfo's + + signer_infos and Tx's signatures. Each required signer + address is added to + + the list only the first time it occurs. + + By convention, the first required signer (usually from + the first message) + + is referred to as the primary signer and pays the fee + for the whole + + transaction. + memo: + type: string + description: >- + memo is any arbitrary note/comment to be added to the + transaction. + + WARNING: in clients, any publicly exposed text should + not be called memo, + + but should be called `note` instead (see + https://github.com/cosmos/cosmos-sdk/issues/9122). + timeout_height: + type: string + format: uint64 + title: >- + timeout is the block height after which this + transaction will not + + be processed by the chain + extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be + added by chains + + when the default options are not sufficient. If any of + these are present + + and can't be handled, the transaction will be rejected + non_critical_extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be + added by chains + + when the default options are not sufficient. If any of + these are present + + and can't be handled, they will be ignored + description: >- + TxBody is the body of a transaction that all signers sign + over. + auth_info: + title: >- + auth_info is the authorization related content of the + transaction, + + specifically signers, signer modes and fee + type: object + properties: + signer_infos: + type: array + items: + type: object + properties: + public_key: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + public_key is the public key of the signer. It + is optional for accounts + + that already exist in state. If unset, the + verifier can use the required \ + + signer address for this position and lookup the + public key. + mode_info: + title: >- + mode_info describes the signing mode of the + signer and is a nested + + structure to support nested multisig pubkey's + type: object + properties: + single: + title: single represents a single signer + type: object + properties: + mode: + title: >- + mode is the signing mode of the single + signer + type: string + enum: + - SIGN_MODE_UNSPECIFIED + - SIGN_MODE_DIRECT + - SIGN_MODE_TEXTUAL + - SIGN_MODE_LEGACY_AMINO_JSON + - SIGN_MODE_EIP_191 + default: SIGN_MODE_UNSPECIFIED + description: >- + SignMode represents a signing mode with + its own security guarantees. + + - SIGN_MODE_UNSPECIFIED: SIGN_MODE_UNSPECIFIED specifies an unknown signing mode and will be + rejected + - SIGN_MODE_DIRECT: SIGN_MODE_DIRECT specifies a signing mode which uses SignDoc and is + verified with raw bytes from Tx + - SIGN_MODE_TEXTUAL: SIGN_MODE_TEXTUAL is a future signing mode that will verify some + human-readable textual representation on + top of the binary representation + + from SIGN_MODE_DIRECT + - SIGN_MODE_LEGACY_AMINO_JSON: SIGN_MODE_LEGACY_AMINO_JSON is a backwards compatibility mode which uses + Amino JSON and will be removed in the + future + - SIGN_MODE_EIP_191: SIGN_MODE_EIP_191 specifies the sign mode for EIP 191 signing on the Cosmos + SDK. Ref: + https://eips.ethereum.org/EIPS/eip-191 + + + Currently, SIGN_MODE_EIP_191 is + registered as a SignMode enum variant, + + but is not implemented on the SDK by + default. To enable EIP-191, you need + + to pass a custom `TxConfig` that has an + implementation of + + `SignModeHandler` for EIP-191. The SDK + may decide to fully support + + EIP-191 in the future. + + + Since: cosmos-sdk 0.45.2 + multi: + title: multi represents a nested multisig signer + type: object + properties: + bitarray: + title: >- + bitarray specifies which keys within the + multisig are signing + type: object + properties: + extra_bits_stored: + type: integer + format: int64 + elems: + type: string + format: byte + description: >- + CompactBitArray is an implementation of + a space efficient bit array. + + This is used to ensure that the encoded + data takes up a minimal amount of + + space after proto encoding. + + This is not thread safe, and is not + intended for concurrent usage. + mode_infos: + type: array + items: {} + title: >- + mode_infos is the corresponding modes of + the signers of the multisig + + which could include nested multisig + public keys + description: >- + ModeInfo describes the signing mode of a single + or nested multisig signer. + sequence: + type: string + format: uint64 + description: >- + sequence is the sequence of the account, which + describes the + + number of committed transactions signed by a + given address. It is used to + + prevent replay attacks. + description: >- + SignerInfo describes the public key and signing mode + of a single top-level + + signer. + description: >- + signer_infos defines the signing modes for the + required signers. The number + + and order of elements must match the required signers + from TxBody's + + messages. The first element is the primary signer and + the one which pays + + the fee. + fee: + description: >- + Fee is the fee and gas limit for the transaction. The + first signer is the + + primary signer and the one which pays the fee. The fee + can be calculated + + based on the cost of evaluating the body and doing + signature verification + + of the signers. This can be estimated via simulation. + type: object + properties: + amount: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an + amount. + + + NOTE: The amount field is an Int which + implements the custom method + + signatures required by gogoproto. + title: amount is the amount of coins to be paid as a fee + gas_limit: + type: string + format: uint64 + title: >- + gas_limit is the maximum gas that can be used in + transaction processing + + before an out of gas error occurs + payer: + type: string + description: >- + if unset, the first signer is responsible for + paying the fees. If set, the specified account + must pay the fees. + + the payer must be a tx signer (and thus have + signed this field in AuthInfo). + + setting this field does *not* change the ordering + of required signers for the transaction. + granter: + type: string + title: >- + if set, the fee payer (either the first signer or + the value of the payer field) requests that a fee + grant be used + + to pay fees instead of the fee payer's own + balance. If an appropriate fee grant does not + exist or the chain does + + not support fee grants, this will fail + description: >- + AuthInfo describes the fee and signer modes that are used + to sign a + + transaction. + signatures: + type: array + items: + type: string + format: byte + description: >- + signatures is a list of signatures that matches the length + and order of + + AuthInfo's signer_infos to allow connecting signature meta + information like + + public key and signing mode by position. + description: Tx is the standard type used for broadcasting transactions. + tx_response: + type: object + properties: + height: + type: string + format: int64 + title: The block height + txhash: + type: string + description: The transaction hash. + codespace: + type: string + title: Namespace for the Code + code: + type: integer + format: int64 + description: Response code. + data: + type: string + description: Result bytes, if any. + raw_log: + type: string + description: >- + The output of the application's logger (raw string). May + be + + non-deterministic. + logs: + type: array + items: + type: object + properties: + msg_index: + type: integer + format: int64 + log: + type: string + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + value: + type: string + description: >- + Attribute defines an attribute wrapper where + the key and value are + + strings instead of raw bytes. + description: >- + StringEvent defines en Event object wrapper where + all the attributes + + contain key/value pairs that are strings instead + of raw bytes. + description: >- + Events contains a slice of Event objects that were + emitted during some + + execution. + description: >- + ABCIMessageLog defines a structure containing an indexed + tx ABCI message log. + description: >- + The output of the application's logger (typed). May be + non-deterministic. + info: + type: string + description: Additional information. May be non-deterministic. + gas_wanted: + type: string + format: int64 + description: Amount of gas requested for transaction. + gas_used: + type: string + format: int64 + description: Amount of gas consumed by transaction. + tx: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: The request transaction bytes. + timestamp: + type: string + description: >- + Time of the previous block. For heights > 1, it's the + weighted median of + + the timestamps of the valid votes in the block.LastCommit. + For height == 1, + + it's genesis time. + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + format: byte + value: + type: string + format: byte + index: + type: boolean + description: >- + EventAttribute is a single key-value pair, + associated with an event. + description: >- + Event allows application developers to attach additional + information to + + ResponseBeginBlock, ResponseEndBlock, ResponseCheckTx + and ResponseDeliverTx. + + Later, transactions may be queried using these events. + description: >- + Events defines all the events emitted by processing a + transaction. Note, + + these events include those emitted by processing all the + messages and those + + emitted from the ante handler. Whereas Logs contains the + events, with + + additional metadata, emitted only by processing the + messages. + + + Since: cosmos-sdk 0.42.11, 0.44.5, 0.45 + description: >- + TxResponse defines a structure containing relevant tx data and + metadata. The + + tags are stringified and the log is JSON decoded. + description: GetTxResponse is the response type for the Service.GetTx method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: hash + description: hash is the tx hash to query, encoded as a hex string. + in: path + required: true + type: string + tags: + - gRPC Gateway API + /inter-tx/interchain_account/owner/{owner}/connection/{connection_id}: + get: + summary: >- + QueryInterchainAccount returns the interchain account for given owner + address on a given connection pair + operationId: InterchainAccount_FCQUO + responses: + '200': + description: A successful response. + schema: + type: object + properties: + interchain_account_address: + type: string + title: >- + QueryInterchainAccountResponse the response type for the + Query/InterchainAccountAddress RPC + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: owner + in: path + required: true + type: string + - name: connection_id + in: path + required: true + type: string + tags: + - gRPC Gateway API + /cosmwasm/wasm/v1/code: + get: + summary: Codes gets the metadata for all stored wasm codes + operationId: Codes_USGTR + responses: + '200': + description: A successful response. + schema: + type: object + properties: + code_infos: + type: array + items: + type: object + properties: + code_id: + type: string + format: uint64 + creator: + type: string + data_hash: + type: string + format: byte + instantiate_permission: + type: object + properties: + permission: + type: string + enum: + - ACCESS_TYPE_UNSPECIFIED + - ACCESS_TYPE_NOBODY + - ACCESS_TYPE_ONLY_ADDRESS + - ACCESS_TYPE_EVERYBODY + - ACCESS_TYPE_ANY_OF_ADDRESSES + default: ACCESS_TYPE_UNSPECIFIED + description: >- + - ACCESS_TYPE_UNSPECIFIED: AccessTypeUnspecified + placeholder for empty value + - ACCESS_TYPE_NOBODY: AccessTypeNobody forbidden + - ACCESS_TYPE_ONLY_ADDRESS: AccessTypeOnlyAddress restricted to a single address + Deprecated: use AccessTypeAnyOfAddresses instead + - ACCESS_TYPE_EVERYBODY: AccessTypeEverybody unrestricted + - ACCESS_TYPE_ANY_OF_ADDRESSES: AccessTypeAnyOfAddresses allow any of the addresses + title: AccessType permission types + address: + type: string + title: |- + Address + Deprecated: replaced by addresses + addresses: + type: array + items: + type: string + description: AccessConfig access control type. + title: CodeInfoResponse contains code meta data from CodeInfo + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + title: >- + QueryCodesResponse is the response type for the Query/Codes RPC + method + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /cosmwasm/wasm/v1/code/{code_id}: + get: + summary: Code gets the binary code and metadata for a singe wasm code + operationId: Code_45RS6 + responses: + '200': + description: A successful response. + schema: + type: object + properties: + code_info: + type: object + properties: + code_id: + type: string + format: uint64 + creator: + type: string + data_hash: + type: string + format: byte + instantiate_permission: + type: object + properties: + permission: + type: string + enum: + - ACCESS_TYPE_UNSPECIFIED + - ACCESS_TYPE_NOBODY + - ACCESS_TYPE_ONLY_ADDRESS + - ACCESS_TYPE_EVERYBODY + - ACCESS_TYPE_ANY_OF_ADDRESSES + default: ACCESS_TYPE_UNSPECIFIED + description: >- + - ACCESS_TYPE_UNSPECIFIED: AccessTypeUnspecified + placeholder for empty value + - ACCESS_TYPE_NOBODY: AccessTypeNobody forbidden + - ACCESS_TYPE_ONLY_ADDRESS: AccessTypeOnlyAddress restricted to a single address + Deprecated: use AccessTypeAnyOfAddresses instead + - ACCESS_TYPE_EVERYBODY: AccessTypeEverybody unrestricted + - ACCESS_TYPE_ANY_OF_ADDRESSES: AccessTypeAnyOfAddresses allow any of the addresses + title: AccessType permission types + address: + type: string + title: |- + Address + Deprecated: replaced by addresses + addresses: + type: array + items: + type: string + description: AccessConfig access control type. + title: CodeInfoResponse contains code meta data from CodeInfo + data: + type: string + format: byte + title: >- + QueryCodeResponse is the response type for the Query/Code RPC + method + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: code_id + in: path + required: true + type: string + format: uint64 + tags: + - gRPC Gateway API + /cosmwasm/wasm/v1/code/{code_id}/contracts: + get: + summary: ContractsByCode lists all smart contracts for a code id + operationId: ContractsByCode_DI5NT + responses: + '200': + description: A successful response. + schema: + type: object + properties: + contracts: + type: array + items: + type: string + title: contracts are a set of contract addresses + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + title: |- + QueryContractsByCodeResponse is the response type for the + Query/ContractsByCode RPC method + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: code_id + in: path + required: true + type: string + format: uint64 + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /cosmwasm/wasm/v1/codes/params: + get: + summary: Params gets the module params + operationId: Params_LUDIW + responses: + '200': + description: A successful response. + schema: + type: object + properties: + params: + description: params defines the parameters of the module. + type: object + properties: + code_upload_access: + type: object + properties: + permission: + type: string + enum: + - ACCESS_TYPE_UNSPECIFIED + - ACCESS_TYPE_NOBODY + - ACCESS_TYPE_ONLY_ADDRESS + - ACCESS_TYPE_EVERYBODY + - ACCESS_TYPE_ANY_OF_ADDRESSES + default: ACCESS_TYPE_UNSPECIFIED + description: >- + - ACCESS_TYPE_UNSPECIFIED: AccessTypeUnspecified + placeholder for empty value + - ACCESS_TYPE_NOBODY: AccessTypeNobody forbidden + - ACCESS_TYPE_ONLY_ADDRESS: AccessTypeOnlyAddress restricted to a single address + Deprecated: use AccessTypeAnyOfAddresses instead + - ACCESS_TYPE_EVERYBODY: AccessTypeEverybody unrestricted + - ACCESS_TYPE_ANY_OF_ADDRESSES: AccessTypeAnyOfAddresses allow any of the addresses + title: AccessType permission types + address: + type: string + title: |- + Address + Deprecated: replaced by addresses + addresses: + type: array + items: + type: string + description: AccessConfig access control type. + instantiate_default_permission: + type: string + enum: + - ACCESS_TYPE_UNSPECIFIED + - ACCESS_TYPE_NOBODY + - ACCESS_TYPE_ONLY_ADDRESS + - ACCESS_TYPE_EVERYBODY + - ACCESS_TYPE_ANY_OF_ADDRESSES + default: ACCESS_TYPE_UNSPECIFIED + description: >- + - ACCESS_TYPE_UNSPECIFIED: AccessTypeUnspecified + placeholder for empty value + - ACCESS_TYPE_NOBODY: AccessTypeNobody forbidden + - ACCESS_TYPE_ONLY_ADDRESS: AccessTypeOnlyAddress restricted to a single address + Deprecated: use AccessTypeAnyOfAddresses instead + - ACCESS_TYPE_EVERYBODY: AccessTypeEverybody unrestricted + - ACCESS_TYPE_ANY_OF_ADDRESSES: AccessTypeAnyOfAddresses allow any of the addresses + title: AccessType permission types + description: >- + QueryParamsResponse is the response type for the Query/Params RPC + method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + /cosmwasm/wasm/v1/codes/pinned: + get: + summary: PinnedCodes gets the pinned code ids + operationId: PinnedCodes_38LCO + responses: + '200': + description: A successful response. + schema: + type: object + properties: + code_ids: + type: array + items: + type: string + format: uint64 + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + title: |- + QueryPinnedCodesResponse is the response type for the + Query/PinnedCodes RPC method + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /cosmwasm/wasm/v1/contract/{address}: + get: + summary: ContractInfo gets the contract meta data + operationId: ContractInfo_NYK65 + responses: + '200': + description: A successful response. + schema: + type: object + properties: + address: + type: string + title: address is the address of the contract + contract_info: + type: object + properties: + code_id: + type: string + format: uint64 + title: CodeID is the reference to the stored Wasm code + creator: + type: string + title: Creator address who initially instantiated the contract + admin: + type: string + title: Admin is an optional address that can execute migrations + label: + type: string + description: >- + Label is optional metadata to be stored with a contract + instance. + created: + description: Created Tx position when the contract was instantiated. + type: object + properties: + block_height: + type: string + format: uint64 + title: BlockHeight is the block the contract was created at + tx_index: + type: string + format: uint64 + title: >- + TxIndex is a monotonic counter within the block + (actual transaction index, + + or gas consumed) + ibc_port_id: + type: string + extension: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + Extension is an extension point to store custom metadata + within the + + persistence model. + title: ContractInfo stores a WASM contract instance + title: >- + QueryContractInfoResponse is the response type for the + Query/ContractInfo RPC + + method + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: address + description: address is the address of the contract to query + in: path + required: true + type: string + tags: + - gRPC Gateway API + /cosmwasm/wasm/v1/contract/{address}/history: + get: + summary: ContractHistory gets the contract code history + operationId: ContractHistory_M2L3Y + responses: + '200': + description: A successful response. + schema: + type: object + properties: + entries: + type: array + items: + type: object + properties: + operation: + type: string + enum: + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_UNSPECIFIED + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_INIT + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_MIGRATE + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_GENESIS + default: CONTRACT_CODE_HISTORY_OPERATION_TYPE_UNSPECIFIED + description: >- + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_UNSPECIFIED: + ContractCodeHistoryOperationTypeUnspecified placeholder + for empty value + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_INIT: ContractCodeHistoryOperationTypeInit on chain contract instantiation + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_MIGRATE: ContractCodeHistoryOperationTypeMigrate code migration + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_GENESIS: ContractCodeHistoryOperationTypeGenesis based on genesis data + title: >- + ContractCodeHistoryOperationType actions that caused a + code change + code_id: + type: string + format: uint64 + title: CodeID is the reference to the stored WASM code + updated: + description: Updated Tx position when the operation was executed. + type: object + properties: + block_height: + type: string + format: uint64 + title: BlockHeight is the block the contract was created at + tx_index: + type: string + format: uint64 + title: >- + TxIndex is a monotonic counter within the block + (actual transaction index, + + or gas consumed) + msg: + type: string + format: byte + description: ContractCodeHistoryEntry metadata to a contract. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + title: |- + QueryContractHistoryResponse is the response type for the + Query/ContractHistory RPC method + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: address + description: address is the address of the contract to query + in: path + required: true + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /cosmwasm/wasm/v1/contract/{address}/raw/{query_data}: + get: + summary: RawContractState gets single key from the raw store data of a contract + operationId: RawContractState_A25W1 + responses: + '200': + description: A successful response. + schema: + type: object + properties: + data: + type: string + format: byte + title: Data contains the raw store data + title: |- + QueryRawContractStateResponse is the response type for the + Query/RawContractState RPC method + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: address + description: address is the address of the contract + in: path + required: true + type: string + - name: query_data + in: path + required: true + type: string + format: byte + tags: + - gRPC Gateway API + /cosmwasm/wasm/v1/contract/{address}/smart/{query_data}: + get: + summary: SmartContractState get smart query result from the contract + operationId: SmartContractState_FMP76 + responses: + '200': + description: A successful response. + schema: + type: object + properties: + data: + type: string + format: byte + title: Data contains the json data returned from the smart contract + title: |- + QuerySmartContractStateResponse is the response type for the + Query/SmartContractState RPC method + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: address + description: address is the address of the contract + in: path + required: true + type: string + - name: query_data + description: QueryData contains the query data passed to the contract + in: path + required: true + type: string + format: byte + tags: + - gRPC Gateway API + /cosmwasm/wasm/v1/contract/{address}/state: + get: + summary: AllContractState gets all raw store data for a single contract + operationId: AllContractState_N88EG + responses: + '200': + description: A successful response. + schema: + type: object + properties: + models: + type: array + items: + type: object + properties: + key: + type: string + format: byte + title: hex-encode key to read it better (this is often ascii) + value: + type: string + format: byte + title: base64-encode raw value + title: Model is a struct that holds a KV pair + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + title: |- + QueryAllContractStateResponse is the response type for the + Query/AllContractState RPC method + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: address + description: address is the address of the contract + in: path + required: true + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /cosmwasm/wasm/v1/contracts/creator/{creator_address}: + get: + summary: ContractsByCreator gets the contracts by creator + operationId: ContractsByCreator_4VHDU + responses: + '200': + description: A successful response. + schema: + type: object + properties: + contract_addresses: + type: array + items: + type: string + title: ContractAddresses result set + pagination: + description: Pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + QueryContractsByCreatorResponse is the response type for the + Query/ContractsByCreator RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: creator_address + description: CreatorAddress is the address of contract creator + in: path + required: true + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /cosmos/feegrant/v1beta1/allowance/{granter}/{grantee}: + get: + summary: Allowance returns fee granted to the grantee by the granter. + operationId: Allowance_5N8HR + responses: + '200': + description: A successful response. + schema: + type: object + properties: + allowance: + description: allowance is a allowance granted for grantee by granter. + type: object + properties: + granter: + type: string + description: >- + granter is the address of the user granting an allowance + of their funds. + grantee: + type: string + description: >- + grantee is the address of the user being granted an + allowance of another user's funds. + allowance: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: allowance can be any of basic and filtered fee allowance. + title: >- + Grant is stored in the KVStore to record a grant with full + context + description: >- + QueryAllowanceResponse is the response type for the + Query/Allowance RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: granter + description: >- + granter is the address of the user granting an allowance of their + funds. + in: path + required: true + type: string + - name: grantee + description: >- + grantee is the address of the user being granted an allowance of + another user's funds. + in: path + required: true + type: string + tags: + - gRPC Gateway API + /cosmos/feegrant/v1beta1/allowances/{grantee}: + get: + summary: Allowances returns all the grants for address. + operationId: Allowances_PKM8A + responses: + '200': + description: A successful response. + schema: + type: object + properties: + allowances: + type: array + items: + type: object + properties: + granter: + type: string + description: >- + granter is the address of the user granting an allowance + of their funds. + grantee: + type: string + description: >- + grantee is the address of the user being granted an + allowance of another user's funds. + allowance: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + allowance can be any of basic and filtered fee + allowance. + title: >- + Grant is stored in the KVStore to record a grant with full + context + description: allowances are allowance's granted for grantee by granter. + pagination: + description: pagination defines an pagination for the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryAllowancesResponse is the response type for the + Query/Allowances RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: grantee + in: path + required: true + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /cosmos/feegrant/v1beta1/issued/{granter}: + get: + summary: |- + AllowancesByGranter returns all the grants given by an address + Since v0.46 + operationId: AllowancesByGranter_1A39E + responses: + '200': + description: A successful response. + schema: + type: object + properties: + allowances: + type: array + items: + type: object + properties: + granter: + type: string + description: >- + granter is the address of the user granting an allowance + of their funds. + grantee: + type: string + description: >- + grantee is the address of the user being granted an + allowance of another user's funds. + allowance: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + allowance can be any of basic and filtered fee + allowance. + title: >- + Grant is stored in the KVStore to record a grant with full + context + description: allowances that have been issued by the granter. + pagination: + description: pagination defines an pagination for the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryAllowancesByGranterResponse is the response type for the + Query/AllowancesByGranter RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: granter + in: path + required: true + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /gaia/globalfee/v1beta1/minimum_gas_prices: + get: + operationId: MinimumGasPrices_18KUX + responses: + '200': + description: A successful response. + schema: + type: object + properties: + minimum_gas_prices: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + DecCoin defines a token with a denomination and a decimal + amount. + + + NOTE: The amount field is an Dec which implements the custom + method + + signatures required by gogoproto. + description: |- + QueryMinimumGasPricesResponse is the response type for the + Query/MinimumGasPrices RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + /cosmos/evidence/v1beta1/evidence: + get: + summary: AllEvidence queries all evidence. + operationId: AllEvidence_ZM26C + responses: + '200': + description: A successful response. + schema: + type: object + properties: + evidence: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: evidence returns all evidences. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryAllEvidenceResponse is the response type for the + Query/AllEvidence RPC + + method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /cosmos/evidence/v1beta1/evidence/{evidence_hash}: + get: + summary: Evidence queries evidence based on evidence hash. + operationId: Evidence_2RMX9 + responses: + '200': + description: A successful response. + schema: + type: object + properties: + evidence: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: evidence returns the requested evidence. + description: >- + QueryEvidenceResponse is the response type for the Query/Evidence + RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: evidence_hash + description: evidence_hash defines the hash of the requested evidence. + in: path + required: true + type: string + format: byte + tags: + - gRPC Gateway API + /cosmos/base/node/v1beta1/config: + get: + summary: Config queries for the operator configuration. + operationId: Config_B18ME + responses: + '200': + description: A successful response. + schema: + type: object + properties: + minimum_gas_price: + type: string + description: >- + ConfigResponse defines the response structure for the Config gRPC + query. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + /cosmos/params/v1beta1/params: + get: + summary: |- + Params queries a specific parameter of a module, given its subspace and + key. + operationId: Params_9R7UX + responses: + '200': + description: A successful response. + schema: + type: object + properties: + param: + description: param defines the queried parameter. + type: object + properties: + subspace: + type: string + key: + type: string + value: + type: string + description: >- + QueryParamsResponse is response type for the Query/Params RPC + method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: subspace + description: subspace defines the module to query the parameter for. + in: query + required: false + type: string + - name: key + description: key defines the key of the parameter in the subspace. + in: query + required: false + type: string + tags: + - gRPC Gateway API + /cosmos/gov/v1beta1/params/{params_type}: + get: + summary: Params queries all parameters of the gov module. + operationId: Params_SZ6SI + responses: + '200': + description: A successful response. + schema: + type: object + properties: + voting_params: + description: voting_params defines the parameters related to voting. + type: object + properties: + voting_period: + type: string + description: Length of the voting period. + deposit_params: + description: deposit_params defines the parameters related to deposit. + type: object + properties: + min_deposit: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the + custom method + + signatures required by gogoproto. + description: Minimum deposit for a proposal to enter voting period. + max_deposit_period: + type: string + description: >- + Maximum period for Atom holders to deposit on a proposal. + Initial value: 2 + months. + tally_params: + description: tally_params defines the parameters related to tally. + type: object + properties: + quorum: + type: string + format: byte + description: >- + Minimum percentage of total stake needed to vote for a + result to be + considered valid. + threshold: + type: string + format: byte + description: >- + Minimum proportion of Yes votes for proposal to pass. + Default value: 0.5. + veto_threshold: + type: string + format: byte + description: >- + Minimum value of Veto votes to Total votes ratio for + proposal to be + vetoed. Default value: 1/3. + description: >- + QueryParamsResponse is the response type for the Query/Params RPC + method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: params_type + description: >- + params_type defines which parameters to query for, can be one of + "voting", + + "tallying" or "deposit". + in: path + required: true + type: string + tags: + - gRPC Gateway API + /cosmos/gov/v1beta1/proposals: + get: + summary: Proposals queries all proposals based on given status. + operationId: Proposals_VOWB2 + responses: + '200': + description: A successful response. + schema: + type: object + properties: + proposals: + type: array + items: + type: object + properties: + proposal_id: + type: string + format: uint64 + content: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + status: + type: string + enum: + - PROPOSAL_STATUS_UNSPECIFIED + - PROPOSAL_STATUS_DEPOSIT_PERIOD + - PROPOSAL_STATUS_VOTING_PERIOD + - PROPOSAL_STATUS_PASSED + - PROPOSAL_STATUS_REJECTED + - PROPOSAL_STATUS_FAILED + default: PROPOSAL_STATUS_UNSPECIFIED + description: >- + ProposalStatus enumerates the valid statuses of a + proposal. + + - PROPOSAL_STATUS_UNSPECIFIED: PROPOSAL_STATUS_UNSPECIFIED defines the default propopsal status. + - PROPOSAL_STATUS_DEPOSIT_PERIOD: PROPOSAL_STATUS_DEPOSIT_PERIOD defines a proposal status during the deposit + period. + - PROPOSAL_STATUS_VOTING_PERIOD: PROPOSAL_STATUS_VOTING_PERIOD defines a proposal status during the voting + period. + - PROPOSAL_STATUS_PASSED: PROPOSAL_STATUS_PASSED defines a proposal status of a proposal that has + passed. + - PROPOSAL_STATUS_REJECTED: PROPOSAL_STATUS_REJECTED defines a proposal status of a proposal that has + been rejected. + - PROPOSAL_STATUS_FAILED: PROPOSAL_STATUS_FAILED defines a proposal status of a proposal that has + failed. + final_tally_result: + type: object + properties: + 'yes': + type: string + abstain: + type: string + 'no': + type: string + no_with_veto: + type: string + description: >- + TallyResult defines a standard tally for a governance + proposal. + submit_time: + type: string + format: date-time + deposit_end_time: + type: string + format: date-time + total_deposit: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an + amount. + + + NOTE: The amount field is an Int which implements the + custom method + + signatures required by gogoproto. + voting_start_time: + type: string + format: date-time + voting_end_time: + type: string + format: date-time + description: >- + Proposal defines the core field members of a governance + proposal. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryProposalsResponse is the response type for the + Query/Proposals RPC + + method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: proposal_status + description: |- + proposal_status defines the status of the proposals. + + - PROPOSAL_STATUS_UNSPECIFIED: PROPOSAL_STATUS_UNSPECIFIED defines the default propopsal status. + - PROPOSAL_STATUS_DEPOSIT_PERIOD: PROPOSAL_STATUS_DEPOSIT_PERIOD defines a proposal status during the deposit + period. + - PROPOSAL_STATUS_VOTING_PERIOD: PROPOSAL_STATUS_VOTING_PERIOD defines a proposal status during the voting + period. + - PROPOSAL_STATUS_PASSED: PROPOSAL_STATUS_PASSED defines a proposal status of a proposal that has + passed. + - PROPOSAL_STATUS_REJECTED: PROPOSAL_STATUS_REJECTED defines a proposal status of a proposal that has + been rejected. + - PROPOSAL_STATUS_FAILED: PROPOSAL_STATUS_FAILED defines a proposal status of a proposal that has + failed. + in: query + required: false + type: string + enum: + - PROPOSAL_STATUS_UNSPECIFIED + - PROPOSAL_STATUS_DEPOSIT_PERIOD + - PROPOSAL_STATUS_VOTING_PERIOD + - PROPOSAL_STATUS_PASSED + - PROPOSAL_STATUS_REJECTED + - PROPOSAL_STATUS_FAILED + default: PROPOSAL_STATUS_UNSPECIFIED + - name: voter + description: voter defines the voter address for the proposals. + in: query + required: false + type: string + - name: depositor + description: depositor defines the deposit addresses from the proposals. + in: query + required: false + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /cosmos/gov/v1beta1/proposals/{proposal_id}: + get: + summary: Proposal queries proposal details based on ProposalID. + operationId: Proposal_76NCB + responses: + '200': + description: A successful response. + schema: + type: object + properties: + proposal: + type: object + properties: + proposal_id: + type: string + format: uint64 + content: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + status: + type: string + enum: + - PROPOSAL_STATUS_UNSPECIFIED + - PROPOSAL_STATUS_DEPOSIT_PERIOD + - PROPOSAL_STATUS_VOTING_PERIOD + - PROPOSAL_STATUS_PASSED + - PROPOSAL_STATUS_REJECTED + - PROPOSAL_STATUS_FAILED + default: PROPOSAL_STATUS_UNSPECIFIED + description: >- + ProposalStatus enumerates the valid statuses of a + proposal. + + - PROPOSAL_STATUS_UNSPECIFIED: PROPOSAL_STATUS_UNSPECIFIED defines the default propopsal status. + - PROPOSAL_STATUS_DEPOSIT_PERIOD: PROPOSAL_STATUS_DEPOSIT_PERIOD defines a proposal status during the deposit + period. + - PROPOSAL_STATUS_VOTING_PERIOD: PROPOSAL_STATUS_VOTING_PERIOD defines a proposal status during the voting + period. + - PROPOSAL_STATUS_PASSED: PROPOSAL_STATUS_PASSED defines a proposal status of a proposal that has + passed. + - PROPOSAL_STATUS_REJECTED: PROPOSAL_STATUS_REJECTED defines a proposal status of a proposal that has + been rejected. + - PROPOSAL_STATUS_FAILED: PROPOSAL_STATUS_FAILED defines a proposal status of a proposal that has + failed. + final_tally_result: + type: object + properties: + 'yes': + type: string + abstain: + type: string + 'no': + type: string + no_with_veto: + type: string + description: >- + TallyResult defines a standard tally for a governance + proposal. + submit_time: + type: string + format: date-time + deposit_end_time: + type: string + format: date-time + total_deposit: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the + custom method + + signatures required by gogoproto. + voting_start_time: + type: string + format: date-time + voting_end_time: + type: string + format: date-time + description: >- + Proposal defines the core field members of a governance + proposal. + description: >- + QueryProposalResponse is the response type for the Query/Proposal + RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: proposal_id + description: proposal_id defines the unique id of the proposal. + in: path + required: true + type: string + format: uint64 + tags: + - gRPC Gateway API + /cosmos/gov/v1beta1/proposals/{proposal_id}/deposits: + get: + summary: Deposits queries all deposits of a single proposal. + operationId: Deposits_9H9W1 + responses: + '200': + description: A successful response. + schema: + type: object + properties: + deposits: + type: array + items: + type: object + properties: + proposal_id: + type: string + format: uint64 + depositor: + type: string + amount: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an + amount. + + + NOTE: The amount field is an Int which implements the + custom method + + signatures required by gogoproto. + description: >- + Deposit defines an amount deposited by an account address to + an active + + proposal. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryDepositsResponse is the response type for the Query/Deposits + RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: proposal_id + description: proposal_id defines the unique id of the proposal. + in: path + required: true + type: string + format: uint64 + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /cosmos/gov/v1beta1/proposals/{proposal_id}/deposits/{depositor}: + get: + summary: >- + Deposit queries single deposit information based proposalID, + depositAddr. + operationId: Deposit_Q9ZCY + responses: + '200': + description: A successful response. + schema: + type: object + properties: + deposit: + type: object + properties: + proposal_id: + type: string + format: uint64 + depositor: + type: string + amount: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the + custom method + + signatures required by gogoproto. + description: >- + Deposit defines an amount deposited by an account address to + an active + + proposal. + description: >- + QueryDepositResponse is the response type for the Query/Deposit + RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: proposal_id + description: proposal_id defines the unique id of the proposal. + in: path + required: true + type: string + format: uint64 + - name: depositor + description: depositor defines the deposit addresses from the proposals. + in: path + required: true + type: string + tags: + - gRPC Gateway API + /cosmos/gov/v1beta1/proposals/{proposal_id}/tally: + get: + summary: TallyResult queries the tally of a proposal vote. + operationId: TallyResult_P38T1 + responses: + '200': + description: A successful response. + schema: + type: object + properties: + tally: + type: object + properties: + 'yes': + type: string + abstain: + type: string + 'no': + type: string + no_with_veto: + type: string + description: >- + TallyResult defines a standard tally for a governance + proposal. + description: >- + QueryTallyResultResponse is the response type for the Query/Tally + RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: proposal_id + description: proposal_id defines the unique id of the proposal. + in: path + required: true + type: string + format: uint64 + tags: + - gRPC Gateway API + /cosmos/gov/v1beta1/proposals/{proposal_id}/votes: + get: + summary: Votes queries votes of a given proposal. + operationId: Votes_K1AD6 + responses: + '200': + description: A successful response. + schema: + type: object + properties: + votes: + type: array + items: + type: object + properties: + proposal_id: + type: string + format: uint64 + voter: + type: string + option: + description: >- + Deprecated: Prefer to use `options` instead. This field + is set in queries + + if and only if `len(options) == 1` and that option has + weight 1. In all + + other cases, this field will default to + VOTE_OPTION_UNSPECIFIED. + type: string + enum: + - VOTE_OPTION_UNSPECIFIED + - VOTE_OPTION_YES + - VOTE_OPTION_ABSTAIN + - VOTE_OPTION_NO + - VOTE_OPTION_NO_WITH_VETO + default: VOTE_OPTION_UNSPECIFIED + options: + type: array + items: + type: object + properties: + option: + type: string + enum: + - VOTE_OPTION_UNSPECIFIED + - VOTE_OPTION_YES + - VOTE_OPTION_ABSTAIN + - VOTE_OPTION_NO + - VOTE_OPTION_NO_WITH_VETO + default: VOTE_OPTION_UNSPECIFIED + description: >- + VoteOption enumerates the valid vote options for a + given governance proposal. + + - VOTE_OPTION_UNSPECIFIED: VOTE_OPTION_UNSPECIFIED defines a no-op vote option. + - VOTE_OPTION_YES: VOTE_OPTION_YES defines a yes vote option. + - VOTE_OPTION_ABSTAIN: VOTE_OPTION_ABSTAIN defines an abstain vote option. + - VOTE_OPTION_NO: VOTE_OPTION_NO defines a no vote option. + - VOTE_OPTION_NO_WITH_VETO: VOTE_OPTION_NO_WITH_VETO defines a no with veto vote option. + weight: + type: string + description: >- + WeightedVoteOption defines a unit of vote for vote + split. + + + Since: cosmos-sdk 0.43 + title: 'Since: cosmos-sdk 0.43' + description: >- + Vote defines a vote on a governance proposal. + + A Vote consists of a proposal ID, the voter, and the vote + option. + description: votes defined the queried votes. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryVotesResponse is the response type for the Query/Votes RPC + method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: proposal_id + description: proposal_id defines the unique id of the proposal. + in: path + required: true + type: string + format: uint64 + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /cosmos/gov/v1beta1/proposals/{proposal_id}/votes/{voter}: + get: + summary: Vote queries voted information based on proposalID, voterAddr. + operationId: Vote_ELJSA + responses: + '200': + description: A successful response. + schema: + type: object + properties: + vote: + type: object + properties: + proposal_id: + type: string + format: uint64 + voter: + type: string + option: + description: >- + Deprecated: Prefer to use `options` instead. This field is + set in queries + + if and only if `len(options) == 1` and that option has + weight 1. In all + + other cases, this field will default to + VOTE_OPTION_UNSPECIFIED. + type: string + enum: + - VOTE_OPTION_UNSPECIFIED + - VOTE_OPTION_YES + - VOTE_OPTION_ABSTAIN + - VOTE_OPTION_NO + - VOTE_OPTION_NO_WITH_VETO + default: VOTE_OPTION_UNSPECIFIED + options: + type: array + items: + type: object + properties: + option: + type: string + enum: + - VOTE_OPTION_UNSPECIFIED + - VOTE_OPTION_YES + - VOTE_OPTION_ABSTAIN + - VOTE_OPTION_NO + - VOTE_OPTION_NO_WITH_VETO + default: VOTE_OPTION_UNSPECIFIED + description: >- + VoteOption enumerates the valid vote options for a + given governance proposal. + + - VOTE_OPTION_UNSPECIFIED: VOTE_OPTION_UNSPECIFIED defines a no-op vote option. + - VOTE_OPTION_YES: VOTE_OPTION_YES defines a yes vote option. + - VOTE_OPTION_ABSTAIN: VOTE_OPTION_ABSTAIN defines an abstain vote option. + - VOTE_OPTION_NO: VOTE_OPTION_NO defines a no vote option. + - VOTE_OPTION_NO_WITH_VETO: VOTE_OPTION_NO_WITH_VETO defines a no with veto vote option. + weight: + type: string + description: >- + WeightedVoteOption defines a unit of vote for vote + split. + + + Since: cosmos-sdk 0.43 + title: 'Since: cosmos-sdk 0.43' + description: >- + Vote defines a vote on a governance proposal. + + A Vote consists of a proposal ID, the voter, and the vote + option. + description: >- + QueryVoteResponse is the response type for the Query/Vote RPC + method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: proposal_id + description: proposal_id defines the unique id of the proposal. + in: path + required: true + type: string + format: uint64 + - name: voter + description: voter defines the oter address for the proposals. + in: path + required: true + type: string + tags: + - gRPC Gateway API + /juno/feeshare/v1/fee_shares: + get: + summary: FeeShares retrieves all registered FeeShares + operationId: FeeShares_ARVUM + responses: + '200': + description: A successful response. + schema: + type: object + properties: + feeshare: + type: array + items: + type: object + properties: + contract_address: + type: string + title: >- + contract_address is the bech32 address of a registered + contract in string + + form + deployer_address: + type: string + description: >- + deployer_address is the bech32 address of message + sender. It must be the + + same as the contracts admin address. + withdrawer_address: + type: string + description: >- + withdrawer_address is the bech32 address of account + receiving the + + transaction fees. + title: >- + FeeShare defines an instance that organizes fee distribution + conditions for + + the owner of a given smart contract + title: FeeShare is a slice of all stored Reveneue + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryFeeSharesResponse is the response type for the + Query/FeeShares RPC + + method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /juno/feeshare/v1/fee_shares/{contract_address}: + get: + summary: FeeShare retrieves a registered FeeShare for a given contract address + operationId: FeeShare_0EHGG + responses: + '200': + description: A successful response. + schema: + type: object + properties: + feeshare: + type: object + properties: + contract_address: + type: string + title: >- + contract_address is the bech32 address of a registered + contract in string + + form + deployer_address: + type: string + description: >- + deployer_address is the bech32 address of message sender. + It must be the + + same as the contracts admin address. + withdrawer_address: + type: string + description: >- + withdrawer_address is the bech32 address of account + receiving the + + transaction fees. + title: >- + FeeShare defines an instance that organizes fee distribution + conditions for + + the owner of a given smart contract + description: >- + QueryFeeShareResponse is the response type for the Query/FeeShare + RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: contract_address + description: contract_address of a registered contract in bech32 format + in: path + required: true + type: string + tags: + - gRPC Gateway API + /juno/feeshare/v1/fee_shares/{deployer_address}: + get: + summary: |- + DeployerFeeShares retrieves all FeeShares that a given deployer has + registered + operationId: DeployerFeeShares_HNW3B + responses: + '200': + description: A successful response. + schema: + type: object + properties: + contract_addresses: + type: array + items: + type: string + title: >- + contract_addresses is the slice of registered contract + addresses for a + + deployer + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + QueryDeployerFeeSharesResponse is the response type for the + Query/DeployerFeeShares RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: deployer_address + description: deployer_address in bech32 format + in: path + required: true + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /juno/feeshare/v1/fee_shares/{withdrawer_address}: + get: + summary: |- + WithdrawerFeeShares retrieves all FeeShares with a given withdrawer + address + operationId: WithdrawerFeeShares_CYI66 + responses: + '200': + description: A successful response. + schema: + type: object + properties: + contract_addresses: + type: array + items: + type: string + title: >- + contract_addresses is the slice of registered contract + addresses for a + + withdrawer + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + QueryWithdrawerFeeSharesResponse is the response type for the + Query/WithdrawerFeeShares RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: withdrawer_address + description: withdrawer_address in bech32 format + in: path + required: true + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /juno/feeshare/v1/params: + get: + summary: Params retrieves the FeeShare module params + operationId: Params_4OI6Q + responses: + '200': + description: A successful response. + schema: + type: object + properties: + params: + title: params is the returned FeeShare parameter + type: object + properties: + enable_fee_share: + type: boolean + title: >- + enable_feeshare defines a parameter to enable the feeshare + module + developer_shares: + type: string + title: >- + developer_shares defines the proportion of the transaction + fees to be + + distributed to the registered contract owner + allowed_denoms: + type: array + items: + type: string + description: >- + allowed_denoms defines the list of denoms that are allowed + to be paid to + + the contract withdraw addresses. If said denom is not in + the list, the fees + + will ONLY be sent to the community pool. + + If this list is empty, all denoms are allowed. + description: >- + QueryParamsResponse is the response type for the Query/Params RPC + method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + /cosmos/slashing/v1beta1/params: + get: + summary: Params queries the parameters of slashing module + operationId: Params_EP1KV + responses: + '200': + description: A successful response. + schema: + type: object + properties: + params: + type: object + properties: + signed_blocks_window: + type: string + format: int64 + min_signed_per_window: + type: string + format: byte + downtime_jail_duration: + type: string + slash_fraction_double_sign: + type: string + format: byte + slash_fraction_downtime: + type: string + format: byte + description: >- + Params represents the parameters used for by the slashing + module. + title: >- + QueryParamsResponse is the response type for the Query/Params RPC + method + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + /cosmos/slashing/v1beta1/signing_infos: + get: + summary: SigningInfos queries signing info of all validators + operationId: SigningInfos_TR6NI + responses: + '200': + description: A successful response. + schema: + type: object + properties: + info: + type: array + items: + type: object + properties: + address: + type: string + start_height: + type: string + format: int64 + title: >- + Height at which validator was first a candidate OR was + unjailed + index_offset: + type: string + format: int64 + description: >- + Index which is incremented each time the validator was a + bonded + + in a block and may have signed a precommit or not. This + in conjunction with the + + `SignedBlocksWindow` param determines the index in the + `MissedBlocksBitArray`. + jailed_until: + type: string + format: date-time + description: >- + Timestamp until which the validator is jailed due to + liveness downtime. + tombstoned: + type: boolean + description: >- + Whether or not a validator has been tombstoned (killed + out of validator set). It is set + + once the validator commits an equivocation or for any + other configured misbehiavor. + missed_blocks_counter: + type: string + format: int64 + description: >- + A counter kept to avoid unnecessary array reads. + + Note that `Sum(MissedBlocksBitArray)` always equals + `MissedBlocksCounter`. + description: >- + ValidatorSigningInfo defines a validator's signing info for + monitoring their + + liveness activity. + title: info is the signing info of all validators + pagination: + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + PageResponse is to be embedded in gRPC response messages where + the + + corresponding request message has used PageRequest. + + message SomeResponse { + repeated Bar results = 1; + PageResponse page = 2; + } + title: >- + QuerySigningInfosResponse is the response type for the + Query/SigningInfos RPC + + method + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /cosmos/slashing/v1beta1/signing_infos/{cons_address}: + get: + summary: SigningInfo queries the signing info of given cons address + operationId: SigningInfo_8QMFV + responses: + '200': + description: A successful response. + schema: + type: object + properties: + val_signing_info: + type: object + properties: + address: + type: string + start_height: + type: string + format: int64 + title: >- + Height at which validator was first a candidate OR was + unjailed + index_offset: + type: string + format: int64 + description: >- + Index which is incremented each time the validator was a + bonded + + in a block and may have signed a precommit or not. This in + conjunction with the + + `SignedBlocksWindow` param determines the index in the + `MissedBlocksBitArray`. + jailed_until: + type: string + format: date-time + description: >- + Timestamp until which the validator is jailed due to + liveness downtime. + tombstoned: + type: boolean + description: >- + Whether or not a validator has been tombstoned (killed out + of validator set). It is set + + once the validator commits an equivocation or for any + other configured misbehiavor. + missed_blocks_counter: + type: string + format: int64 + description: >- + A counter kept to avoid unnecessary array reads. + + Note that `Sum(MissedBlocksBitArray)` always equals + `MissedBlocksCounter`. + description: >- + ValidatorSigningInfo defines a validator's signing info for + monitoring their + + liveness activity. + title: >- + val_signing_info is the signing info of requested val cons + address + title: >- + QuerySigningInfoResponse is the response type for the + Query/SigningInfo RPC + + method + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: cons_address + description: cons_address is the address to query signing info of + in: path + required: true + type: string + tags: + - gRPC Gateway API + /cosmos/upgrade/v1beta1/applied_plan/{name}: + get: + summary: AppliedPlan queries a previously applied upgrade plan by its name. + operationId: AppliedPlan_4G511 + responses: + '200': + description: A successful response. + schema: + type: object + properties: + height: + type: string + format: int64 + description: height is the block height at which the plan was applied. + description: >- + QueryAppliedPlanResponse is the response type for the + Query/AppliedPlan RPC + + method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: name + description: name is the name of the applied plan to query for. + in: path + required: true + type: string + tags: + - gRPC Gateway API + /cosmos/upgrade/v1beta1/current_plan: + get: + summary: CurrentPlan queries the current upgrade plan. + operationId: CurrentPlan_EEL3L + responses: + '200': + description: A successful response. + schema: + type: object + properties: + plan: + description: plan is the current upgrade plan. + type: object + properties: + name: + type: string + description: >- + Sets the name for the upgrade. This name will be used by + the upgraded + + version of the software to apply any special "on-upgrade" + commands during + + the first BeginBlock method after the upgrade is applied. + It is also used + + to detect whether a software version can handle a given + upgrade. If no + + upgrade handler with this name has been set in the + software, it will be + + assumed that the software is out-of-date when the upgrade + Time or Height is + + reached and the software will exit. + time: + type: string + format: date-time + description: >- + Deprecated: Time based upgrades have been deprecated. Time + based upgrade logic + + has been removed from the SDK. + + If this field is not empty, an error will be thrown. + height: + type: string + format: int64 + description: |- + The height at which the upgrade must be performed. + Only used if Time is not set. + info: + type: string + title: >- + Any application specific upgrade info to be included + on-chain + + such as a git commit that validators could automatically + upgrade to + upgraded_client_state: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + Deprecated: UpgradedClientState field has been deprecated. + IBC upgrade logic has been + + moved to the IBC module in the sub module 02-client. + + If this field is not empty, an error will be thrown. + description: >- + QueryCurrentPlanResponse is the response type for the + Query/CurrentPlan RPC + + method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + /cosmos/upgrade/v1beta1/module_versions: + get: + summary: ModuleVersions queries the list of module versions from state. + description: 'Since: cosmos-sdk 0.43' + operationId: ModuleVersions_PJ2IL + responses: + '200': + description: A successful response. + schema: + type: object + properties: + module_versions: + type: array + items: + type: object + properties: + name: + type: string + title: name of the app module + version: + type: string + format: uint64 + title: consensus version of the app module + description: |- + ModuleVersion specifies a module and its consensus version. + + Since: cosmos-sdk 0.43 + description: >- + module_versions is a list of module names with their consensus + versions. + description: >- + QueryModuleVersionsResponse is the response type for the + Query/ModuleVersions + + RPC method. + + + Since: cosmos-sdk 0.43 + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: module_name + description: |- + module_name is a field to query a specific module + consensus version from state. Leaving this empty will + fetch the full list of module versions from state. + in: query + required: false + type: string + tags: + - gRPC Gateway API + /cosmos/upgrade/v1beta1/upgraded_consensus_state/{last_height}: + get: + summary: >- + UpgradedConsensusState queries the consensus state that will serve + + as a trusted kernel for the next version of this chain. It will only be + + stored at the last height of this chain. + + UpgradedConsensusState RPC not supported with legacy querier + + This rpc is deprecated now that IBC has its own replacement + + (https://github.com/cosmos/ibc-go/blob/2c880a22e9f9cc75f62b527ca94aa75ce1106001/proto/ibc/core/client/v1/query.proto#L54) + operationId: UpgradedConsensusState_NHBES + responses: + '200': + description: A successful response. + schema: + type: object + properties: + upgraded_consensus_state: + type: string + format: byte + title: 'Since: cosmos-sdk 0.43' + description: >- + QueryUpgradedConsensusStateResponse is the response type for the + Query/UpgradedConsensusState + + RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: last_height + description: |- + last height of the current chain must be sent in request + as this is the height under which next consensus state is stored + in: path + required: true + type: string + format: int64 + tags: + - gRPC Gateway API + /cosmos/authz/v1beta1/grants: + get: + summary: Returns list of `Authorization`, granted to the grantee by the granter. + operationId: Grants_0MX8R + responses: + '200': + description: A successful response. + schema: + type: object + properties: + grants: + type: array + items: + type: object + properties: + authorization: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + expiration: + type: string + format: date-time + description: |- + Grant gives permissions to execute + the provide method with expiration time. + description: >- + authorizations is a list of grants granted for grantee by + granter. + pagination: + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + PageResponse is to be embedded in gRPC response messages where + the + + corresponding request message has used PageRequest. + + message SomeResponse { + repeated Bar results = 1; + PageResponse page = 2; + } + description: >- + QueryGrantsResponse is the response type for the + Query/Authorizations RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: granter + in: query + required: false + type: string + - name: grantee + in: query + required: false + type: string + - name: msg_type_url + description: >- + Optional, msg_type_url, when set, will query only grants matching + given msg type. + in: query + required: false + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /cosmos/authz/v1beta1/grants/grantee/{grantee}: + get: + summary: GranteeGrants returns a list of `GrantAuthorization` by grantee. + description: 'Since: cosmos-sdk 0.45.2' + operationId: GranteeGrants_8IKJS + responses: + '200': + description: A successful response. + schema: + type: object + properties: + grants: + type: array + items: + type: object + properties: + granter: + type: string + grantee: + type: string + authorization: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + expiration: + type: string + format: date-time + description: 'Since: cosmos-sdk 0.45.2' + title: >- + GrantAuthorization extends a grant with both the addresses + of the grantee and granter. + + It is used in genesis.proto and query.proto + description: grants is a list of grants granted to the grantee. + pagination: + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + PageResponse is to be embedded in gRPC response messages where + the + + corresponding request message has used PageRequest. + + message SomeResponse { + repeated Bar results = 1; + PageResponse page = 2; + } + description: >- + QueryGranteeGrantsResponse is the response type for the + Query/GranteeGrants RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: grantee + in: path + required: true + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /cosmos/authz/v1beta1/grants/granter/{granter}: + get: + summary: GranterGrants returns list of `GrantAuthorization`, granted by granter. + description: 'Since: cosmos-sdk 0.45.2' + operationId: GranterGrants_NWMPX + responses: + '200': + description: A successful response. + schema: + type: object + properties: + grants: + type: array + items: + type: object + properties: + granter: + type: string + grantee: + type: string + authorization: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + expiration: + type: string + format: date-time + description: 'Since: cosmos-sdk 0.45.2' + title: >- + GrantAuthorization extends a grant with both the addresses + of the grantee and granter. + + It is used in genesis.proto and query.proto + description: grants is a list of grants granted by the granter. + pagination: + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + PageResponse is to be embedded in gRPC response messages where + the + + corresponding request message has used PageRequest. + + message SomeResponse { + repeated Bar results = 1; + PageResponse page = 2; + } + description: >- + QueryGranterGrantsResponse is the response type for the + Query/GranterGrants RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: granter + in: path + required: true + type: string + - name: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - gRPC Gateway API + /cosmos/mint/v1beta1/annual_provisions: + get: + summary: AnnualProvisions current minting annual provisions value. + operationId: AnnualProvisions_WMS1W + responses: + '200': + description: A successful response. + schema: + type: object + properties: + annual_provisions: + type: string + format: byte + description: >- + annual_provisions is the current minting annual provisions + value. + description: |- + QueryAnnualProvisionsResponse is the response type for the + Query/AnnualProvisions RPC method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + /cosmos/mint/v1beta1/inflation: + get: + summary: Inflation returns the current minting inflation value. + operationId: Inflation_SI7I6 + responses: + '200': + description: A successful response. + schema: + type: object + properties: + inflation: + type: string + format: byte + description: inflation is the current minting inflation value. + description: >- + QueryInflationResponse is the response type for the + Query/Inflation RPC + + method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API + /cosmos/mint/v1beta1/params: + get: + summary: Params returns the total set of minting parameters. + operationId: Params_H9W1T + responses: + '200': + description: A successful response. + schema: + type: object + properties: + params: + description: params defines the parameters of the module. + type: object + properties: + mint_denom: + type: string + title: type of coin to mint + blocks_per_year: + type: string + format: uint64 + title: expected blocks per year + description: >- + QueryParamsResponse is the response type for the Query/Params RPC + method. + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + tags: + - gRPC Gateway API +definitions: + cosmos.auth.v1beta1.Params: + type: object + properties: + max_memo_characters: + type: string + format: uint64 + tx_sig_limit: + type: string + format: uint64 + tx_size_cost_per_byte: + type: string + format: uint64 + sig_verify_cost_ed25519: + type: string + format: uint64 + sig_verify_cost_secp256k1: + type: string + format: uint64 + description: Params defines the parameters for the auth module. + cosmos.auth.v1beta1.QueryAccountResponse: + type: object + properties: + account: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: account defines the account of the corresponding address. + description: >- + QueryAccountResponse is the response type for the Query/Account RPC + method. + cosmos.auth.v1beta1.QueryAccountsResponse: + type: object + properties: + accounts: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: accounts are the existing accounts + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryAccountsResponse is the response type for the Query/Accounts RPC + method. + + + Since: cosmos-sdk 0.43 + cosmos.auth.v1beta1.QueryModuleAccountByNameResponse: + type: object + properties: + account: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + QueryModuleAccountByNameResponse is the response type for the + Query/ModuleAccountByName RPC method. + cosmos.auth.v1beta1.QueryParamsResponse: + type: object + properties: + params: + description: params defines the parameters of the module. + type: object + properties: + max_memo_characters: + type: string + format: uint64 + tx_sig_limit: + type: string + format: uint64 + tx_size_cost_per_byte: + type: string + format: uint64 + sig_verify_cost_ed25519: + type: string + format: uint64 + sig_verify_cost_secp256k1: + type: string + format: uint64 + description: QueryParamsResponse is the response type for the Query/Params RPC method. + cosmos.base.query.v1beta1.PageRequest: + type: object + properties: + key: + type: string + format: byte + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + offset: + type: string + format: uint64 + description: |- + offset is a numeric offset that can be used when key is unavailable. + It is less efficient than using key. Only one of offset or key should + be set. + limit: + type: string + format: uint64 + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + count_total: + type: boolean + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in UIs. + + count_total is only respected when offset is used. It is ignored when + key + + is set. + reverse: + type: boolean + description: >- + reverse is set to true if results are to be returned in the descending + order. + + + Since: cosmos-sdk 0.43 + description: |- + message SomeRequest { + Foo some_parameter = 1; + PageRequest pagination = 2; + } + title: |- + PageRequest is to be embedded in gRPC request messages for efficient + pagination. Ex: + cosmos.base.query.v1beta1.PageResponse: + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: |- + total is total number of results available if PageRequest.count_total + was set, its value is undefined otherwise + description: |- + PageResponse is to be embedded in gRPC response messages where the + corresponding request message has used PageRequest. + + message SomeResponse { + repeated Bar results = 1; + PageResponse page = 2; + } + google.protobuf.Any: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + grpc.gateway.runtime.Error: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + cosmos.bank.v1beta1.DenomUnit: + type: object + properties: + denom: + type: string + description: denom represents the string name of the given denom unit (e.g uatom). + exponent: + type: integer + format: int64 + description: >- + 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). + aliases: + type: array + items: + type: string + title: aliases is a list of string aliases for the given denom + description: |- + DenomUnit represents a struct that describes a given + denomination unit of the basic token. + cosmos.bank.v1beta1.Metadata: + type: object + properties: + description: + type: string + denom_units: + type: array + items: + type: object + properties: + denom: + type: string + description: >- + denom represents the string name of the given denom unit (e.g + uatom). + exponent: + type: integer + format: int64 + description: >- + 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). + aliases: + type: array + items: + type: string + title: aliases is a list of string aliases for the given denom + description: |- + DenomUnit represents a struct that describes a given + denomination unit of the basic token. + title: denom_units represents the list of DenomUnit's for a given coin + base: + type: string + description: >- + base represents the base denom (should be the DenomUnit with exponent + = 0). + display: + type: string + description: |- + display indicates the suggested denom that should be + displayed in clients. + name: + type: string + description: 'Since: cosmos-sdk 0.43' + title: 'name defines the name of the token (eg: Cosmos Atom)' + symbol: + type: string + description: >- + symbol is the token symbol usually shown on exchanges (eg: ATOM). This + can + + be the same as the display. + + + Since: cosmos-sdk 0.43 + description: |- + Metadata represents a struct that describes + a basic token. + cosmos.bank.v1beta1.Params: + type: object + properties: + send_enabled: + type: array + items: + type: object + properties: + denom: + type: string + enabled: + type: boolean + description: >- + SendEnabled maps coin denom to a send_enabled status (whether a + denom is + + sendable). + default_send_enabled: + type: boolean + description: Params defines the parameters for the bank module. + cosmos.bank.v1beta1.QueryAllBalancesResponse: + type: object + properties: + balances: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: |- + Coin defines a token with a denomination and an amount. + + NOTE: The amount field is an Int which implements the custom method + signatures required by gogoproto. + description: balances is the balances of all the coins. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryAllBalancesResponse is the response type for the Query/AllBalances + RPC + + method. + cosmos.bank.v1beta1.QueryBalanceResponse: + type: object + properties: + balance: + type: object + properties: + denom: + type: string + amount: + type: string + description: |- + Coin defines a token with a denomination and an amount. + + NOTE: The amount field is an Int which implements the custom method + signatures required by gogoproto. + description: >- + QueryBalanceResponse is the response type for the Query/Balance RPC + method. + cosmos.bank.v1beta1.QueryDenomMetadataResponse: + type: object + properties: + metadata: + type: object + properties: + description: + type: string + denom_units: + type: array + items: + type: object + properties: + denom: + type: string + description: >- + denom represents the string name of the given denom unit + (e.g uatom). + exponent: + type: integer + format: int64 + description: >- + 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). + aliases: + type: array + items: + type: string + title: aliases is a list of string aliases for the given denom + description: |- + DenomUnit represents a struct that describes a given + denomination unit of the basic token. + title: denom_units represents the list of DenomUnit's for a given coin + base: + type: string + description: >- + base represents the base denom (should be the DenomUnit with + exponent = 0). + display: + type: string + description: |- + display indicates the suggested denom that should be + displayed in clients. + name: + type: string + description: 'Since: cosmos-sdk 0.43' + title: 'name defines the name of the token (eg: Cosmos Atom)' + symbol: + type: string + description: >- + symbol is the token symbol usually shown on exchanges (eg: ATOM). + This can + + be the same as the display. + + + Since: cosmos-sdk 0.43 + description: |- + Metadata represents a struct that describes + a basic token. + description: >- + QueryDenomMetadataResponse is the response type for the + Query/DenomMetadata RPC + + method. + cosmos.bank.v1beta1.QueryDenomsMetadataResponse: + type: object + properties: + metadatas: + type: array + items: + type: object + properties: + description: + type: string + denom_units: + type: array + items: + type: object + properties: + denom: + type: string + description: >- + denom represents the string name of the given denom unit + (e.g uatom). + exponent: + type: integer + format: int64 + description: >- + 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). + aliases: + type: array + items: + type: string + title: aliases is a list of string aliases for the given denom + description: |- + DenomUnit represents a struct that describes a given + denomination unit of the basic token. + title: denom_units represents the list of DenomUnit's for a given coin + base: + type: string + description: >- + base represents the base denom (should be the DenomUnit with + exponent = 0). + display: + type: string + description: |- + display indicates the suggested denom that should be + displayed in clients. + name: + type: string + description: 'Since: cosmos-sdk 0.43' + title: 'name defines the name of the token (eg: Cosmos Atom)' + symbol: + type: string + description: >- + symbol is the token symbol usually shown on exchanges (eg: + ATOM). This can + + be the same as the display. + + + Since: cosmos-sdk 0.43 + description: |- + Metadata represents a struct that describes + a basic token. + description: >- + metadata provides the client information for all the registered + tokens. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryDenomsMetadataResponse is the response type for the + Query/DenomsMetadata RPC + + method. + cosmos.bank.v1beta1.QueryParamsResponse: + type: object + properties: + params: + type: object + properties: + send_enabled: + type: array + items: + type: object + properties: + denom: + type: string + enabled: + type: boolean + description: >- + SendEnabled maps coin denom to a send_enabled status (whether a + denom is + + sendable). + default_send_enabled: + type: boolean + description: Params defines the parameters for the bank module. + description: >- + QueryParamsResponse defines the response type for querying x/bank + parameters. + cosmos.bank.v1beta1.QuerySpendableBalancesResponse: + type: object + properties: + balances: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: |- + Coin defines a token with a denomination and an amount. + + NOTE: The amount field is an Int which implements the custom method + signatures required by gogoproto. + description: balances is the spendable balances of all the coins. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QuerySpendableBalancesResponse defines the gRPC response structure for + querying + + an account's spendable balances. + cosmos.bank.v1beta1.QuerySupplyOfResponse: + type: object + properties: + amount: + type: object + properties: + denom: + type: string + amount: + type: string + description: |- + Coin defines a token with a denomination and an amount. + + NOTE: The amount field is an Int which implements the custom method + signatures required by gogoproto. + description: >- + QuerySupplyOfResponse is the response type for the Query/SupplyOf RPC + method. + cosmos.bank.v1beta1.QueryTotalSupplyResponse: + type: object + properties: + supply: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: |- + Coin defines a token with a denomination and an amount. + + NOTE: The amount field is an Int which implements the custom method + signatures required by gogoproto. + title: supply is the supply of the coins + pagination: + description: |- + pagination defines the pagination in the response. + + Since: cosmos-sdk 0.43 + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + title: >- + QueryTotalSupplyResponse is the response type for the Query/TotalSupply + RPC + + method + cosmos.bank.v1beta1.SendEnabled: + type: object + properties: + denom: + type: string + enabled: + type: boolean + description: |- + SendEnabled maps coin denom to a send_enabled status (whether a denom is + sendable). + cosmos.base.v1beta1.Coin: + type: object + properties: + denom: + type: string + amount: + type: string + description: |- + Coin defines a token with a denomination and an amount. + + NOTE: The amount field is an Int which implements the custom method + signatures required by gogoproto. + cosmos.staking.v1beta1.BondStatus: + type: string + enum: + - BOND_STATUS_UNSPECIFIED + - BOND_STATUS_UNBONDED + - BOND_STATUS_UNBONDING + - BOND_STATUS_BONDED + default: BOND_STATUS_UNSPECIFIED + description: |- + BondStatus is the status of a validator. + + - BOND_STATUS_UNSPECIFIED: UNSPECIFIED defines an invalid validator status. + - BOND_STATUS_UNBONDED: UNBONDED defines a validator that is not bonded. + - BOND_STATUS_UNBONDING: UNBONDING defines a validator that is unbonding. + - BOND_STATUS_BONDED: BONDED defines a validator that is bonded. + cosmos.staking.v1beta1.Commission: + type: object + properties: + commission_rates: + description: >- + commission_rates defines the initial commission rates to be used for + creating a validator. + type: object + properties: + rate: + type: string + description: rate is the commission rate charged to delegators, as a fraction. + max_rate: + type: string + description: >- + max_rate defines the maximum commission rate which validator can + ever charge, as a fraction. + max_change_rate: + type: string + description: >- + max_change_rate defines the maximum daily increase of the + validator commission, as a fraction. + update_time: + type: string + format: date-time + description: update_time is the last time the commission rate was changed. + description: Commission defines commission parameters for a given validator. + cosmos.staking.v1beta1.CommissionRates: + type: object + properties: + rate: + type: string + description: rate is the commission rate charged to delegators, as a fraction. + max_rate: + type: string + description: >- + max_rate defines the maximum commission rate which validator can ever + charge, as a fraction. + max_change_rate: + type: string + description: >- + max_change_rate defines the maximum daily increase of the validator + commission, as a fraction. + description: >- + CommissionRates defines the initial commission rates to be used for + creating + + a validator. + cosmos.staking.v1beta1.Delegation: + type: object + properties: + delegator_address: + type: string + description: delegator_address is the bech32-encoded address of the delegator. + validator_address: + type: string + description: validator_address is the bech32-encoded address of the validator. + shares: + type: string + description: shares define the delegation shares received. + description: |- + Delegation represents the bond with tokens held by an account. It is + owned by one delegator, and is associated with the voting power of one + validator. + cosmos.staking.v1beta1.DelegationResponse: + type: object + properties: + delegation: + type: object + properties: + delegator_address: + type: string + description: delegator_address is the bech32-encoded address of the delegator. + validator_address: + type: string + description: validator_address is the bech32-encoded address of the validator. + shares: + type: string + description: shares define the delegation shares received. + description: |- + Delegation represents the bond with tokens held by an account. It is + owned by one delegator, and is associated with the voting power of one + validator. + balance: + type: object + properties: + denom: + type: string + amount: + type: string + description: |- + Coin defines a token with a denomination and an amount. + + NOTE: The amount field is an Int which implements the custom method + signatures required by gogoproto. + description: |- + DelegationResponse is equivalent to Delegation except that it contains a + balance in addition to shares which is more suitable for client responses. + cosmos.staking.v1beta1.Description: + type: object + properties: + moniker: + type: string + description: moniker defines a human-readable name for the validator. + identity: + type: string + description: >- + identity defines an optional identity signature (ex. UPort or + Keybase). + website: + type: string + description: website defines an optional website link. + security_contact: + type: string + description: security_contact defines an optional email for security contact. + details: + type: string + description: details define other optional details. + description: Description defines a validator description. + cosmos.staking.v1beta1.HistoricalInfo: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for processing a block in + the blockchain, + + including all blockchain data structures and the rules of the + application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + valset: + type: array + items: + type: object + properties: + operator_address: + type: string + description: >- + operator_address defines the address of the validator's + operator; bech encoded in JSON. + consensus_pubkey: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + consensus_pubkey is the consensus public key of the validator, + as a Protobuf Any. + jailed: + type: boolean + description: >- + jailed defined whether the validator has been jailed from bonded + status or not. + status: + description: status is the validator status (bonded/unbonding/unbonded). + type: string + enum: + - BOND_STATUS_UNSPECIFIED + - BOND_STATUS_UNBONDED + - BOND_STATUS_UNBONDING + - BOND_STATUS_BONDED + default: BOND_STATUS_UNSPECIFIED + tokens: + type: string + description: tokens define the delegated tokens (incl. self-delegation). + delegator_shares: + type: string + description: >- + delegator_shares defines total shares issued to a validator's + delegators. + description: + description: description defines the description terms for the validator. + type: object + properties: + moniker: + type: string + description: moniker defines a human-readable name for the validator. + identity: + type: string + description: >- + identity defines an optional identity signature (ex. UPort + or Keybase). + website: + type: string + description: website defines an optional website link. + security_contact: + type: string + description: >- + security_contact defines an optional email for security + contact. + details: + type: string + description: details define other optional details. + unbonding_height: + type: string + format: int64 + description: >- + unbonding_height defines, if unbonding, the height at which this + validator has begun unbonding. + unbonding_time: + type: string + format: date-time + description: >- + unbonding_time defines, if unbonding, the min time for the + validator to complete unbonding. + commission: + description: commission defines the commission parameters. + type: object + properties: + commission_rates: + description: >- + commission_rates defines the initial commission rates to be + used for creating a validator. + type: object + properties: + rate: + type: string + description: >- + rate is the commission rate charged to delegators, as a + fraction. + max_rate: + type: string + description: >- + max_rate defines the maximum commission rate which + validator can ever charge, as a fraction. + max_change_rate: + type: string + description: >- + max_change_rate defines the maximum daily increase of + the validator commission, as a fraction. + update_time: + type: string + format: date-time + description: >- + update_time is the last time the commission rate was + changed. + min_self_delegation: + type: string + description: >- + min_self_delegation is the validator's self declared minimum + self delegation. + description: >- + Validator defines a validator, together with the total amount of the + + Validator's bond shares and their exchange rate to coins. Slashing + results in + + a decrease in the exchange rate, allowing correct calculation of + future + + undelegations without iterating over delegators. When coins are + delegated to + + this validator, the validator is credited with a delegation whose + number of + + bond shares is based on the amount of coins delegated divided by the + current + + exchange rate. Voting power can be calculated as total bonded shares + + multiplied by exchange rate. + description: >- + HistoricalInfo contains header and validator information for a given + block. + + It is stored as part of staking module's state, which persists the `n` + most + + recent HistoricalInfo + + (`n` is set by the staking module's `historical_entries` parameter). + cosmos.staking.v1beta1.Params: + type: object + properties: + unbonding_time: + type: string + description: unbonding_time is the time duration of unbonding. + max_validators: + type: integer + format: int64 + description: max_validators is the maximum number of validators. + max_entries: + type: integer + format: int64 + description: >- + max_entries is the max entries for either unbonding delegation or + redelegation (per pair/trio). + historical_entries: + type: integer + format: int64 + description: historical_entries is the number of historical entries to persist. + bond_denom: + type: string + description: bond_denom defines the bondable coin denomination. + description: Params defines the parameters for the staking module. + cosmos.staking.v1beta1.Pool: + type: object + properties: + not_bonded_tokens: + type: string + bonded_tokens: + type: string + description: |- + Pool is used for tracking bonded and not-bonded token supply of the bond + denomination. + cosmos.staking.v1beta1.QueryDelegationResponse: + type: object + properties: + delegation_response: + type: object + properties: + delegation: + type: object + properties: + delegator_address: + type: string + description: >- + delegator_address is the bech32-encoded address of the + delegator. + validator_address: + type: string + description: >- + validator_address is the bech32-encoded address of the + validator. + shares: + type: string + description: shares define the delegation shares received. + description: >- + Delegation represents the bond with tokens held by an account. It + is + + owned by one delegator, and is associated with the voting power of + one + + validator. + balance: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom + method + + signatures required by gogoproto. + description: >- + DelegationResponse is equivalent to Delegation except that it contains + a + + balance in addition to shares which is more suitable for client + responses. + description: >- + QueryDelegationResponse is response type for the Query/Delegation RPC + method. + cosmos.staking.v1beta1.QueryDelegatorDelegationsResponse: + type: object + properties: + delegation_responses: + type: array + items: + type: object + properties: + delegation: + type: object + properties: + delegator_address: + type: string + description: >- + delegator_address is the bech32-encoded address of the + delegator. + validator_address: + type: string + description: >- + validator_address is the bech32-encoded address of the + validator. + shares: + type: string + description: shares define the delegation shares received. + description: >- + Delegation represents the bond with tokens held by an account. + It is + + owned by one delegator, and is associated with the voting power + of one + + validator. + balance: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom + method + + signatures required by gogoproto. + description: >- + DelegationResponse is equivalent to Delegation except that it + contains a + + balance in addition to shares which is more suitable for client + responses. + description: delegation_responses defines all the delegations' info of a delegator. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + QueryDelegatorDelegationsResponse is response type for the + Query/DelegatorDelegations RPC method. + cosmos.staking.v1beta1.QueryDelegatorUnbondingDelegationsResponse: + type: object + properties: + unbonding_responses: + type: array + items: + type: object + properties: + delegator_address: + type: string + description: >- + delegator_address is the bech32-encoded address of the + delegator. + validator_address: + type: string + description: >- + validator_address is the bech32-encoded address of the + validator. + entries: + type: array + items: + type: object + properties: + creation_height: + type: string + format: int64 + description: >- + creation_height is the height which the unbonding took + place. + completion_time: + type: string + format: date-time + description: completion_time is the unix time for unbonding completion. + initial_balance: + type: string + description: >- + initial_balance defines the tokens initially scheduled to + receive at completion. + balance: + type: string + description: balance defines the tokens to receive at completion. + description: >- + UnbondingDelegationEntry defines an unbonding object with + relevant metadata. + description: entries are the unbonding delegation entries. + description: >- + UnbondingDelegation stores all of a single delegator's unbonding + bonds + + for a single validator in an time-ordered list. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + QueryUnbondingDelegatorDelegationsResponse is response type for the + Query/UnbondingDelegatorDelegations RPC method. + cosmos.staking.v1beta1.QueryDelegatorValidatorResponse: + type: object + properties: + validator: + type: object + properties: + operator_address: + type: string + description: >- + operator_address defines the address of the validator's operator; + bech encoded in JSON. + consensus_pubkey: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + consensus_pubkey is the consensus public key of the validator, as + a Protobuf Any. + jailed: + type: boolean + description: >- + jailed defined whether the validator has been jailed from bonded + status or not. + status: + description: status is the validator status (bonded/unbonding/unbonded). + type: string + enum: + - BOND_STATUS_UNSPECIFIED + - BOND_STATUS_UNBONDED + - BOND_STATUS_UNBONDING + - BOND_STATUS_BONDED + default: BOND_STATUS_UNSPECIFIED + tokens: + type: string + description: tokens define the delegated tokens (incl. self-delegation). + delegator_shares: + type: string + description: >- + delegator_shares defines total shares issued to a validator's + delegators. + description: + description: description defines the description terms for the validator. + type: object + properties: + moniker: + type: string + description: moniker defines a human-readable name for the validator. + identity: + type: string + description: >- + identity defines an optional identity signature (ex. UPort or + Keybase). + website: + type: string + description: website defines an optional website link. + security_contact: + type: string + description: >- + security_contact defines an optional email for security + contact. + details: + type: string + description: details define other optional details. + unbonding_height: + type: string + format: int64 + description: >- + unbonding_height defines, if unbonding, the height at which this + validator has begun unbonding. + unbonding_time: + type: string + format: date-time + description: >- + unbonding_time defines, if unbonding, the min time for the + validator to complete unbonding. + commission: + description: commission defines the commission parameters. + type: object + properties: + commission_rates: + description: >- + commission_rates defines the initial commission rates to be + used for creating a validator. + type: object + properties: + rate: + type: string + description: >- + rate is the commission rate charged to delegators, as a + fraction. + max_rate: + type: string + description: >- + max_rate defines the maximum commission rate which + validator can ever charge, as a fraction. + max_change_rate: + type: string + description: >- + max_change_rate defines the maximum daily increase of the + validator commission, as a fraction. + update_time: + type: string + format: date-time + description: update_time is the last time the commission rate was changed. + min_self_delegation: + type: string + description: >- + min_self_delegation is the validator's self declared minimum self + delegation. + description: >- + Validator defines a validator, together with the total amount of the + + Validator's bond shares and their exchange rate to coins. Slashing + results in + + a decrease in the exchange rate, allowing correct calculation of + future + + undelegations without iterating over delegators. When coins are + delegated to + + this validator, the validator is credited with a delegation whose + number of + + bond shares is based on the amount of coins delegated divided by the + current + + exchange rate. Voting power can be calculated as total bonded shares + + multiplied by exchange rate. + description: |- + QueryDelegatorValidatorResponse response type for the + Query/DelegatorValidator RPC method. + cosmos.staking.v1beta1.QueryDelegatorValidatorsResponse: + type: object + properties: + validators: + type: array + items: + type: object + properties: + operator_address: + type: string + description: >- + operator_address defines the address of the validator's + operator; bech encoded in JSON. + consensus_pubkey: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + consensus_pubkey is the consensus public key of the validator, + as a Protobuf Any. + jailed: + type: boolean + description: >- + jailed defined whether the validator has been jailed from bonded + status or not. + status: + description: status is the validator status (bonded/unbonding/unbonded). + type: string + enum: + - BOND_STATUS_UNSPECIFIED + - BOND_STATUS_UNBONDED + - BOND_STATUS_UNBONDING + - BOND_STATUS_BONDED + default: BOND_STATUS_UNSPECIFIED + tokens: + type: string + description: tokens define the delegated tokens (incl. self-delegation). + delegator_shares: + type: string + description: >- + delegator_shares defines total shares issued to a validator's + delegators. + description: + description: description defines the description terms for the validator. + type: object + properties: + moniker: + type: string + description: moniker defines a human-readable name for the validator. + identity: + type: string + description: >- + identity defines an optional identity signature (ex. UPort + or Keybase). + website: + type: string + description: website defines an optional website link. + security_contact: + type: string + description: >- + security_contact defines an optional email for security + contact. + details: + type: string + description: details define other optional details. + unbonding_height: + type: string + format: int64 + description: >- + unbonding_height defines, if unbonding, the height at which this + validator has begun unbonding. + unbonding_time: + type: string + format: date-time + description: >- + unbonding_time defines, if unbonding, the min time for the + validator to complete unbonding. + commission: + description: commission defines the commission parameters. + type: object + properties: + commission_rates: + description: >- + commission_rates defines the initial commission rates to be + used for creating a validator. + type: object + properties: + rate: + type: string + description: >- + rate is the commission rate charged to delegators, as a + fraction. + max_rate: + type: string + description: >- + max_rate defines the maximum commission rate which + validator can ever charge, as a fraction. + max_change_rate: + type: string + description: >- + max_change_rate defines the maximum daily increase of + the validator commission, as a fraction. + update_time: + type: string + format: date-time + description: >- + update_time is the last time the commission rate was + changed. + min_self_delegation: + type: string + description: >- + min_self_delegation is the validator's self declared minimum + self delegation. + description: >- + Validator defines a validator, together with the total amount of the + + Validator's bond shares and their exchange rate to coins. Slashing + results in + + a decrease in the exchange rate, allowing correct calculation of + future + + undelegations without iterating over delegators. When coins are + delegated to + + this validator, the validator is credited with a delegation whose + number of + + bond shares is based on the amount of coins delegated divided by the + current + + exchange rate. Voting power can be calculated as total bonded shares + + multiplied by exchange rate. + description: validators defines the the validators' info of a delegator. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + QueryDelegatorValidatorsResponse is response type for the + Query/DelegatorValidators RPC method. + cosmos.staking.v1beta1.QueryHistoricalInfoResponse: + type: object + properties: + hist: + description: hist defines the historical info at the given height. + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for processing a block + in the blockchain, + + including all blockchain data structures and the rules of the + application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + valset: + type: array + items: + type: object + properties: + operator_address: + type: string + description: >- + operator_address defines the address of the validator's + operator; bech encoded in JSON. + consensus_pubkey: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + consensus_pubkey is the consensus public key of the + validator, as a Protobuf Any. + jailed: + type: boolean + description: >- + jailed defined whether the validator has been jailed from + bonded status or not. + status: + description: status is the validator status (bonded/unbonding/unbonded). + type: string + enum: + - BOND_STATUS_UNSPECIFIED + - BOND_STATUS_UNBONDED + - BOND_STATUS_UNBONDING + - BOND_STATUS_BONDED + default: BOND_STATUS_UNSPECIFIED + tokens: + type: string + description: tokens define the delegated tokens (incl. self-delegation). + delegator_shares: + type: string + description: >- + delegator_shares defines total shares issued to a + validator's delegators. + description: + description: description defines the description terms for the validator. + type: object + properties: + moniker: + type: string + description: moniker defines a human-readable name for the validator. + identity: + type: string + description: >- + identity defines an optional identity signature (ex. + UPort or Keybase). + website: + type: string + description: website defines an optional website link. + security_contact: + type: string + description: >- + security_contact defines an optional email for security + contact. + details: + type: string + description: details define other optional details. + unbonding_height: + type: string + format: int64 + description: >- + unbonding_height defines, if unbonding, the height at which + this validator has begun unbonding. + unbonding_time: + type: string + format: date-time + description: >- + unbonding_time defines, if unbonding, the min time for the + validator to complete unbonding. + commission: + description: commission defines the commission parameters. + type: object + properties: + commission_rates: + description: >- + commission_rates defines the initial commission rates to + be used for creating a validator. + type: object + properties: + rate: + type: string + description: >- + rate is the commission rate charged to delegators, + as a fraction. + max_rate: + type: string + description: >- + max_rate defines the maximum commission rate which + validator can ever charge, as a fraction. + max_change_rate: + type: string + description: >- + max_change_rate defines the maximum daily increase + of the validator commission, as a fraction. + update_time: + type: string + format: date-time + description: >- + update_time is the last time the commission rate was + changed. + min_self_delegation: + type: string + description: >- + min_self_delegation is the validator's self declared minimum + self delegation. + description: >- + Validator defines a validator, together with the total amount of + the + + Validator's bond shares and their exchange rate to coins. + Slashing results in + + a decrease in the exchange rate, allowing correct calculation of + future + + undelegations without iterating over delegators. When coins are + delegated to + + this validator, the validator is credited with a delegation + whose number of + + bond shares is based on the amount of coins delegated divided by + the current + + exchange rate. Voting power can be calculated as total bonded + shares + + multiplied by exchange rate. + description: >- + QueryHistoricalInfoResponse is response type for the Query/HistoricalInfo + RPC + + method. + cosmos.staking.v1beta1.QueryParamsResponse: + type: object + properties: + params: + description: params holds all the parameters of this module. + type: object + properties: + unbonding_time: + type: string + description: unbonding_time is the time duration of unbonding. + max_validators: + type: integer + format: int64 + description: max_validators is the maximum number of validators. + max_entries: + type: integer + format: int64 + description: >- + max_entries is the max entries for either unbonding delegation or + redelegation (per pair/trio). + historical_entries: + type: integer + format: int64 + description: historical_entries is the number of historical entries to persist. + bond_denom: + type: string + description: bond_denom defines the bondable coin denomination. + description: QueryParamsResponse is response type for the Query/Params RPC method. + cosmos.staking.v1beta1.QueryPoolResponse: + type: object + properties: + pool: + description: pool defines the pool info. + type: object + properties: + not_bonded_tokens: + type: string + bonded_tokens: + type: string + description: QueryPoolResponse is response type for the Query/Pool RPC method. + cosmos.staking.v1beta1.QueryRedelegationsResponse: + type: object + properties: + redelegation_responses: + type: array + items: + type: object + properties: + redelegation: + type: object + properties: + delegator_address: + type: string + description: >- + delegator_address is the bech32-encoded address of the + delegator. + validator_src_address: + type: string + description: >- + validator_src_address is the validator redelegation source + operator address. + validator_dst_address: + type: string + description: >- + validator_dst_address is the validator redelegation + destination operator address. + entries: + type: array + items: + type: object + properties: + creation_height: + type: string + format: int64 + description: >- + creation_height defines the height which the + redelegation took place. + completion_time: + type: string + format: date-time + description: >- + completion_time defines the unix time for redelegation + completion. + initial_balance: + type: string + description: >- + initial_balance defines the initial balance when + redelegation started. + shares_dst: + type: string + description: >- + shares_dst is the amount of destination-validator + shares created by redelegation. + description: >- + RedelegationEntry defines a redelegation object with + relevant metadata. + description: entries are the redelegation entries. + description: >- + Redelegation contains the list of a particular delegator's + redelegating bonds + + from a particular source validator to a particular destination + validator. + entries: + type: array + items: + type: object + properties: + redelegation_entry: + type: object + properties: + creation_height: + type: string + format: int64 + description: >- + creation_height defines the height which the + redelegation took place. + completion_time: + type: string + format: date-time + description: >- + completion_time defines the unix time for redelegation + completion. + initial_balance: + type: string + description: >- + initial_balance defines the initial balance when + redelegation started. + shares_dst: + type: string + description: >- + shares_dst is the amount of destination-validator + shares created by redelegation. + description: >- + RedelegationEntry defines a redelegation object with + relevant metadata. + balance: + type: string + description: >- + RedelegationEntryResponse is equivalent to a RedelegationEntry + except that it + + contains a balance in addition to shares which is more + suitable for client + + responses. + description: >- + RedelegationResponse is equivalent to a Redelegation except that its + entries + + contain a balance in addition to shares which is more suitable for + client + + responses. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryRedelegationsResponse is response type for the Query/Redelegations + RPC + + method. + cosmos.staking.v1beta1.QueryUnbondingDelegationResponse: + type: object + properties: + unbond: + type: object + properties: + delegator_address: + type: string + description: delegator_address is the bech32-encoded address of the delegator. + validator_address: + type: string + description: validator_address is the bech32-encoded address of the validator. + entries: + type: array + items: + type: object + properties: + creation_height: + type: string + format: int64 + description: >- + creation_height is the height which the unbonding took + place. + completion_time: + type: string + format: date-time + description: completion_time is the unix time for unbonding completion. + initial_balance: + type: string + description: >- + initial_balance defines the tokens initially scheduled to + receive at completion. + balance: + type: string + description: balance defines the tokens to receive at completion. + description: >- + UnbondingDelegationEntry defines an unbonding object with + relevant metadata. + description: entries are the unbonding delegation entries. + description: |- + UnbondingDelegation stores all of a single delegator's unbonding bonds + for a single validator in an time-ordered list. + description: |- + QueryDelegationResponse is response type for the Query/UnbondingDelegation + RPC method. + cosmos.staking.v1beta1.QueryValidatorDelegationsResponse: + type: object + properties: + delegation_responses: + type: array + items: + type: object + properties: + delegation: + type: object + properties: + delegator_address: + type: string + description: >- + delegator_address is the bech32-encoded address of the + delegator. + validator_address: + type: string + description: >- + validator_address is the bech32-encoded address of the + validator. + shares: + type: string + description: shares define the delegation shares received. + description: >- + Delegation represents the bond with tokens held by an account. + It is + + owned by one delegator, and is associated with the voting power + of one + + validator. + balance: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom + method + + signatures required by gogoproto. + description: >- + DelegationResponse is equivalent to Delegation except that it + contains a + + balance in addition to shares which is more suitable for client + responses. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + title: |- + QueryValidatorDelegationsResponse is response type for the + Query/ValidatorDelegations RPC method + cosmos.staking.v1beta1.QueryValidatorResponse: + type: object + properties: + validator: + type: object + properties: + operator_address: + type: string + description: >- + operator_address defines the address of the validator's operator; + bech encoded in JSON. + consensus_pubkey: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + consensus_pubkey is the consensus public key of the validator, as + a Protobuf Any. + jailed: + type: boolean + description: >- + jailed defined whether the validator has been jailed from bonded + status or not. + status: + description: status is the validator status (bonded/unbonding/unbonded). + type: string + enum: + - BOND_STATUS_UNSPECIFIED + - BOND_STATUS_UNBONDED + - BOND_STATUS_UNBONDING + - BOND_STATUS_BONDED + default: BOND_STATUS_UNSPECIFIED + tokens: + type: string + description: tokens define the delegated tokens (incl. self-delegation). + delegator_shares: + type: string + description: >- + delegator_shares defines total shares issued to a validator's + delegators. + description: + description: description defines the description terms for the validator. + type: object + properties: + moniker: + type: string + description: moniker defines a human-readable name for the validator. + identity: + type: string + description: >- + identity defines an optional identity signature (ex. UPort or + Keybase). + website: + type: string + description: website defines an optional website link. + security_contact: + type: string + description: >- + security_contact defines an optional email for security + contact. + details: + type: string + description: details define other optional details. + unbonding_height: + type: string + format: int64 + description: >- + unbonding_height defines, if unbonding, the height at which this + validator has begun unbonding. + unbonding_time: + type: string + format: date-time + description: >- + unbonding_time defines, if unbonding, the min time for the + validator to complete unbonding. + commission: + description: commission defines the commission parameters. + type: object + properties: + commission_rates: + description: >- + commission_rates defines the initial commission rates to be + used for creating a validator. + type: object + properties: + rate: + type: string + description: >- + rate is the commission rate charged to delegators, as a + fraction. + max_rate: + type: string + description: >- + max_rate defines the maximum commission rate which + validator can ever charge, as a fraction. + max_change_rate: + type: string + description: >- + max_change_rate defines the maximum daily increase of the + validator commission, as a fraction. + update_time: + type: string + format: date-time + description: update_time is the last time the commission rate was changed. + min_self_delegation: + type: string + description: >- + min_self_delegation is the validator's self declared minimum self + delegation. + description: >- + Validator defines a validator, together with the total amount of the + + Validator's bond shares and their exchange rate to coins. Slashing + results in + + a decrease in the exchange rate, allowing correct calculation of + future + + undelegations without iterating over delegators. When coins are + delegated to + + this validator, the validator is credited with a delegation whose + number of + + bond shares is based on the amount of coins delegated divided by the + current + + exchange rate. Voting power can be calculated as total bonded shares + + multiplied by exchange rate. + title: QueryValidatorResponse is response type for the Query/Validator RPC method + cosmos.staking.v1beta1.QueryValidatorUnbondingDelegationsResponse: + type: object + properties: + unbonding_responses: + type: array + items: + type: object + properties: + delegator_address: + type: string + description: >- + delegator_address is the bech32-encoded address of the + delegator. + validator_address: + type: string + description: >- + validator_address is the bech32-encoded address of the + validator. + entries: + type: array + items: + type: object + properties: + creation_height: + type: string + format: int64 + description: >- + creation_height is the height which the unbonding took + place. + completion_time: + type: string + format: date-time + description: completion_time is the unix time for unbonding completion. + initial_balance: + type: string + description: >- + initial_balance defines the tokens initially scheduled to + receive at completion. + balance: + type: string + description: balance defines the tokens to receive at completion. + description: >- + UnbondingDelegationEntry defines an unbonding object with + relevant metadata. + description: entries are the unbonding delegation entries. + description: >- + UnbondingDelegation stores all of a single delegator's unbonding + bonds + + for a single validator in an time-ordered list. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + QueryValidatorUnbondingDelegationsResponse is response type for the + Query/ValidatorUnbondingDelegations RPC method. + cosmos.staking.v1beta1.QueryValidatorsResponse: + type: object + properties: + validators: + type: array + items: + type: object + properties: + operator_address: + type: string + description: >- + operator_address defines the address of the validator's + operator; bech encoded in JSON. + consensus_pubkey: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + consensus_pubkey is the consensus public key of the validator, + as a Protobuf Any. + jailed: + type: boolean + description: >- + jailed defined whether the validator has been jailed from bonded + status or not. + status: + description: status is the validator status (bonded/unbonding/unbonded). + type: string + enum: + - BOND_STATUS_UNSPECIFIED + - BOND_STATUS_UNBONDED + - BOND_STATUS_UNBONDING + - BOND_STATUS_BONDED + default: BOND_STATUS_UNSPECIFIED + tokens: + type: string + description: tokens define the delegated tokens (incl. self-delegation). + delegator_shares: + type: string + description: >- + delegator_shares defines total shares issued to a validator's + delegators. + description: + description: description defines the description terms for the validator. + type: object + properties: + moniker: + type: string + description: moniker defines a human-readable name for the validator. + identity: + type: string + description: >- + identity defines an optional identity signature (ex. UPort + or Keybase). + website: + type: string + description: website defines an optional website link. + security_contact: + type: string + description: >- + security_contact defines an optional email for security + contact. + details: + type: string + description: details define other optional details. + unbonding_height: + type: string + format: int64 + description: >- + unbonding_height defines, if unbonding, the height at which this + validator has begun unbonding. + unbonding_time: + type: string + format: date-time + description: >- + unbonding_time defines, if unbonding, the min time for the + validator to complete unbonding. + commission: + description: commission defines the commission parameters. + type: object + properties: + commission_rates: + description: >- + commission_rates defines the initial commission rates to be + used for creating a validator. + type: object + properties: + rate: + type: string + description: >- + rate is the commission rate charged to delegators, as a + fraction. + max_rate: + type: string + description: >- + max_rate defines the maximum commission rate which + validator can ever charge, as a fraction. + max_change_rate: + type: string + description: >- + max_change_rate defines the maximum daily increase of + the validator commission, as a fraction. + update_time: + type: string + format: date-time + description: >- + update_time is the last time the commission rate was + changed. + min_self_delegation: + type: string + description: >- + min_self_delegation is the validator's self declared minimum + self delegation. + description: >- + Validator defines a validator, together with the total amount of the + + Validator's bond shares and their exchange rate to coins. Slashing + results in + + a decrease in the exchange rate, allowing correct calculation of + future + + undelegations without iterating over delegators. When coins are + delegated to + + this validator, the validator is credited with a delegation whose + number of + + bond shares is based on the amount of coins delegated divided by the + current + + exchange rate. Voting power can be calculated as total bonded shares + + multiplied by exchange rate. + description: validators contains all the queried validators. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + title: >- + QueryValidatorsResponse is response type for the Query/Validators RPC + method + cosmos.staking.v1beta1.Redelegation: + type: object + properties: + delegator_address: + type: string + description: delegator_address is the bech32-encoded address of the delegator. + validator_src_address: + type: string + description: >- + validator_src_address is the validator redelegation source operator + address. + validator_dst_address: + type: string + description: >- + validator_dst_address is the validator redelegation destination + operator address. + entries: + type: array + items: + type: object + properties: + creation_height: + type: string + format: int64 + description: >- + creation_height defines the height which the redelegation took + place. + completion_time: + type: string + format: date-time + description: >- + completion_time defines the unix time for redelegation + completion. + initial_balance: + type: string + description: >- + initial_balance defines the initial balance when redelegation + started. + shares_dst: + type: string + description: >- + shares_dst is the amount of destination-validator shares created + by redelegation. + description: >- + RedelegationEntry defines a redelegation object with relevant + metadata. + description: entries are the redelegation entries. + description: >- + Redelegation contains the list of a particular delegator's redelegating + bonds + + from a particular source validator to a particular destination validator. + cosmos.staking.v1beta1.RedelegationEntry: + type: object + properties: + creation_height: + type: string + format: int64 + description: creation_height defines the height which the redelegation took place. + completion_time: + type: string + format: date-time + description: completion_time defines the unix time for redelegation completion. + initial_balance: + type: string + description: initial_balance defines the initial balance when redelegation started. + shares_dst: + type: string + description: >- + shares_dst is the amount of destination-validator shares created by + redelegation. + description: RedelegationEntry defines a redelegation object with relevant metadata. + cosmos.staking.v1beta1.RedelegationEntryResponse: + type: object + properties: + redelegation_entry: + type: object + properties: + creation_height: + type: string + format: int64 + description: >- + creation_height defines the height which the redelegation took + place. + completion_time: + type: string + format: date-time + description: completion_time defines the unix time for redelegation completion. + initial_balance: + type: string + description: >- + initial_balance defines the initial balance when redelegation + started. + shares_dst: + type: string + description: >- + shares_dst is the amount of destination-validator shares created + by redelegation. + description: >- + RedelegationEntry defines a redelegation object with relevant + metadata. + balance: + type: string + description: >- + RedelegationEntryResponse is equivalent to a RedelegationEntry except that + it + + contains a balance in addition to shares which is more suitable for client + + responses. + cosmos.staking.v1beta1.RedelegationResponse: + type: object + properties: + redelegation: + type: object + properties: + delegator_address: + type: string + description: delegator_address is the bech32-encoded address of the delegator. + validator_src_address: + type: string + description: >- + validator_src_address is the validator redelegation source + operator address. + validator_dst_address: + type: string + description: >- + validator_dst_address is the validator redelegation destination + operator address. + entries: + type: array + items: + type: object + properties: + creation_height: + type: string + format: int64 + description: >- + creation_height defines the height which the redelegation + took place. + completion_time: + type: string + format: date-time + description: >- + completion_time defines the unix time for redelegation + completion. + initial_balance: + type: string + description: >- + initial_balance defines the initial balance when + redelegation started. + shares_dst: + type: string + description: >- + shares_dst is the amount of destination-validator shares + created by redelegation. + description: >- + RedelegationEntry defines a redelegation object with relevant + metadata. + description: entries are the redelegation entries. + description: >- + Redelegation contains the list of a particular delegator's + redelegating bonds + + from a particular source validator to a particular destination + validator. + entries: + type: array + items: + type: object + properties: + redelegation_entry: + type: object + properties: + creation_height: + type: string + format: int64 + description: >- + creation_height defines the height which the redelegation + took place. + completion_time: + type: string + format: date-time + description: >- + completion_time defines the unix time for redelegation + completion. + initial_balance: + type: string + description: >- + initial_balance defines the initial balance when + redelegation started. + shares_dst: + type: string + description: >- + shares_dst is the amount of destination-validator shares + created by redelegation. + description: >- + RedelegationEntry defines a redelegation object with relevant + metadata. + balance: + type: string + description: >- + RedelegationEntryResponse is equivalent to a RedelegationEntry + except that it + + contains a balance in addition to shares which is more suitable for + client + + responses. + description: >- + RedelegationResponse is equivalent to a Redelegation except that its + entries + + contain a balance in addition to shares which is more suitable for client + + responses. + cosmos.staking.v1beta1.UnbondingDelegation: + type: object + properties: + delegator_address: + type: string + description: delegator_address is the bech32-encoded address of the delegator. + validator_address: + type: string + description: validator_address is the bech32-encoded address of the validator. + entries: + type: array + items: + type: object + properties: + creation_height: + type: string + format: int64 + description: creation_height is the height which the unbonding took place. + completion_time: + type: string + format: date-time + description: completion_time is the unix time for unbonding completion. + initial_balance: + type: string + description: >- + initial_balance defines the tokens initially scheduled to + receive at completion. + balance: + type: string + description: balance defines the tokens to receive at completion. + description: >- + UnbondingDelegationEntry defines an unbonding object with relevant + metadata. + description: entries are the unbonding delegation entries. + description: |- + UnbondingDelegation stores all of a single delegator's unbonding bonds + for a single validator in an time-ordered list. + cosmos.staking.v1beta1.UnbondingDelegationEntry: + type: object + properties: + creation_height: + type: string + format: int64 + description: creation_height is the height which the unbonding took place. + completion_time: + type: string + format: date-time + description: completion_time is the unix time for unbonding completion. + initial_balance: + type: string + description: >- + initial_balance defines the tokens initially scheduled to receive at + completion. + balance: + type: string + description: balance defines the tokens to receive at completion. + description: >- + UnbondingDelegationEntry defines an unbonding object with relevant + metadata. + cosmos.staking.v1beta1.Validator: + type: object + properties: + operator_address: + type: string + description: >- + operator_address defines the address of the validator's operator; bech + encoded in JSON. + consensus_pubkey: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + consensus_pubkey is the consensus public key of the validator, as a + Protobuf Any. + jailed: + type: boolean + description: >- + jailed defined whether the validator has been jailed from bonded + status or not. + status: + description: status is the validator status (bonded/unbonding/unbonded). + type: string + enum: + - BOND_STATUS_UNSPECIFIED + - BOND_STATUS_UNBONDED + - BOND_STATUS_UNBONDING + - BOND_STATUS_BONDED + default: BOND_STATUS_UNSPECIFIED + tokens: + type: string + description: tokens define the delegated tokens (incl. self-delegation). + delegator_shares: + type: string + description: >- + delegator_shares defines total shares issued to a validator's + delegators. + description: + description: description defines the description terms for the validator. + type: object + properties: + moniker: + type: string + description: moniker defines a human-readable name for the validator. + identity: + type: string + description: >- + identity defines an optional identity signature (ex. UPort or + Keybase). + website: + type: string + description: website defines an optional website link. + security_contact: + type: string + description: security_contact defines an optional email for security contact. + details: + type: string + description: details define other optional details. + unbonding_height: + type: string + format: int64 + description: >- + unbonding_height defines, if unbonding, the height at which this + validator has begun unbonding. + unbonding_time: + type: string + format: date-time + description: >- + unbonding_time defines, if unbonding, the min time for the validator + to complete unbonding. + commission: + description: commission defines the commission parameters. + type: object + properties: + commission_rates: + description: >- + commission_rates defines the initial commission rates to be used + for creating a validator. + type: object + properties: + rate: + type: string + description: >- + rate is the commission rate charged to delegators, as a + fraction. + max_rate: + type: string + description: >- + max_rate defines the maximum commission rate which validator + can ever charge, as a fraction. + max_change_rate: + type: string + description: >- + max_change_rate defines the maximum daily increase of the + validator commission, as a fraction. + update_time: + type: string + format: date-time + description: update_time is the last time the commission rate was changed. + min_self_delegation: + type: string + description: >- + min_self_delegation is the validator's self declared minimum self + delegation. + description: >- + Validator defines a validator, together with the total amount of the + + Validator's bond shares and their exchange rate to coins. Slashing results + in + + a decrease in the exchange rate, allowing correct calculation of future + + undelegations without iterating over delegators. When coins are delegated + to + + this validator, the validator is credited with a delegation whose number + of + + bond shares is based on the amount of coins delegated divided by the + current + + exchange rate. Voting power can be calculated as total bonded shares + + multiplied by exchange rate. + tendermint.types.BlockID: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + tendermint.types.Header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for processing a block in the + blockchain, + + including all blockchain data structures and the rules of the + application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + tendermint.types.PartSetHeader: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + tendermint.version.Consensus: + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for processing a block in the + blockchain, + + including all blockchain data structures and the rules of the + application's + + state transition machine. + cosmos.base.tendermint.v1beta1.GetBlockByHeightResponse: + type: object + properties: + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + block: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for processing a block + in the blockchain, + + including all blockchain data structures and the rules of the + application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + data: + type: object + properties: + txs: + type: array + items: + type: string + format: byte + description: >- + Txs that will be applied by state @ block.Height+1. + + NOTE: not all txs here are valid. We're just agreeing on the + order first. + + This means that block.AppHash does not include these txs. + title: Data contains the set of transactions included in the block + evidence: + type: object + properties: + evidence: + type: array + items: + type: object + properties: + duplicate_vote_evidence: + type: object + properties: + vote_a: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: >- + SignedMsgType is a type of signed message in the + consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or commit vote + from validators for + + consensus. + vote_b: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: >- + SignedMsgType is a type of signed message in the + consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or commit vote + from validators for + + consensus. + total_voting_power: + type: string + format: int64 + validator_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: >- + DuplicateVoteEvidence contains evidence of a validator + signed two conflicting votes. + light_client_attack_evidence: + type: object + properties: + conflicting_block: + type: object + properties: + signed_header: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules + for processing a block in the + blockchain, + + including all blockchain data structures + and the rules of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: >- + hashes from the app output from the prev + block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: >- + Header defines the structure of a block + header. + commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: >- + BlockIdFlag indicates which BlcokID the + signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: >- + CommitSig is a part of the Vote included + in a Commit. + description: >- + Commit contains the evidence that a block + was committed by a set of validators. + validator_set: + type: object + properties: + validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: >- + PublicKey defines the keys available for + use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + proposer: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: >- + PublicKey defines the keys available for + use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + common_height: + type: string + format: int64 + byzantine_validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: >- + PublicKey defines the keys available for use + with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: >- + LightClientAttackEvidence contains evidence of a set of + validators attempting to mislead a light client. + last_commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: BlockIdFlag indicates which BlcokID the signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: CommitSig is a part of the Vote included in a Commit. + description: >- + Commit contains the evidence that a block was committed by a set + of validators. + description: >- + GetBlockByHeightResponse is the response type for the + Query/GetBlockByHeight RPC method. + cosmos.base.tendermint.v1beta1.GetLatestBlockResponse: + type: object + properties: + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + block: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for processing a block + in the blockchain, + + including all blockchain data structures and the rules of the + application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + data: + type: object + properties: + txs: + type: array + items: + type: string + format: byte + description: >- + Txs that will be applied by state @ block.Height+1. + + NOTE: not all txs here are valid. We're just agreeing on the + order first. + + This means that block.AppHash does not include these txs. + title: Data contains the set of transactions included in the block + evidence: + type: object + properties: + evidence: + type: array + items: + type: object + properties: + duplicate_vote_evidence: + type: object + properties: + vote_a: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: >- + SignedMsgType is a type of signed message in the + consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or commit vote + from validators for + + consensus. + vote_b: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: >- + SignedMsgType is a type of signed message in the + consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or commit vote + from validators for + + consensus. + total_voting_power: + type: string + format: int64 + validator_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: >- + DuplicateVoteEvidence contains evidence of a validator + signed two conflicting votes. + light_client_attack_evidence: + type: object + properties: + conflicting_block: + type: object + properties: + signed_header: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules + for processing a block in the + blockchain, + + including all blockchain data structures + and the rules of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: >- + hashes from the app output from the prev + block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: >- + Header defines the structure of a block + header. + commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: >- + BlockIdFlag indicates which BlcokID the + signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: >- + CommitSig is a part of the Vote included + in a Commit. + description: >- + Commit contains the evidence that a block + was committed by a set of validators. + validator_set: + type: object + properties: + validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: >- + PublicKey defines the keys available for + use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + proposer: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: >- + PublicKey defines the keys available for + use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + common_height: + type: string + format: int64 + byzantine_validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: >- + PublicKey defines the keys available for use + with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: >- + LightClientAttackEvidence contains evidence of a set of + validators attempting to mislead a light client. + last_commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: BlockIdFlag indicates which BlcokID the signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: CommitSig is a part of the Vote included in a Commit. + description: >- + Commit contains the evidence that a block was committed by a set + of validators. + description: >- + GetLatestBlockResponse is the response type for the Query/GetLatestBlock + RPC method. + cosmos.base.tendermint.v1beta1.GetLatestValidatorSetResponse: + type: object + properties: + block_height: + type: string + format: int64 + validators: + type: array + items: + type: object + properties: + address: + type: string + pub_key: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + description: Validator is the type for the validator-set. + pagination: + description: pagination defines an pagination for the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + GetLatestValidatorSetResponse is the response type for the + Query/GetValidatorSetByHeight RPC method. + cosmos.base.tendermint.v1beta1.GetNodeInfoResponse: + type: object + properties: + default_node_info: + type: object + properties: + protocol_version: + type: object + properties: + p2p: + type: string + format: uint64 + block: + type: string + format: uint64 + app: + type: string + format: uint64 + default_node_id: + type: string + listen_addr: + type: string + network: + type: string + version: + type: string + channels: + type: string + format: byte + moniker: + type: string + other: + type: object + properties: + tx_index: + type: string + rpc_address: + type: string + application_version: + type: object + properties: + name: + type: string + app_name: + type: string + version: + type: string + git_commit: + type: string + build_tags: + type: string + go_version: + type: string + build_deps: + type: array + items: + type: object + properties: + path: + type: string + title: module path + version: + type: string + title: module version + sum: + type: string + title: checksum + title: Module is the type for VersionInfo + cosmos_sdk_version: + type: string + title: 'Since: cosmos-sdk 0.43' + description: VersionInfo is the type for the GetNodeInfoResponse message. + description: >- + GetNodeInfoResponse is the request type for the Query/GetNodeInfo RPC + method. + cosmos.base.tendermint.v1beta1.GetSyncingResponse: + type: object + properties: + syncing: + type: boolean + description: >- + GetSyncingResponse is the response type for the Query/GetSyncing RPC + method. + cosmos.base.tendermint.v1beta1.GetValidatorSetByHeightResponse: + type: object + properties: + block_height: + type: string + format: int64 + validators: + type: array + items: + type: object + properties: + address: + type: string + pub_key: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + description: Validator is the type for the validator-set. + pagination: + description: pagination defines an pagination for the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + GetValidatorSetByHeightResponse is the response type for the + Query/GetValidatorSetByHeight RPC method. + cosmos.base.tendermint.v1beta1.Module: + type: object + properties: + path: + type: string + title: module path + version: + type: string + title: module version + sum: + type: string + title: checksum + title: Module is the type for VersionInfo + cosmos.base.tendermint.v1beta1.Validator: + type: object + properties: + address: + type: string + pub_key: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + description: Validator is the type for the validator-set. + cosmos.base.tendermint.v1beta1.VersionInfo: + type: object + properties: + name: + type: string + app_name: + type: string + version: + type: string + git_commit: + type: string + build_tags: + type: string + go_version: + type: string + build_deps: + type: array + items: + type: object + properties: + path: + type: string + title: module path + version: + type: string + title: module version + sum: + type: string + title: checksum + title: Module is the type for VersionInfo + cosmos_sdk_version: + type: string + title: 'Since: cosmos-sdk 0.43' + description: VersionInfo is the type for the GetNodeInfoResponse message. + tendermint.crypto.PublicKey: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + tendermint.p2p.DefaultNodeInfo: + type: object + properties: + protocol_version: + type: object + properties: + p2p: + type: string + format: uint64 + block: + type: string + format: uint64 + app: + type: string + format: uint64 + default_node_id: + type: string + listen_addr: + type: string + network: + type: string + version: + type: string + channels: + type: string + format: byte + moniker: + type: string + other: + type: object + properties: + tx_index: + type: string + rpc_address: + type: string + tendermint.p2p.DefaultNodeInfoOther: + type: object + properties: + tx_index: + type: string + rpc_address: + type: string + tendermint.p2p.ProtocolVersion: + type: object + properties: + p2p: + type: string + format: uint64 + block: + type: string + format: uint64 + app: + type: string + format: uint64 + tendermint.types.Block: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for processing a block in + the blockchain, + + including all blockchain data structures and the rules of the + application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + data: + type: object + properties: + txs: + type: array + items: + type: string + format: byte + description: >- + Txs that will be applied by state @ block.Height+1. + + NOTE: not all txs here are valid. We're just agreeing on the + order first. + + This means that block.AppHash does not include these txs. + title: Data contains the set of transactions included in the block + evidence: + type: object + properties: + evidence: + type: array + items: + type: object + properties: + duplicate_vote_evidence: + type: object + properties: + vote_a: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: >- + SignedMsgType is a type of signed message in the + consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or commit vote + from validators for + + consensus. + vote_b: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: >- + SignedMsgType is a type of signed message in the + consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or commit vote + from validators for + + consensus. + total_voting_power: + type: string + format: int64 + validator_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: >- + DuplicateVoteEvidence contains evidence of a validator + signed two conflicting votes. + light_client_attack_evidence: + type: object + properties: + conflicting_block: + type: object + properties: + signed_header: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for + processing a block in the blockchain, + + including all blockchain data structures and + the rules of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: >- + hashes from the app output from the prev + block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: >- + BlockIdFlag indicates which BlcokID the + signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: >- + CommitSig is a part of the Vote included + in a Commit. + description: >- + Commit contains the evidence that a block was + committed by a set of validators. + validator_set: + type: object + properties: + validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: >- + PublicKey defines the keys available for + use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + proposer: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: >- + PublicKey defines the keys available for use + with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + common_height: + type: string + format: int64 + byzantine_validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: >- + PublicKey defines the keys available for use with + Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: >- + LightClientAttackEvidence contains evidence of a set of + validators attempting to mislead a light client. + last_commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: BlockIdFlag indicates which BlcokID the signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: CommitSig is a part of the Vote included in a Commit. + description: >- + Commit contains the evidence that a block was committed by a set of + validators. + tendermint.types.BlockIDFlag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: BlockIdFlag indicates which BlcokID the signature is for + tendermint.types.Commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: BlockIdFlag indicates which BlcokID the signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: CommitSig is a part of the Vote included in a Commit. + description: >- + Commit contains the evidence that a block was committed by a set of + validators. + tendermint.types.CommitSig: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: BlockIdFlag indicates which BlcokID the signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: CommitSig is a part of the Vote included in a Commit. + tendermint.types.Data: + type: object + properties: + txs: + type: array + items: + type: string + format: byte + description: >- + Txs that will be applied by state @ block.Height+1. + + NOTE: not all txs here are valid. We're just agreeing on the order + first. + + This means that block.AppHash does not include these txs. + title: Data contains the set of transactions included in the block + tendermint.types.DuplicateVoteEvidence: + type: object + properties: + vote_a: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: |- + SignedMsgType is a type of signed message in the consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or commit vote from validators + for + + consensus. + vote_b: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: |- + SignedMsgType is a type of signed message in the consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or commit vote from validators + for + + consensus. + total_voting_power: + type: string + format: int64 + validator_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: >- + DuplicateVoteEvidence contains evidence of a validator signed two + conflicting votes. + tendermint.types.Evidence: + type: object + properties: + duplicate_vote_evidence: + type: object + properties: + vote_a: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: |- + SignedMsgType is a type of signed message in the consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or commit vote from + validators for + + consensus. + vote_b: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: |- + SignedMsgType is a type of signed message in the consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or commit vote from + validators for + + consensus. + total_voting_power: + type: string + format: int64 + validator_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: >- + DuplicateVoteEvidence contains evidence of a validator signed two + conflicting votes. + light_client_attack_evidence: + type: object + properties: + conflicting_block: + type: object + properties: + signed_header: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for processing + a block in the blockchain, + + including all blockchain data structures and the rules + of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: >- + BlockIdFlag indicates which BlcokID the + signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: >- + CommitSig is a part of the Vote included in a + Commit. + description: >- + Commit contains the evidence that a block was committed by + a set of validators. + validator_set: + type: object + properties: + validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: >- + PublicKey defines the keys available for use with + Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + proposer: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: >- + PublicKey defines the keys available for use with + Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + common_height: + type: string + format: int64 + byzantine_validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: >- + LightClientAttackEvidence contains evidence of a set of validators + attempting to mislead a light client. + tendermint.types.EvidenceList: + type: object + properties: + evidence: + type: array + items: + type: object + properties: + duplicate_vote_evidence: + type: object + properties: + vote_a: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: >- + SignedMsgType is a type of signed message in the + consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or commit vote from + validators for + + consensus. + vote_b: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: >- + SignedMsgType is a type of signed message in the + consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or commit vote from + validators for + + consensus. + total_voting_power: + type: string + format: int64 + validator_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: >- + DuplicateVoteEvidence contains evidence of a validator signed + two conflicting votes. + light_client_attack_evidence: + type: object + properties: + conflicting_block: + type: object + properties: + signed_header: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for + processing a block in the blockchain, + + including all blockchain data structures and the + rules of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: >- + BlockIdFlag indicates which BlcokID the + signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: >- + CommitSig is a part of the Vote included in a + Commit. + description: >- + Commit contains the evidence that a block was + committed by a set of validators. + validator_set: + type: object + properties: + validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: >- + PublicKey defines the keys available for use + with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + proposer: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: >- + PublicKey defines the keys available for use + with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + common_height: + type: string + format: int64 + byzantine_validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: >- + PublicKey defines the keys available for use with + Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: >- + LightClientAttackEvidence contains evidence of a set of + validators attempting to mislead a light client. + tendermint.types.LightBlock: + type: object + properties: + signed_header: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for processing a block + in the blockchain, + + including all blockchain data structures and the rules of the + application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: BlockIdFlag indicates which BlcokID the signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: CommitSig is a part of the Vote included in a Commit. + description: >- + Commit contains the evidence that a block was committed by a set + of validators. + validator_set: + type: object + properties: + validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + proposer: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + tendermint.types.LightClientAttackEvidence: + type: object + properties: + conflicting_block: + type: object + properties: + signed_header: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for processing a + block in the blockchain, + + including all blockchain data structures and the rules of + the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: >- + BlockIdFlag indicates which BlcokID the signature is + for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: CommitSig is a part of the Vote included in a Commit. + description: >- + Commit contains the evidence that a block was committed by a + set of validators. + validator_set: + type: object + properties: + validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: >- + PublicKey defines the keys available for use with + Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + proposer: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: >- + PublicKey defines the keys available for use with + Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + common_height: + type: string + format: int64 + byzantine_validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: >- + LightClientAttackEvidence contains evidence of a set of validators + attempting to mislead a light client. + tendermint.types.SignedHeader: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for processing a block in + the blockchain, + + including all blockchain data structures and the rules of the + application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: BlockIdFlag indicates which BlcokID the signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: CommitSig is a part of the Vote included in a Commit. + description: >- + Commit contains the evidence that a block was committed by a set of + validators. + tendermint.types.SignedMsgType: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: |- + SignedMsgType is a type of signed message in the consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + tendermint.types.Validator: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + tendermint.types.ValidatorSet: + type: object + properties: + validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + proposer: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: PublicKey defines the keys available for use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + tendermint.types.Vote: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: |- + SignedMsgType is a type of signed message in the consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: |- + Vote represents a prevote, precommit, or commit vote from validators for + consensus. + router.v1.Params: + type: object + properties: + fee_percentage: + type: string + description: Params defines the set of IBC router parameters. + router.v1.QueryParamsResponse: + type: object + properties: + params: + description: params defines the parameters of the module. + type: object + properties: + fee_percentage: + type: string + description: QueryParamsResponse is the response type for the Query/Params RPC method. + type: object + properties: + params: + description: params defines the parameters of the module. + type: object + properties: + denom_creation_fee: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom + method + + signatures required by gogoproto. + denom_creation_gas_consume: + type: string + format: uint64 + title: >- + if denom_creation_fee is an empty array, then this field is used + to add more gas consumption + + to the base cost. + + https://github.com/CosmWasm/token-factory/issues/11 + description: QueryParamsResponse is the response type for the Query/Params RPC method. + cosmos.base.v1beta1.DecCoin: + type: object + properties: + denom: + type: string + amount: + type: string + description: |- + DecCoin defines a token with a denomination and a decimal amount. + + NOTE: The amount field is an Dec which implements the custom method + signatures required by gogoproto. + cosmos.distribution.v1beta1.DelegationDelegatorReward: + type: object + properties: + validator_address: + type: string + reward: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: |- + DecCoin defines a token with a denomination and a decimal amount. + + NOTE: The amount field is an Dec which implements the custom method + signatures required by gogoproto. + description: |- + DelegationDelegatorReward represents the properties + of a delegator's delegation reward. + cosmos.distribution.v1beta1.Params: + type: object + properties: + community_tax: + type: string + base_proposer_reward: + type: string + bonus_proposer_reward: + type: string + withdraw_addr_enabled: + type: boolean + description: Params defines the set of params for the distribution module. + cosmos.distribution.v1beta1.QueryCommunityPoolResponse: + type: object + properties: + pool: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: |- + DecCoin defines a token with a denomination and a decimal amount. + + NOTE: The amount field is an Dec which implements the custom method + signatures required by gogoproto. + description: pool defines community pool's coins. + description: >- + QueryCommunityPoolResponse is the response type for the + Query/CommunityPool + + RPC method. + cosmos.distribution.v1beta1.QueryDelegationRewardsResponse: + type: object + properties: + rewards: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: |- + DecCoin defines a token with a denomination and a decimal amount. + + NOTE: The amount field is an Dec which implements the custom method + signatures required by gogoproto. + description: rewards defines the rewards accrued by a delegation. + description: |- + QueryDelegationRewardsResponse is the response type for the + Query/DelegationRewards RPC method. + cosmos.distribution.v1beta1.QueryDelegationTotalRewardsResponse: + type: object + properties: + rewards: + type: array + items: + type: object + properties: + validator_address: + type: string + reward: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + DecCoin defines a token with a denomination and a decimal + amount. + + + NOTE: The amount field is an Dec which implements the custom + method + + signatures required by gogoproto. + description: |- + DelegationDelegatorReward represents the properties + of a delegator's delegation reward. + description: rewards defines all the rewards accrued by a delegator. + total: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: |- + DecCoin defines a token with a denomination and a decimal amount. + + NOTE: The amount field is an Dec which implements the custom method + signatures required by gogoproto. + description: total defines the sum of all the rewards. + description: |- + QueryDelegationTotalRewardsResponse is the response type for the + Query/DelegationTotalRewards RPC method. + cosmos.distribution.v1beta1.QueryDelegatorValidatorsResponse: + type: object + properties: + validators: + type: array + items: + type: string + description: validators defines the validators a delegator is delegating for. + description: |- + QueryDelegatorValidatorsResponse is the response type for the + Query/DelegatorValidators RPC method. + cosmos.distribution.v1beta1.QueryDelegatorWithdrawAddressResponse: + type: object + properties: + withdraw_address: + type: string + description: withdraw_address defines the delegator address to query for. + description: |- + QueryDelegatorWithdrawAddressResponse is the response type for the + Query/DelegatorWithdrawAddress RPC method. + cosmos.distribution.v1beta1.QueryParamsResponse: + type: object + properties: + params: + description: params defines the parameters of the module. + type: object + properties: + community_tax: + type: string + base_proposer_reward: + type: string + bonus_proposer_reward: + type: string + withdraw_addr_enabled: + type: boolean + description: QueryParamsResponse is the response type for the Query/Params RPC method. + cosmos.distribution.v1beta1.QueryValidatorCommissionResponse: + type: object + properties: + commission: + description: commission defines the commision the validator received. + type: object + properties: + commission: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + DecCoin defines a token with a denomination and a decimal + amount. + + + NOTE: The amount field is an Dec which implements the custom + method + + signatures required by gogoproto. + title: |- + QueryValidatorCommissionResponse is the response type for the + Query/ValidatorCommission RPC method + cosmos.distribution.v1beta1.QueryValidatorOutstandingRewardsResponse: + type: object + properties: + rewards: + type: object + properties: + rewards: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + DecCoin defines a token with a denomination and a decimal + amount. + + + NOTE: The amount field is an Dec which implements the custom + method + + signatures required by gogoproto. + description: >- + ValidatorOutstandingRewards represents outstanding (un-withdrawn) + rewards + + for a validator inexpensive to track, allows simple sanity checks. + description: |- + QueryValidatorOutstandingRewardsResponse is the response type for the + Query/ValidatorOutstandingRewards RPC method. + cosmos.distribution.v1beta1.QueryValidatorSlashesResponse: + type: object + properties: + slashes: + type: array + items: + type: object + properties: + validator_period: + type: string + format: uint64 + fraction: + type: string + description: |- + ValidatorSlashEvent represents a validator slash event. + Height is implicit within the store key. + This is needed to calculate appropriate amount of staking tokens + for delegations which are withdrawn after a slash has occurred. + description: slashes defines the slashes the validator received. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + QueryValidatorSlashesResponse is the response type for the + Query/ValidatorSlashes RPC method. + cosmos.distribution.v1beta1.ValidatorAccumulatedCommission: + type: object + properties: + commission: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: |- + DecCoin defines a token with a denomination and a decimal amount. + + NOTE: The amount field is an Dec which implements the custom method + signatures required by gogoproto. + description: |- + ValidatorAccumulatedCommission represents accumulated commission + for a validator kept as a running counter, can be withdrawn at any time. + cosmos.distribution.v1beta1.ValidatorOutstandingRewards: + type: object + properties: + rewards: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: |- + DecCoin defines a token with a denomination and a decimal amount. + + NOTE: The amount field is an Dec which implements the custom method + signatures required by gogoproto. + description: |- + ValidatorOutstandingRewards represents outstanding (un-withdrawn) rewards + for a validator inexpensive to track, allows simple sanity checks. + cosmos.distribution.v1beta1.ValidatorSlashEvent: + type: object + properties: + validator_period: + type: string + format: uint64 + fraction: + type: string + description: |- + ValidatorSlashEvent represents a validator slash event. + Height is implicit within the store key. + This is needed to calculate appropriate amount of staking tokens + for delegations which are withdrawn after a slash has occurred. + cosmos.base.abci.v1beta1.ABCIMessageLog: + type: object + properties: + msg_index: + type: integer + format: int64 + log: + type: string + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + value: + type: string + description: >- + Attribute defines an attribute wrapper where the key and value + are + + strings instead of raw bytes. + description: |- + StringEvent defines en Event object wrapper where all the attributes + contain key/value pairs that are strings instead of raw bytes. + description: |- + Events contains a slice of Event objects that were emitted during some + execution. + description: >- + ABCIMessageLog defines a structure containing an indexed tx ABCI message + log. + cosmos.base.abci.v1beta1.Attribute: + type: object + properties: + key: + type: string + value: + type: string + description: |- + Attribute defines an attribute wrapper where the key and value are + strings instead of raw bytes. + cosmos.base.abci.v1beta1.GasInfo: + type: object + properties: + gas_wanted: + type: string + format: uint64 + description: GasWanted is the maximum units of work we allow this tx to perform. + gas_used: + type: string + format: uint64 + description: GasUsed is the amount of gas actually consumed. + description: GasInfo defines tx execution gas context. + cosmos.base.abci.v1beta1.Result: + type: object + properties: + data: + type: string + format: byte + description: >- + Data is any data returned from message or handler execution. It MUST + be + + length prefixed in order to separate data from multiple message + executions. + log: + type: string + description: Log contains the log information from message or handler execution. + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + format: byte + value: + type: string + format: byte + index: + type: boolean + description: >- + EventAttribute is a single key-value pair, associated with an + event. + description: >- + Event allows application developers to attach additional information + to + + ResponseBeginBlock, ResponseEndBlock, ResponseCheckTx and + ResponseDeliverTx. + + Later, transactions may be queried using these events. + description: >- + Events contains a slice of Event objects that were emitted during + message + + or handler execution. + description: Result is the union of ResponseFormat and ResponseCheckTx. + cosmos.base.abci.v1beta1.StringEvent: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + value: + type: string + description: |- + Attribute defines an attribute wrapper where the key and value are + strings instead of raw bytes. + description: |- + StringEvent defines en Event object wrapper where all the attributes + contain key/value pairs that are strings instead of raw bytes. + cosmos.base.abci.v1beta1.TxResponse: + type: object + properties: + height: + type: string + format: int64 + title: The block height + txhash: + type: string + description: The transaction hash. + codespace: + type: string + title: Namespace for the Code + code: + type: integer + format: int64 + description: Response code. + data: + type: string + description: Result bytes, if any. + raw_log: + type: string + description: |- + The output of the application's logger (raw string). May be + non-deterministic. + logs: + type: array + items: + type: object + properties: + msg_index: + type: integer + format: int64 + log: + type: string + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + value: + type: string + description: >- + Attribute defines an attribute wrapper where the key and + value are + + strings instead of raw bytes. + description: >- + StringEvent defines en Event object wrapper where all the + attributes + + contain key/value pairs that are strings instead of raw bytes. + description: >- + Events contains a slice of Event objects that were emitted + during some + + execution. + description: >- + ABCIMessageLog defines a structure containing an indexed tx ABCI + message log. + description: >- + The output of the application's logger (typed). May be + non-deterministic. + info: + type: string + description: Additional information. May be non-deterministic. + gas_wanted: + type: string + format: int64 + description: Amount of gas requested for transaction. + gas_used: + type: string + format: int64 + description: Amount of gas consumed by transaction. + tx: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: The request transaction bytes. + timestamp: + type: string + description: >- + Time of the previous block. For heights > 1, it's the weighted median + of + + the timestamps of the valid votes in the block.LastCommit. For height + == 1, + + it's genesis time. + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + format: byte + value: + type: string + format: byte + index: + type: boolean + description: >- + EventAttribute is a single key-value pair, associated with an + event. + description: >- + Event allows application developers to attach additional information + to + + ResponseBeginBlock, ResponseEndBlock, ResponseCheckTx and + ResponseDeliverTx. + + Later, transactions may be queried using these events. + description: >- + Events defines all the events emitted by processing a transaction. + Note, + + these events include those emitted by processing all the messages and + those + + emitted from the ante handler. Whereas Logs contains the events, with + + additional metadata, emitted only by processing the messages. + + + Since: cosmos-sdk 0.42.11, 0.44.5, 0.45 + description: >- + TxResponse defines a structure containing relevant tx data and metadata. + The + + tags are stringified and the log is JSON decoded. + cosmos.crypto.multisig.v1beta1.CompactBitArray: + type: object + properties: + extra_bits_stored: + type: integer + format: int64 + elems: + type: string + format: byte + description: |- + CompactBitArray is an implementation of a space efficient bit array. + This is used to ensure that the encoded data takes up a minimal amount of + space after proto encoding. + This is not thread safe, and is not intended for concurrent usage. + cosmos.tx.signing.v1beta1.SignMode: + type: string + enum: + - SIGN_MODE_UNSPECIFIED + - SIGN_MODE_DIRECT + - SIGN_MODE_TEXTUAL + - SIGN_MODE_LEGACY_AMINO_JSON + - SIGN_MODE_EIP_191 + default: SIGN_MODE_UNSPECIFIED + description: |- + SignMode represents a signing mode with its own security guarantees. + + - SIGN_MODE_UNSPECIFIED: SIGN_MODE_UNSPECIFIED specifies an unknown signing mode and will be + rejected + - SIGN_MODE_DIRECT: SIGN_MODE_DIRECT specifies a signing mode which uses SignDoc and is + verified with raw bytes from Tx + - SIGN_MODE_TEXTUAL: SIGN_MODE_TEXTUAL is a future signing mode that will verify some + human-readable textual representation on top of the binary representation + from SIGN_MODE_DIRECT + - SIGN_MODE_LEGACY_AMINO_JSON: SIGN_MODE_LEGACY_AMINO_JSON is a backwards compatibility mode which uses + Amino JSON and will be removed in the future + - SIGN_MODE_EIP_191: SIGN_MODE_EIP_191 specifies the sign mode for EIP 191 signing on the Cosmos + SDK. Ref: https://eips.ethereum.org/EIPS/eip-191 + + Currently, SIGN_MODE_EIP_191 is registered as a SignMode enum variant, + but is not implemented on the SDK by default. To enable EIP-191, you need + to pass a custom `TxConfig` that has an implementation of + `SignModeHandler` for EIP-191. The SDK may decide to fully support + EIP-191 in the future. + + Since: cosmos-sdk 0.45.2 + cosmos.tx.v1beta1.AuthInfo: + type: object + properties: + signer_infos: + type: array + items: + type: object + properties: + public_key: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + public_key is the public key of the signer. It is optional for + accounts + + that already exist in state. If unset, the verifier can use the + required \ + + signer address for this position and lookup the public key. + mode_info: + title: >- + mode_info describes the signing mode of the signer and is a + nested + + structure to support nested multisig pubkey's + type: object + properties: + single: + title: single represents a single signer + type: object + properties: + mode: + title: mode is the signing mode of the single signer + type: string + enum: + - SIGN_MODE_UNSPECIFIED + - SIGN_MODE_DIRECT + - SIGN_MODE_TEXTUAL + - SIGN_MODE_LEGACY_AMINO_JSON + - SIGN_MODE_EIP_191 + default: SIGN_MODE_UNSPECIFIED + description: >- + SignMode represents a signing mode with its own security + guarantees. + + - SIGN_MODE_UNSPECIFIED: SIGN_MODE_UNSPECIFIED specifies an unknown signing mode and will be + rejected + - SIGN_MODE_DIRECT: SIGN_MODE_DIRECT specifies a signing mode which uses SignDoc and is + verified with raw bytes from Tx + - SIGN_MODE_TEXTUAL: SIGN_MODE_TEXTUAL is a future signing mode that will verify some + human-readable textual representation on top of the + binary representation + + from SIGN_MODE_DIRECT + - SIGN_MODE_LEGACY_AMINO_JSON: SIGN_MODE_LEGACY_AMINO_JSON is a backwards compatibility mode which uses + Amino JSON and will be removed in the future + - SIGN_MODE_EIP_191: SIGN_MODE_EIP_191 specifies the sign mode for EIP 191 signing on the Cosmos + SDK. Ref: https://eips.ethereum.org/EIPS/eip-191 + + + Currently, SIGN_MODE_EIP_191 is registered as a SignMode + enum variant, + + but is not implemented on the SDK by default. To enable + EIP-191, you need + + to pass a custom `TxConfig` that has an implementation + of + + `SignModeHandler` for EIP-191. The SDK may decide to + fully support + + EIP-191 in the future. + + + Since: cosmos-sdk 0.45.2 + multi: + title: multi represents a nested multisig signer + type: object + properties: + bitarray: + title: >- + bitarray specifies which keys within the multisig are + signing + type: object + properties: + extra_bits_stored: + type: integer + format: int64 + elems: + type: string + format: byte + description: >- + CompactBitArray is an implementation of a space + efficient bit array. + + This is used to ensure that the encoded data takes up a + minimal amount of + + space after proto encoding. + + This is not thread safe, and is not intended for + concurrent usage. + mode_infos: + type: array + items: {} + title: >- + mode_infos is the corresponding modes of the signers of + the multisig + + which could include nested multisig public keys + description: >- + ModeInfo describes the signing mode of a single or nested + multisig signer. + sequence: + type: string + format: uint64 + description: >- + sequence is the sequence of the account, which describes the + + number of committed transactions signed by a given address. It + is used to + + prevent replay attacks. + description: >- + SignerInfo describes the public key and signing mode of a single + top-level + + signer. + description: >- + signer_infos defines the signing modes for the required signers. The + number + + and order of elements must match the required signers from TxBody's + + messages. The first element is the primary signer and the one which + pays + + the fee. + fee: + description: >- + Fee is the fee and gas limit for the transaction. The first signer is + the + + primary signer and the one which pays the fee. The fee can be + calculated + + based on the cost of evaluating the body and doing signature + verification + + of the signers. This can be estimated via simulation. + type: object + properties: + amount: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom + method + + signatures required by gogoproto. + title: amount is the amount of coins to be paid as a fee + gas_limit: + type: string + format: uint64 + title: >- + gas_limit is the maximum gas that can be used in transaction + processing + + before an out of gas error occurs + payer: + type: string + description: >- + if unset, the first signer is responsible for paying the fees. If + set, the specified account must pay the fees. + + the payer must be a tx signer (and thus have signed this field in + AuthInfo). + + setting this field does *not* change the ordering of required + signers for the transaction. + granter: + type: string + title: >- + if set, the fee payer (either the first signer or the value of the + payer field) requests that a fee grant be used + + to pay fees instead of the fee payer's own balance. If an + appropriate fee grant does not exist or the chain does + + not support fee grants, this will fail + description: |- + AuthInfo describes the fee and signer modes that are used to sign a + transaction. + cosmos.tx.v1beta1.BroadcastMode: + type: string + enum: + - BROADCAST_MODE_UNSPECIFIED + - BROADCAST_MODE_BLOCK + - BROADCAST_MODE_SYNC + - BROADCAST_MODE_ASYNC + default: BROADCAST_MODE_UNSPECIFIED + description: >- + BroadcastMode specifies the broadcast mode for the TxService.Broadcast RPC + method. + + - BROADCAST_MODE_UNSPECIFIED: zero-value for mode ordering + - BROADCAST_MODE_BLOCK: BROADCAST_MODE_BLOCK defines a tx broadcasting mode where the client waits for + the tx to be committed in a block. + - BROADCAST_MODE_SYNC: BROADCAST_MODE_SYNC defines a tx broadcasting mode where the client waits for + a CheckTx execution response only. + - BROADCAST_MODE_ASYNC: BROADCAST_MODE_ASYNC defines a tx broadcasting mode where the client returns + immediately. + cosmos.tx.v1beta1.BroadcastTxRequest: + type: object + properties: + tx_bytes: + type: string + format: byte + description: tx_bytes is the raw transaction. + mode: + type: string + enum: + - BROADCAST_MODE_UNSPECIFIED + - BROADCAST_MODE_BLOCK + - BROADCAST_MODE_SYNC + - BROADCAST_MODE_ASYNC + default: BROADCAST_MODE_UNSPECIFIED + description: >- + BroadcastMode specifies the broadcast mode for the TxService.Broadcast + RPC method. + + - BROADCAST_MODE_UNSPECIFIED: zero-value for mode ordering + - BROADCAST_MODE_BLOCK: BROADCAST_MODE_BLOCK defines a tx broadcasting mode where the client waits for + the tx to be committed in a block. + - BROADCAST_MODE_SYNC: BROADCAST_MODE_SYNC defines a tx broadcasting mode where the client waits for + a CheckTx execution response only. + - BROADCAST_MODE_ASYNC: BROADCAST_MODE_ASYNC defines a tx broadcasting mode where the client returns + immediately. + description: |- + BroadcastTxRequest is the request type for the Service.BroadcastTxRequest + RPC method. + cosmos.tx.v1beta1.BroadcastTxResponse: + type: object + properties: + tx_response: + type: object + properties: + height: + type: string + format: int64 + title: The block height + txhash: + type: string + description: The transaction hash. + codespace: + type: string + title: Namespace for the Code + code: + type: integer + format: int64 + description: Response code. + data: + type: string + description: Result bytes, if any. + raw_log: + type: string + description: |- + The output of the application's logger (raw string). May be + non-deterministic. + logs: + type: array + items: + type: object + properties: + msg_index: + type: integer + format: int64 + log: + type: string + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + value: + type: string + description: >- + Attribute defines an attribute wrapper where the key + and value are + + strings instead of raw bytes. + description: >- + StringEvent defines en Event object wrapper where all the + attributes + + contain key/value pairs that are strings instead of raw + bytes. + description: >- + Events contains a slice of Event objects that were emitted + during some + + execution. + description: >- + ABCIMessageLog defines a structure containing an indexed tx ABCI + message log. + description: >- + The output of the application's logger (typed). May be + non-deterministic. + info: + type: string + description: Additional information. May be non-deterministic. + gas_wanted: + type: string + format: int64 + description: Amount of gas requested for transaction. + gas_used: + type: string + format: int64 + description: Amount of gas consumed by transaction. + tx: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: The request transaction bytes. + timestamp: + type: string + description: >- + Time of the previous block. For heights > 1, it's the weighted + median of + + the timestamps of the valid votes in the block.LastCommit. For + height == 1, + + it's genesis time. + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + format: byte + value: + type: string + format: byte + index: + type: boolean + description: >- + EventAttribute is a single key-value pair, associated with + an event. + description: >- + Event allows application developers to attach additional + information to + + ResponseBeginBlock, ResponseEndBlock, ResponseCheckTx and + ResponseDeliverTx. + + Later, transactions may be queried using these events. + description: >- + Events defines all the events emitted by processing a transaction. + Note, + + these events include those emitted by processing all the messages + and those + + emitted from the ante handler. Whereas Logs contains the events, + with + + additional metadata, emitted only by processing the messages. + + + Since: cosmos-sdk 0.42.11, 0.44.5, 0.45 + description: >- + TxResponse defines a structure containing relevant tx data and + metadata. The + + tags are stringified and the log is JSON decoded. + description: |- + BroadcastTxResponse is the response type for the + Service.BroadcastTx method. + cosmos.tx.v1beta1.Fee: + type: object + properties: + amount: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: |- + Coin defines a token with a denomination and an amount. + + NOTE: The amount field is an Int which implements the custom method + signatures required by gogoproto. + title: amount is the amount of coins to be paid as a fee + gas_limit: + type: string + format: uint64 + title: >- + gas_limit is the maximum gas that can be used in transaction + processing + + before an out of gas error occurs + payer: + type: string + description: >- + if unset, the first signer is responsible for paying the fees. If set, + the specified account must pay the fees. + + the payer must be a tx signer (and thus have signed this field in + AuthInfo). + + setting this field does *not* change the ordering of required signers + for the transaction. + granter: + type: string + title: >- + if set, the fee payer (either the first signer or the value of the + payer field) requests that a fee grant be used + + to pay fees instead of the fee payer's own balance. If an appropriate + fee grant does not exist or the chain does + + not support fee grants, this will fail + description: >- + Fee includes the amount of coins paid in fees and the maximum + + gas to be used by the transaction. The ratio yields an effective + "gasprice", + + which must be above some miminum to be accepted into the mempool. + cosmos.tx.v1beta1.GetBlockWithTxsResponse: + type: object + properties: + txs: + type: array + items: + type: object + properties: + body: + title: body is the processable content of the transaction + type: object + properties: + messages: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + messages is a list of messages to be executed. The required + signers of + + those messages define the number and order of elements in + AuthInfo's + + signer_infos and Tx's signatures. Each required signer + address is added to + + the list only the first time it occurs. + + By convention, the first required signer (usually from the + first message) + + is referred to as the primary signer and pays the fee for + the whole + + transaction. + memo: + type: string + description: >- + memo is any arbitrary note/comment to be added to the + transaction. + + WARNING: in clients, any publicly exposed text should not be + called memo, + + but should be called `note` instead (see + https://github.com/cosmos/cosmos-sdk/issues/9122). + timeout_height: + type: string + format: uint64 + title: >- + timeout is the block height after which this transaction + will not + + be processed by the chain + extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be added by + chains + + when the default options are not sufficient. If any of these + are present + + and can't be handled, the transaction will be rejected + non_critical_extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be added by + chains + + when the default options are not sufficient. If any of these + are present + + and can't be handled, they will be ignored + description: TxBody is the body of a transaction that all signers sign over. + auth_info: + title: >- + auth_info is the authorization related content of the + transaction, + + specifically signers, signer modes and fee + type: object + properties: + signer_infos: + type: array + items: + type: object + properties: + public_key: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + public_key is the public key of the signer. It is + optional for accounts + + that already exist in state. If unset, the verifier + can use the required \ + + signer address for this position and lookup the public + key. + mode_info: + title: >- + mode_info describes the signing mode of the signer and + is a nested + + structure to support nested multisig pubkey's + type: object + properties: + single: + title: single represents a single signer + type: object + properties: + mode: + title: mode is the signing mode of the single signer + type: string + enum: + - SIGN_MODE_UNSPECIFIED + - SIGN_MODE_DIRECT + - SIGN_MODE_TEXTUAL + - SIGN_MODE_LEGACY_AMINO_JSON + - SIGN_MODE_EIP_191 + default: SIGN_MODE_UNSPECIFIED + description: >- + SignMode represents a signing mode with its + own security guarantees. + + - SIGN_MODE_UNSPECIFIED: SIGN_MODE_UNSPECIFIED specifies an unknown signing mode and will be + rejected + - SIGN_MODE_DIRECT: SIGN_MODE_DIRECT specifies a signing mode which uses SignDoc and is + verified with raw bytes from Tx + - SIGN_MODE_TEXTUAL: SIGN_MODE_TEXTUAL is a future signing mode that will verify some + human-readable textual representation on top + of the binary representation + + from SIGN_MODE_DIRECT + - SIGN_MODE_LEGACY_AMINO_JSON: SIGN_MODE_LEGACY_AMINO_JSON is a backwards compatibility mode which uses + Amino JSON and will be removed in the future + - SIGN_MODE_EIP_191: SIGN_MODE_EIP_191 specifies the sign mode for EIP 191 signing on the Cosmos + SDK. Ref: + https://eips.ethereum.org/EIPS/eip-191 + + + Currently, SIGN_MODE_EIP_191 is registered as + a SignMode enum variant, + + but is not implemented on the SDK by default. + To enable EIP-191, you need + + to pass a custom `TxConfig` that has an + implementation of + + `SignModeHandler` for EIP-191. The SDK may + decide to fully support + + EIP-191 in the future. + + + Since: cosmos-sdk 0.45.2 + multi: + title: multi represents a nested multisig signer + type: object + properties: + bitarray: + title: >- + bitarray specifies which keys within the + multisig are signing + type: object + properties: + extra_bits_stored: + type: integer + format: int64 + elems: + type: string + format: byte + description: >- + CompactBitArray is an implementation of a + space efficient bit array. + + This is used to ensure that the encoded data + takes up a minimal amount of + + space after proto encoding. + + This is not thread safe, and is not intended + for concurrent usage. + mode_infos: + type: array + items: {} + title: >- + mode_infos is the corresponding modes of the + signers of the multisig + + which could include nested multisig public + keys + description: >- + ModeInfo describes the signing mode of a single or + nested multisig signer. + sequence: + type: string + format: uint64 + description: >- + sequence is the sequence of the account, which + describes the + + number of committed transactions signed by a given + address. It is used to + + prevent replay attacks. + description: >- + SignerInfo describes the public key and signing mode of a + single top-level + + signer. + description: >- + signer_infos defines the signing modes for the required + signers. The number + + and order of elements must match the required signers from + TxBody's + + messages. The first element is the primary signer and the + one which pays + + the fee. + fee: + description: >- + Fee is the fee and gas limit for the transaction. The first + signer is the + + primary signer and the one which pays the fee. The fee can + be calculated + + based on the cost of evaluating the body and doing signature + verification + + of the signers. This can be estimated via simulation. + type: object + properties: + amount: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an + amount. + + + NOTE: The amount field is an Int which implements the + custom method + + signatures required by gogoproto. + title: amount is the amount of coins to be paid as a fee + gas_limit: + type: string + format: uint64 + title: >- + gas_limit is the maximum gas that can be used in + transaction processing + + before an out of gas error occurs + payer: + type: string + description: >- + if unset, the first signer is responsible for paying the + fees. If set, the specified account must pay the fees. + + the payer must be a tx signer (and thus have signed this + field in AuthInfo). + + setting this field does *not* change the ordering of + required signers for the transaction. + granter: + type: string + title: >- + if set, the fee payer (either the first signer or the + value of the payer field) requests that a fee grant be + used + + to pay fees instead of the fee payer's own balance. If + an appropriate fee grant does not exist or the chain + does + + not support fee grants, this will fail + description: >- + AuthInfo describes the fee and signer modes that are used to + sign a + + transaction. + signatures: + type: array + items: + type: string + format: byte + description: >- + signatures is a list of signatures that matches the length and + order of + + AuthInfo's signer_infos to allow connecting signature meta + information like + + public key and signing mode by position. + description: Tx is the standard type used for broadcasting transactions. + description: txs are the transactions in the block. + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + block: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules for processing a block + in the blockchain, + + including all blockchain data structures and the rules of the + application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: hashes from the app output from the prev block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: Header defines the structure of a block header. + data: + type: object + properties: + txs: + type: array + items: + type: string + format: byte + description: >- + Txs that will be applied by state @ block.Height+1. + + NOTE: not all txs here are valid. We're just agreeing on the + order first. + + This means that block.AppHash does not include these txs. + title: Data contains the set of transactions included in the block + evidence: + type: object + properties: + evidence: + type: array + items: + type: object + properties: + duplicate_vote_evidence: + type: object + properties: + vote_a: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: >- + SignedMsgType is a type of signed message in the + consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or commit vote + from validators for + + consensus. + vote_b: + type: object + properties: + type: + type: string + enum: + - SIGNED_MSG_TYPE_UNKNOWN + - SIGNED_MSG_TYPE_PREVOTE + - SIGNED_MSG_TYPE_PRECOMMIT + - SIGNED_MSG_TYPE_PROPOSAL + default: SIGNED_MSG_TYPE_UNKNOWN + description: >- + SignedMsgType is a type of signed message in the + consensus. + + - SIGNED_MSG_TYPE_PREVOTE: Votes + - SIGNED_MSG_TYPE_PROPOSAL: Proposals + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + timestamp: + type: string + format: date-time + validator_address: + type: string + format: byte + validator_index: + type: integer + format: int32 + signature: + type: string + format: byte + description: >- + Vote represents a prevote, precommit, or commit vote + from validators for + + consensus. + total_voting_power: + type: string + format: int64 + validator_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: >- + DuplicateVoteEvidence contains evidence of a validator + signed two conflicting votes. + light_client_attack_evidence: + type: object + properties: + conflicting_block: + type: object + properties: + signed_header: + type: object + properties: + header: + type: object + properties: + version: + title: basic block info + type: object + properties: + block: + type: string + format: uint64 + app: + type: string + format: uint64 + description: >- + Consensus captures the consensus rules + for processing a block in the + blockchain, + + including all blockchain data structures + and the rules of the application's + + state transition machine. + chain_id: + type: string + height: + type: string + format: int64 + time: + type: string + format: date-time + last_block_id: + title: prev block info + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + last_commit_hash: + type: string + format: byte + title: hashes of block data + data_hash: + type: string + format: byte + validators_hash: + type: string + format: byte + title: >- + hashes from the app output from the prev + block + next_validators_hash: + type: string + format: byte + consensus_hash: + type: string + format: byte + app_hash: + type: string + format: byte + last_results_hash: + type: string + format: byte + evidence_hash: + type: string + format: byte + title: consensus info + proposer_address: + type: string + format: byte + description: >- + Header defines the structure of a block + header. + commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: >- + BlockIdFlag indicates which BlcokID the + signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: >- + CommitSig is a part of the Vote included + in a Commit. + description: >- + Commit contains the evidence that a block + was committed by a set of validators. + validator_set: + type: object + properties: + validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: >- + PublicKey defines the keys available for + use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + proposer: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: >- + PublicKey defines the keys available for + use with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + common_height: + type: string + format: int64 + byzantine_validators: + type: array + items: + type: object + properties: + address: + type: string + format: byte + pub_key: + type: object + properties: + ed25519: + type: string + format: byte + secp256k1: + type: string + format: byte + title: >- + PublicKey defines the keys available for use + with Validators + voting_power: + type: string + format: int64 + proposer_priority: + type: string + format: int64 + total_voting_power: + type: string + format: int64 + timestamp: + type: string + format: date-time + description: >- + LightClientAttackEvidence contains evidence of a set of + validators attempting to mislead a light client. + last_commit: + type: object + properties: + height: + type: string + format: int64 + round: + type: integer + format: int32 + block_id: + type: object + properties: + hash: + type: string + format: byte + part_set_header: + type: object + properties: + total: + type: integer + format: int64 + hash: + type: string + format: byte + title: PartsetHeader + title: BlockID + signatures: + type: array + items: + type: object + properties: + block_id_flag: + type: string + enum: + - BLOCK_ID_FLAG_UNKNOWN + - BLOCK_ID_FLAG_ABSENT + - BLOCK_ID_FLAG_COMMIT + - BLOCK_ID_FLAG_NIL + default: BLOCK_ID_FLAG_UNKNOWN + title: BlockIdFlag indicates which BlcokID the signature is for + validator_address: + type: string + format: byte + timestamp: + type: string + format: date-time + signature: + type: string + format: byte + description: CommitSig is a part of the Vote included in a Commit. + description: >- + Commit contains the evidence that a block was committed by a set + of validators. + pagination: + description: pagination defines a pagination for the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + GetBlockWithTxsResponse is the response type for the + Service.GetBlockWithTxs method. + + + Since: cosmos-sdk 0.45.2 + cosmos.tx.v1beta1.GetTxResponse: + type: object + properties: + tx: + type: object + properties: + body: + title: body is the processable content of the transaction + type: object + properties: + messages: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + messages is a list of messages to be executed. The required + signers of + + those messages define the number and order of elements in + AuthInfo's + + signer_infos and Tx's signatures. Each required signer address + is added to + + the list only the first time it occurs. + + By convention, the first required signer (usually from the + first message) + + is referred to as the primary signer and pays the fee for the + whole + + transaction. + memo: + type: string + description: >- + memo is any arbitrary note/comment to be added to the + transaction. + + WARNING: in clients, any publicly exposed text should not be + called memo, + + but should be called `note` instead (see + https://github.com/cosmos/cosmos-sdk/issues/9122). + timeout_height: + type: string + format: uint64 + title: >- + timeout is the block height after which this transaction will + not + + be processed by the chain + extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be added by + chains + + when the default options are not sufficient. If any of these + are present + + and can't be handled, the transaction will be rejected + non_critical_extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be added by + chains + + when the default options are not sufficient. If any of these + are present + + and can't be handled, they will be ignored + description: TxBody is the body of a transaction that all signers sign over. + auth_info: + title: |- + auth_info is the authorization related content of the transaction, + specifically signers, signer modes and fee + type: object + properties: + signer_infos: + type: array + items: + type: object + properties: + public_key: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + public_key is the public key of the signer. It is + optional for accounts + + that already exist in state. If unset, the verifier can + use the required \ + + signer address for this position and lookup the public + key. + mode_info: + title: >- + mode_info describes the signing mode of the signer and + is a nested + + structure to support nested multisig pubkey's + type: object + properties: + single: + title: single represents a single signer + type: object + properties: + mode: + title: mode is the signing mode of the single signer + type: string + enum: + - SIGN_MODE_UNSPECIFIED + - SIGN_MODE_DIRECT + - SIGN_MODE_TEXTUAL + - SIGN_MODE_LEGACY_AMINO_JSON + - SIGN_MODE_EIP_191 + default: SIGN_MODE_UNSPECIFIED + description: >- + SignMode represents a signing mode with its own + security guarantees. + + - SIGN_MODE_UNSPECIFIED: SIGN_MODE_UNSPECIFIED specifies an unknown signing mode and will be + rejected + - SIGN_MODE_DIRECT: SIGN_MODE_DIRECT specifies a signing mode which uses SignDoc and is + verified with raw bytes from Tx + - SIGN_MODE_TEXTUAL: SIGN_MODE_TEXTUAL is a future signing mode that will verify some + human-readable textual representation on top of + the binary representation + + from SIGN_MODE_DIRECT + - SIGN_MODE_LEGACY_AMINO_JSON: SIGN_MODE_LEGACY_AMINO_JSON is a backwards compatibility mode which uses + Amino JSON and will be removed in the future + - SIGN_MODE_EIP_191: SIGN_MODE_EIP_191 specifies the sign mode for EIP 191 signing on the Cosmos + SDK. Ref: https://eips.ethereum.org/EIPS/eip-191 + + + Currently, SIGN_MODE_EIP_191 is registered as a + SignMode enum variant, + + but is not implemented on the SDK by default. To + enable EIP-191, you need + + to pass a custom `TxConfig` that has an + implementation of + + `SignModeHandler` for EIP-191. The SDK may + decide to fully support + + EIP-191 in the future. + + + Since: cosmos-sdk 0.45.2 + multi: + title: multi represents a nested multisig signer + type: object + properties: + bitarray: + title: >- + bitarray specifies which keys within the + multisig are signing + type: object + properties: + extra_bits_stored: + type: integer + format: int64 + elems: + type: string + format: byte + description: >- + CompactBitArray is an implementation of a space + efficient bit array. + + This is used to ensure that the encoded data + takes up a minimal amount of + + space after proto encoding. + + This is not thread safe, and is not intended for + concurrent usage. + mode_infos: + type: array + items: {} + title: >- + mode_infos is the corresponding modes of the + signers of the multisig + + which could include nested multisig public keys + description: >- + ModeInfo describes the signing mode of a single or + nested multisig signer. + sequence: + type: string + format: uint64 + description: >- + sequence is the sequence of the account, which describes + the + + number of committed transactions signed by a given + address. It is used to + + prevent replay attacks. + description: >- + SignerInfo describes the public key and signing mode of a + single top-level + + signer. + description: >- + signer_infos defines the signing modes for the required + signers. The number + + and order of elements must match the required signers from + TxBody's + + messages. The first element is the primary signer and the one + which pays + + the fee. + fee: + description: >- + Fee is the fee and gas limit for the transaction. The first + signer is the + + primary signer and the one which pays the fee. The fee can be + calculated + + based on the cost of evaluating the body and doing signature + verification + + of the signers. This can be estimated via simulation. + type: object + properties: + amount: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the + custom method + + signatures required by gogoproto. + title: amount is the amount of coins to be paid as a fee + gas_limit: + type: string + format: uint64 + title: >- + gas_limit is the maximum gas that can be used in + transaction processing + + before an out of gas error occurs + payer: + type: string + description: >- + if unset, the first signer is responsible for paying the + fees. If set, the specified account must pay the fees. + + the payer must be a tx signer (and thus have signed this + field in AuthInfo). + + setting this field does *not* change the ordering of + required signers for the transaction. + granter: + type: string + title: >- + if set, the fee payer (either the first signer or the + value of the payer field) requests that a fee grant be + used + + to pay fees instead of the fee payer's own balance. If an + appropriate fee grant does not exist or the chain does + + not support fee grants, this will fail + description: >- + AuthInfo describes the fee and signer modes that are used to sign + a + + transaction. + signatures: + type: array + items: + type: string + format: byte + description: >- + signatures is a list of signatures that matches the length and + order of + + AuthInfo's signer_infos to allow connecting signature meta + information like + + public key and signing mode by position. + description: Tx is the standard type used for broadcasting transactions. + tx_response: + type: object + properties: + height: + type: string + format: int64 + title: The block height + txhash: + type: string + description: The transaction hash. + codespace: + type: string + title: Namespace for the Code + code: + type: integer + format: int64 + description: Response code. + data: + type: string + description: Result bytes, if any. + raw_log: + type: string + description: |- + The output of the application's logger (raw string). May be + non-deterministic. + logs: + type: array + items: + type: object + properties: + msg_index: + type: integer + format: int64 + log: + type: string + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + value: + type: string + description: >- + Attribute defines an attribute wrapper where the key + and value are + + strings instead of raw bytes. + description: >- + StringEvent defines en Event object wrapper where all the + attributes + + contain key/value pairs that are strings instead of raw + bytes. + description: >- + Events contains a slice of Event objects that were emitted + during some + + execution. + description: >- + ABCIMessageLog defines a structure containing an indexed tx ABCI + message log. + description: >- + The output of the application's logger (typed). May be + non-deterministic. + info: + type: string + description: Additional information. May be non-deterministic. + gas_wanted: + type: string + format: int64 + description: Amount of gas requested for transaction. + gas_used: + type: string + format: int64 + description: Amount of gas consumed by transaction. + tx: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: The request transaction bytes. + timestamp: + type: string + description: >- + Time of the previous block. For heights > 1, it's the weighted + median of + + the timestamps of the valid votes in the block.LastCommit. For + height == 1, + + it's genesis time. + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + format: byte + value: + type: string + format: byte + index: + type: boolean + description: >- + EventAttribute is a single key-value pair, associated with + an event. + description: >- + Event allows application developers to attach additional + information to + + ResponseBeginBlock, ResponseEndBlock, ResponseCheckTx and + ResponseDeliverTx. + + Later, transactions may be queried using these events. + description: >- + Events defines all the events emitted by processing a transaction. + Note, + + these events include those emitted by processing all the messages + and those + + emitted from the ante handler. Whereas Logs contains the events, + with + + additional metadata, emitted only by processing the messages. + + + Since: cosmos-sdk 0.42.11, 0.44.5, 0.45 + description: >- + TxResponse defines a structure containing relevant tx data and + metadata. The + + tags are stringified and the log is JSON decoded. + description: GetTxResponse is the response type for the Service.GetTx method. + cosmos.tx.v1beta1.GetTxsEventResponse: + type: object + properties: + txs: + type: array + items: + type: object + properties: + body: + title: body is the processable content of the transaction + type: object + properties: + messages: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + messages is a list of messages to be executed. The required + signers of + + those messages define the number and order of elements in + AuthInfo's + + signer_infos and Tx's signatures. Each required signer + address is added to + + the list only the first time it occurs. + + By convention, the first required signer (usually from the + first message) + + is referred to as the primary signer and pays the fee for + the whole + + transaction. + memo: + type: string + description: >- + memo is any arbitrary note/comment to be added to the + transaction. + + WARNING: in clients, any publicly exposed text should not be + called memo, + + but should be called `note` instead (see + https://github.com/cosmos/cosmos-sdk/issues/9122). + timeout_height: + type: string + format: uint64 + title: >- + timeout is the block height after which this transaction + will not + + be processed by the chain + extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be added by + chains + + when the default options are not sufficient. If any of these + are present + + and can't be handled, the transaction will be rejected + non_critical_extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be added by + chains + + when the default options are not sufficient. If any of these + are present + + and can't be handled, they will be ignored + description: TxBody is the body of a transaction that all signers sign over. + auth_info: + title: >- + auth_info is the authorization related content of the + transaction, + + specifically signers, signer modes and fee + type: object + properties: + signer_infos: + type: array + items: + type: object + properties: + public_key: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + public_key is the public key of the signer. It is + optional for accounts + + that already exist in state. If unset, the verifier + can use the required \ + + signer address for this position and lookup the public + key. + mode_info: + title: >- + mode_info describes the signing mode of the signer and + is a nested + + structure to support nested multisig pubkey's + type: object + properties: + single: + title: single represents a single signer + type: object + properties: + mode: + title: mode is the signing mode of the single signer + type: string + enum: + - SIGN_MODE_UNSPECIFIED + - SIGN_MODE_DIRECT + - SIGN_MODE_TEXTUAL + - SIGN_MODE_LEGACY_AMINO_JSON + - SIGN_MODE_EIP_191 + default: SIGN_MODE_UNSPECIFIED + description: >- + SignMode represents a signing mode with its + own security guarantees. + + - SIGN_MODE_UNSPECIFIED: SIGN_MODE_UNSPECIFIED specifies an unknown signing mode and will be + rejected + - SIGN_MODE_DIRECT: SIGN_MODE_DIRECT specifies a signing mode which uses SignDoc and is + verified with raw bytes from Tx + - SIGN_MODE_TEXTUAL: SIGN_MODE_TEXTUAL is a future signing mode that will verify some + human-readable textual representation on top + of the binary representation + + from SIGN_MODE_DIRECT + - SIGN_MODE_LEGACY_AMINO_JSON: SIGN_MODE_LEGACY_AMINO_JSON is a backwards compatibility mode which uses + Amino JSON and will be removed in the future + - SIGN_MODE_EIP_191: SIGN_MODE_EIP_191 specifies the sign mode for EIP 191 signing on the Cosmos + SDK. Ref: + https://eips.ethereum.org/EIPS/eip-191 + + + Currently, SIGN_MODE_EIP_191 is registered as + a SignMode enum variant, + + but is not implemented on the SDK by default. + To enable EIP-191, you need + + to pass a custom `TxConfig` that has an + implementation of + + `SignModeHandler` for EIP-191. The SDK may + decide to fully support + + EIP-191 in the future. + + + Since: cosmos-sdk 0.45.2 + multi: + title: multi represents a nested multisig signer + type: object + properties: + bitarray: + title: >- + bitarray specifies which keys within the + multisig are signing + type: object + properties: + extra_bits_stored: + type: integer + format: int64 + elems: + type: string + format: byte + description: >- + CompactBitArray is an implementation of a + space efficient bit array. + + This is used to ensure that the encoded data + takes up a minimal amount of + + space after proto encoding. + + This is not thread safe, and is not intended + for concurrent usage. + mode_infos: + type: array + items: {} + title: >- + mode_infos is the corresponding modes of the + signers of the multisig + + which could include nested multisig public + keys + description: >- + ModeInfo describes the signing mode of a single or + nested multisig signer. + sequence: + type: string + format: uint64 + description: >- + sequence is the sequence of the account, which + describes the + + number of committed transactions signed by a given + address. It is used to + + prevent replay attacks. + description: >- + SignerInfo describes the public key and signing mode of a + single top-level + + signer. + description: >- + signer_infos defines the signing modes for the required + signers. The number + + and order of elements must match the required signers from + TxBody's + + messages. The first element is the primary signer and the + one which pays + + the fee. + fee: + description: >- + Fee is the fee and gas limit for the transaction. The first + signer is the + + primary signer and the one which pays the fee. The fee can + be calculated + + based on the cost of evaluating the body and doing signature + verification + + of the signers. This can be estimated via simulation. + type: object + properties: + amount: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an + amount. + + + NOTE: The amount field is an Int which implements the + custom method + + signatures required by gogoproto. + title: amount is the amount of coins to be paid as a fee + gas_limit: + type: string + format: uint64 + title: >- + gas_limit is the maximum gas that can be used in + transaction processing + + before an out of gas error occurs + payer: + type: string + description: >- + if unset, the first signer is responsible for paying the + fees. If set, the specified account must pay the fees. + + the payer must be a tx signer (and thus have signed this + field in AuthInfo). + + setting this field does *not* change the ordering of + required signers for the transaction. + granter: + type: string + title: >- + if set, the fee payer (either the first signer or the + value of the payer field) requests that a fee grant be + used + + to pay fees instead of the fee payer's own balance. If + an appropriate fee grant does not exist or the chain + does + + not support fee grants, this will fail + description: >- + AuthInfo describes the fee and signer modes that are used to + sign a + + transaction. + signatures: + type: array + items: + type: string + format: byte + description: >- + signatures is a list of signatures that matches the length and + order of + + AuthInfo's signer_infos to allow connecting signature meta + information like + + public key and signing mode by position. + description: Tx is the standard type used for broadcasting transactions. + description: txs is the list of queried transactions. + tx_responses: + type: array + items: + type: object + properties: + height: + type: string + format: int64 + title: The block height + txhash: + type: string + description: The transaction hash. + codespace: + type: string + title: Namespace for the Code + code: + type: integer + format: int64 + description: Response code. + data: + type: string + description: Result bytes, if any. + raw_log: + type: string + description: |- + The output of the application's logger (raw string). May be + non-deterministic. + logs: + type: array + items: + type: object + properties: + msg_index: + type: integer + format: int64 + log: + type: string + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + value: + type: string + description: >- + Attribute defines an attribute wrapper where the + key and value are + + strings instead of raw bytes. + description: >- + StringEvent defines en Event object wrapper where all + the attributes + + contain key/value pairs that are strings instead of raw + bytes. + description: >- + Events contains a slice of Event objects that were emitted + during some + + execution. + description: >- + ABCIMessageLog defines a structure containing an indexed tx + ABCI message log. + description: >- + The output of the application's logger (typed). May be + non-deterministic. + info: + type: string + description: Additional information. May be non-deterministic. + gas_wanted: + type: string + format: int64 + description: Amount of gas requested for transaction. + gas_used: + type: string + format: int64 + description: Amount of gas consumed by transaction. + tx: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: The request transaction bytes. + timestamp: + type: string + description: >- + Time of the previous block. For heights > 1, it's the weighted + median of + + the timestamps of the valid votes in the block.LastCommit. For + height == 1, + + it's genesis time. + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + format: byte + value: + type: string + format: byte + index: + type: boolean + description: >- + EventAttribute is a single key-value pair, associated + with an event. + description: >- + Event allows application developers to attach additional + information to + + ResponseBeginBlock, ResponseEndBlock, ResponseCheckTx and + ResponseDeliverTx. + + Later, transactions may be queried using these events. + description: >- + Events defines all the events emitted by processing a + transaction. Note, + + these events include those emitted by processing all the + messages and those + + emitted from the ante handler. Whereas Logs contains the events, + with + + additional metadata, emitted only by processing the messages. + + + Since: cosmos-sdk 0.42.11, 0.44.5, 0.45 + description: >- + TxResponse defines a structure containing relevant tx data and + metadata. The + + tags are stringified and the log is JSON decoded. + description: tx_responses is the list of queried TxResponses. + pagination: + description: pagination defines a pagination for the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + GetTxsEventResponse is the response type for the Service.TxsByEvents + RPC method. + cosmos.tx.v1beta1.ModeInfo: + type: object + properties: + single: + title: single represents a single signer + type: object + properties: + mode: + title: mode is the signing mode of the single signer + type: string + enum: + - SIGN_MODE_UNSPECIFIED + - SIGN_MODE_DIRECT + - SIGN_MODE_TEXTUAL + - SIGN_MODE_LEGACY_AMINO_JSON + - SIGN_MODE_EIP_191 + default: SIGN_MODE_UNSPECIFIED + description: >- + SignMode represents a signing mode with its own security + guarantees. + + - SIGN_MODE_UNSPECIFIED: SIGN_MODE_UNSPECIFIED specifies an unknown signing mode and will be + rejected + - SIGN_MODE_DIRECT: SIGN_MODE_DIRECT specifies a signing mode which uses SignDoc and is + verified with raw bytes from Tx + - SIGN_MODE_TEXTUAL: SIGN_MODE_TEXTUAL is a future signing mode that will verify some + human-readable textual representation on top of the binary + representation + + from SIGN_MODE_DIRECT + - SIGN_MODE_LEGACY_AMINO_JSON: SIGN_MODE_LEGACY_AMINO_JSON is a backwards compatibility mode which uses + Amino JSON and will be removed in the future + - SIGN_MODE_EIP_191: SIGN_MODE_EIP_191 specifies the sign mode for EIP 191 signing on the Cosmos + SDK. Ref: https://eips.ethereum.org/EIPS/eip-191 + + + Currently, SIGN_MODE_EIP_191 is registered as a SignMode enum + variant, + + but is not implemented on the SDK by default. To enable EIP-191, + you need + + to pass a custom `TxConfig` that has an implementation of + + `SignModeHandler` for EIP-191. The SDK may decide to fully support + + EIP-191 in the future. + + + Since: cosmos-sdk 0.45.2 + multi: + title: multi represents a nested multisig signer + type: object + properties: + bitarray: + title: bitarray specifies which keys within the multisig are signing + type: object + properties: + extra_bits_stored: + type: integer + format: int64 + elems: + type: string + format: byte + description: >- + CompactBitArray is an implementation of a space efficient bit + array. + + This is used to ensure that the encoded data takes up a minimal + amount of + + space after proto encoding. + + This is not thread safe, and is not intended for concurrent usage. + mode_infos: + type: array + items: {} + title: >- + mode_infos is the corresponding modes of the signers of the + multisig + + which could include nested multisig public keys + description: ModeInfo describes the signing mode of a single or nested multisig signer. + cosmos.tx.v1beta1.ModeInfo.Multi: + type: object + properties: + bitarray: + title: bitarray specifies which keys within the multisig are signing + type: object + properties: + extra_bits_stored: + type: integer + format: int64 + elems: + type: string + format: byte + description: >- + CompactBitArray is an implementation of a space efficient bit array. + + This is used to ensure that the encoded data takes up a minimal amount + of + + space after proto encoding. + + This is not thread safe, and is not intended for concurrent usage. + mode_infos: + type: array + items: {} + title: |- + mode_infos is the corresponding modes of the signers of the multisig + which could include nested multisig public keys + title: Multi is the mode info for a multisig public key + cosmos.tx.v1beta1.ModeInfo.Single: + type: object + properties: + mode: + title: mode is the signing mode of the single signer + type: string + enum: + - SIGN_MODE_UNSPECIFIED + - SIGN_MODE_DIRECT + - SIGN_MODE_TEXTUAL + - SIGN_MODE_LEGACY_AMINO_JSON + - SIGN_MODE_EIP_191 + default: SIGN_MODE_UNSPECIFIED + description: >- + SignMode represents a signing mode with its own security guarantees. + + - SIGN_MODE_UNSPECIFIED: SIGN_MODE_UNSPECIFIED specifies an unknown signing mode and will be + rejected + - SIGN_MODE_DIRECT: SIGN_MODE_DIRECT specifies a signing mode which uses SignDoc and is + verified with raw bytes from Tx + - SIGN_MODE_TEXTUAL: SIGN_MODE_TEXTUAL is a future signing mode that will verify some + human-readable textual representation on top of the binary + representation + + from SIGN_MODE_DIRECT + - SIGN_MODE_LEGACY_AMINO_JSON: SIGN_MODE_LEGACY_AMINO_JSON is a backwards compatibility mode which uses + Amino JSON and will be removed in the future + - SIGN_MODE_EIP_191: SIGN_MODE_EIP_191 specifies the sign mode for EIP 191 signing on the Cosmos + SDK. Ref: https://eips.ethereum.org/EIPS/eip-191 + + + Currently, SIGN_MODE_EIP_191 is registered as a SignMode enum variant, + + but is not implemented on the SDK by default. To enable EIP-191, you + need + + to pass a custom `TxConfig` that has an implementation of + + `SignModeHandler` for EIP-191. The SDK may decide to fully support + + EIP-191 in the future. + + + Since: cosmos-sdk 0.45.2 + title: |- + Single is the mode info for a single signer. It is structured as a message + to allow for additional fields such as locale for SIGN_MODE_TEXTUAL in the + future + cosmos.tx.v1beta1.OrderBy: + type: string + enum: + - ORDER_BY_UNSPECIFIED + - ORDER_BY_ASC + - ORDER_BY_DESC + default: ORDER_BY_UNSPECIFIED + description: >- + - ORDER_BY_UNSPECIFIED: ORDER_BY_UNSPECIFIED specifies an unknown sorting + order. OrderBy defaults to ASC in this case. + - ORDER_BY_ASC: ORDER_BY_ASC defines ascending order + - ORDER_BY_DESC: ORDER_BY_DESC defines descending order + title: OrderBy defines the sorting order + cosmos.tx.v1beta1.SignerInfo: + type: object + properties: + public_key: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + public_key is the public key of the signer. It is optional for + accounts + + that already exist in state. If unset, the verifier can use the + required \ + + signer address for this position and lookup the public key. + mode_info: + title: |- + mode_info describes the signing mode of the signer and is a nested + structure to support nested multisig pubkey's + type: object + properties: + single: + title: single represents a single signer + type: object + properties: + mode: + title: mode is the signing mode of the single signer + type: string + enum: + - SIGN_MODE_UNSPECIFIED + - SIGN_MODE_DIRECT + - SIGN_MODE_TEXTUAL + - SIGN_MODE_LEGACY_AMINO_JSON + - SIGN_MODE_EIP_191 + default: SIGN_MODE_UNSPECIFIED + description: >- + SignMode represents a signing mode with its own security + guarantees. + + - SIGN_MODE_UNSPECIFIED: SIGN_MODE_UNSPECIFIED specifies an unknown signing mode and will be + rejected + - SIGN_MODE_DIRECT: SIGN_MODE_DIRECT specifies a signing mode which uses SignDoc and is + verified with raw bytes from Tx + - SIGN_MODE_TEXTUAL: SIGN_MODE_TEXTUAL is a future signing mode that will verify some + human-readable textual representation on top of the binary + representation + + from SIGN_MODE_DIRECT + - SIGN_MODE_LEGACY_AMINO_JSON: SIGN_MODE_LEGACY_AMINO_JSON is a backwards compatibility mode which uses + Amino JSON and will be removed in the future + - SIGN_MODE_EIP_191: SIGN_MODE_EIP_191 specifies the sign mode for EIP 191 signing on the Cosmos + SDK. Ref: https://eips.ethereum.org/EIPS/eip-191 + + + Currently, SIGN_MODE_EIP_191 is registered as a SignMode enum + variant, + + but is not implemented on the SDK by default. To enable + EIP-191, you need + + to pass a custom `TxConfig` that has an implementation of + + `SignModeHandler` for EIP-191. The SDK may decide to fully + support + + EIP-191 in the future. + + + Since: cosmos-sdk 0.45.2 + multi: + title: multi represents a nested multisig signer + type: object + properties: + bitarray: + title: bitarray specifies which keys within the multisig are signing + type: object + properties: + extra_bits_stored: + type: integer + format: int64 + elems: + type: string + format: byte + description: >- + CompactBitArray is an implementation of a space efficient bit + array. + + This is used to ensure that the encoded data takes up a + minimal amount of + + space after proto encoding. + + This is not thread safe, and is not intended for concurrent + usage. + mode_infos: + type: array + items: {} + title: >- + mode_infos is the corresponding modes of the signers of the + multisig + + which could include nested multisig public keys + description: >- + ModeInfo describes the signing mode of a single or nested multisig + signer. + sequence: + type: string + format: uint64 + description: >- + sequence is the sequence of the account, which describes the + + number of committed transactions signed by a given address. It is used + to + + prevent replay attacks. + description: |- + SignerInfo describes the public key and signing mode of a single top-level + signer. + cosmos.tx.v1beta1.SimulateRequest: + type: object + properties: + tx: + description: |- + tx is the transaction to simulate. + Deprecated. Send raw tx bytes instead. + type: object + properties: + body: + title: body is the processable content of the transaction + type: object + properties: + messages: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + messages is a list of messages to be executed. The required + signers of + + those messages define the number and order of elements in + AuthInfo's + + signer_infos and Tx's signatures. Each required signer address + is added to + + the list only the first time it occurs. + + By convention, the first required signer (usually from the + first message) + + is referred to as the primary signer and pays the fee for the + whole + + transaction. + memo: + type: string + description: >- + memo is any arbitrary note/comment to be added to the + transaction. + + WARNING: in clients, any publicly exposed text should not be + called memo, + + but should be called `note` instead (see + https://github.com/cosmos/cosmos-sdk/issues/9122). + timeout_height: + type: string + format: uint64 + title: >- + timeout is the block height after which this transaction will + not + + be processed by the chain + extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be added by + chains + + when the default options are not sufficient. If any of these + are present + + and can't be handled, the transaction will be rejected + non_critical_extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be added by + chains + + when the default options are not sufficient. If any of these + are present + + and can't be handled, they will be ignored + description: TxBody is the body of a transaction that all signers sign over. + auth_info: + title: |- + auth_info is the authorization related content of the transaction, + specifically signers, signer modes and fee + type: object + properties: + signer_infos: + type: array + items: + type: object + properties: + public_key: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + public_key is the public key of the signer. It is + optional for accounts + + that already exist in state. If unset, the verifier can + use the required \ + + signer address for this position and lookup the public + key. + mode_info: + title: >- + mode_info describes the signing mode of the signer and + is a nested + + structure to support nested multisig pubkey's + type: object + properties: + single: + title: single represents a single signer + type: object + properties: + mode: + title: mode is the signing mode of the single signer + type: string + enum: + - SIGN_MODE_UNSPECIFIED + - SIGN_MODE_DIRECT + - SIGN_MODE_TEXTUAL + - SIGN_MODE_LEGACY_AMINO_JSON + - SIGN_MODE_EIP_191 + default: SIGN_MODE_UNSPECIFIED + description: >- + SignMode represents a signing mode with its own + security guarantees. + + - SIGN_MODE_UNSPECIFIED: SIGN_MODE_UNSPECIFIED specifies an unknown signing mode and will be + rejected + - SIGN_MODE_DIRECT: SIGN_MODE_DIRECT specifies a signing mode which uses SignDoc and is + verified with raw bytes from Tx + - SIGN_MODE_TEXTUAL: SIGN_MODE_TEXTUAL is a future signing mode that will verify some + human-readable textual representation on top of + the binary representation + + from SIGN_MODE_DIRECT + - SIGN_MODE_LEGACY_AMINO_JSON: SIGN_MODE_LEGACY_AMINO_JSON is a backwards compatibility mode which uses + Amino JSON and will be removed in the future + - SIGN_MODE_EIP_191: SIGN_MODE_EIP_191 specifies the sign mode for EIP 191 signing on the Cosmos + SDK. Ref: https://eips.ethereum.org/EIPS/eip-191 + + + Currently, SIGN_MODE_EIP_191 is registered as a + SignMode enum variant, + + but is not implemented on the SDK by default. To + enable EIP-191, you need + + to pass a custom `TxConfig` that has an + implementation of + + `SignModeHandler` for EIP-191. The SDK may + decide to fully support + + EIP-191 in the future. + + + Since: cosmos-sdk 0.45.2 + multi: + title: multi represents a nested multisig signer + type: object + properties: + bitarray: + title: >- + bitarray specifies which keys within the + multisig are signing + type: object + properties: + extra_bits_stored: + type: integer + format: int64 + elems: + type: string + format: byte + description: >- + CompactBitArray is an implementation of a space + efficient bit array. + + This is used to ensure that the encoded data + takes up a minimal amount of + + space after proto encoding. + + This is not thread safe, and is not intended for + concurrent usage. + mode_infos: + type: array + items: {} + title: >- + mode_infos is the corresponding modes of the + signers of the multisig + + which could include nested multisig public keys + description: >- + ModeInfo describes the signing mode of a single or + nested multisig signer. + sequence: + type: string + format: uint64 + description: >- + sequence is the sequence of the account, which describes + the + + number of committed transactions signed by a given + address. It is used to + + prevent replay attacks. + description: >- + SignerInfo describes the public key and signing mode of a + single top-level + + signer. + description: >- + signer_infos defines the signing modes for the required + signers. The number + + and order of elements must match the required signers from + TxBody's + + messages. The first element is the primary signer and the one + which pays + + the fee. + fee: + description: >- + Fee is the fee and gas limit for the transaction. The first + signer is the + + primary signer and the one which pays the fee. The fee can be + calculated + + based on the cost of evaluating the body and doing signature + verification + + of the signers. This can be estimated via simulation. + type: object + properties: + amount: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the + custom method + + signatures required by gogoproto. + title: amount is the amount of coins to be paid as a fee + gas_limit: + type: string + format: uint64 + title: >- + gas_limit is the maximum gas that can be used in + transaction processing + + before an out of gas error occurs + payer: + type: string + description: >- + if unset, the first signer is responsible for paying the + fees. If set, the specified account must pay the fees. + + the payer must be a tx signer (and thus have signed this + field in AuthInfo). + + setting this field does *not* change the ordering of + required signers for the transaction. + granter: + type: string + title: >- + if set, the fee payer (either the first signer or the + value of the payer field) requests that a fee grant be + used + + to pay fees instead of the fee payer's own balance. If an + appropriate fee grant does not exist or the chain does + + not support fee grants, this will fail + description: >- + AuthInfo describes the fee and signer modes that are used to sign + a + + transaction. + signatures: + type: array + items: + type: string + format: byte + description: >- + signatures is a list of signatures that matches the length and + order of + + AuthInfo's signer_infos to allow connecting signature meta + information like + + public key and signing mode by position. + tx_bytes: + type: string + format: byte + description: |- + tx_bytes is the raw transaction. + + Since: cosmos-sdk 0.43 + description: |- + SimulateRequest is the request type for the Service.Simulate + RPC method. + cosmos.tx.v1beta1.SimulateResponse: + type: object + properties: + gas_info: + description: gas_info is the information about gas used in the simulation. + type: object + properties: + gas_wanted: + type: string + format: uint64 + description: >- + GasWanted is the maximum units of work we allow this tx to + perform. + gas_used: + type: string + format: uint64 + description: GasUsed is the amount of gas actually consumed. + result: + description: result is the result of the simulation. + type: object + properties: + data: + type: string + format: byte + description: >- + Data is any data returned from message or handler execution. It + MUST be + + length prefixed in order to separate data from multiple message + executions. + log: + type: string + description: >- + Log contains the log information from message or handler + execution. + events: + type: array + items: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + format: byte + value: + type: string + format: byte + index: + type: boolean + description: >- + EventAttribute is a single key-value pair, associated with + an event. + description: >- + Event allows application developers to attach additional + information to + + ResponseBeginBlock, ResponseEndBlock, ResponseCheckTx and + ResponseDeliverTx. + + Later, transactions may be queried using these events. + description: >- + Events contains a slice of Event objects that were emitted during + message + + or handler execution. + description: |- + SimulateResponse is the response type for the + Service.SimulateRPC method. + cosmos.tx.v1beta1.Tx: + type: object + properties: + body: + title: body is the processable content of the transaction + type: object + properties: + messages: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + messages is a list of messages to be executed. The required + signers of + + those messages define the number and order of elements in + AuthInfo's + + signer_infos and Tx's signatures. Each required signer address is + added to + + the list only the first time it occurs. + + By convention, the first required signer (usually from the first + message) + + is referred to as the primary signer and pays the fee for the + whole + + transaction. + memo: + type: string + description: >- + memo is any arbitrary note/comment to be added to the transaction. + + WARNING: in clients, any publicly exposed text should not be + called memo, + + but should be called `note` instead (see + https://github.com/cosmos/cosmos-sdk/issues/9122). + timeout_height: + type: string + format: uint64 + title: |- + timeout is the block height after which this transaction will not + be processed by the chain + extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be added by + chains + + when the default options are not sufficient. If any of these are + present + + and can't be handled, the transaction will be rejected + non_critical_extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be added by + chains + + when the default options are not sufficient. If any of these are + present + + and can't be handled, they will be ignored + description: TxBody is the body of a transaction that all signers sign over. + auth_info: + title: |- + auth_info is the authorization related content of the transaction, + specifically signers, signer modes and fee + type: object + properties: + signer_infos: + type: array + items: + type: object + properties: + public_key: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + public_key is the public key of the signer. It is optional + for accounts + + that already exist in state. If unset, the verifier can use + the required \ + + signer address for this position and lookup the public key. + mode_info: + title: >- + mode_info describes the signing mode of the signer and is a + nested + + structure to support nested multisig pubkey's + type: object + properties: + single: + title: single represents a single signer + type: object + properties: + mode: + title: mode is the signing mode of the single signer + type: string + enum: + - SIGN_MODE_UNSPECIFIED + - SIGN_MODE_DIRECT + - SIGN_MODE_TEXTUAL + - SIGN_MODE_LEGACY_AMINO_JSON + - SIGN_MODE_EIP_191 + default: SIGN_MODE_UNSPECIFIED + description: >- + SignMode represents a signing mode with its own + security guarantees. + + - SIGN_MODE_UNSPECIFIED: SIGN_MODE_UNSPECIFIED specifies an unknown signing mode and will be + rejected + - SIGN_MODE_DIRECT: SIGN_MODE_DIRECT specifies a signing mode which uses SignDoc and is + verified with raw bytes from Tx + - SIGN_MODE_TEXTUAL: SIGN_MODE_TEXTUAL is a future signing mode that will verify some + human-readable textual representation on top of the + binary representation + + from SIGN_MODE_DIRECT + - SIGN_MODE_LEGACY_AMINO_JSON: SIGN_MODE_LEGACY_AMINO_JSON is a backwards compatibility mode which uses + Amino JSON and will be removed in the future + - SIGN_MODE_EIP_191: SIGN_MODE_EIP_191 specifies the sign mode for EIP 191 signing on the Cosmos + SDK. Ref: https://eips.ethereum.org/EIPS/eip-191 + + + Currently, SIGN_MODE_EIP_191 is registered as a + SignMode enum variant, + + but is not implemented on the SDK by default. To + enable EIP-191, you need + + to pass a custom `TxConfig` that has an + implementation of + + `SignModeHandler` for EIP-191. The SDK may decide to + fully support + + EIP-191 in the future. + + + Since: cosmos-sdk 0.45.2 + multi: + title: multi represents a nested multisig signer + type: object + properties: + bitarray: + title: >- + bitarray specifies which keys within the multisig + are signing + type: object + properties: + extra_bits_stored: + type: integer + format: int64 + elems: + type: string + format: byte + description: >- + CompactBitArray is an implementation of a space + efficient bit array. + + This is used to ensure that the encoded data takes + up a minimal amount of + + space after proto encoding. + + This is not thread safe, and is not intended for + concurrent usage. + mode_infos: + type: array + items: {} + title: >- + mode_infos is the corresponding modes of the signers + of the multisig + + which could include nested multisig public keys + description: >- + ModeInfo describes the signing mode of a single or nested + multisig signer. + sequence: + type: string + format: uint64 + description: >- + sequence is the sequence of the account, which describes the + + number of committed transactions signed by a given address. + It is used to + + prevent replay attacks. + description: >- + SignerInfo describes the public key and signing mode of a single + top-level + + signer. + description: >- + signer_infos defines the signing modes for the required signers. + The number + + and order of elements must match the required signers from + TxBody's + + messages. The first element is the primary signer and the one + which pays + + the fee. + fee: + description: >- + Fee is the fee and gas limit for the transaction. The first signer + is the + + primary signer and the one which pays the fee. The fee can be + calculated + + based on the cost of evaluating the body and doing signature + verification + + of the signers. This can be estimated via simulation. + type: object + properties: + amount: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom + method + + signatures required by gogoproto. + title: amount is the amount of coins to be paid as a fee + gas_limit: + type: string + format: uint64 + title: >- + gas_limit is the maximum gas that can be used in transaction + processing + + before an out of gas error occurs + payer: + type: string + description: >- + if unset, the first signer is responsible for paying the fees. + If set, the specified account must pay the fees. + + the payer must be a tx signer (and thus have signed this field + in AuthInfo). + + setting this field does *not* change the ordering of required + signers for the transaction. + granter: + type: string + title: >- + if set, the fee payer (either the first signer or the value of + the payer field) requests that a fee grant be used + + to pay fees instead of the fee payer's own balance. If an + appropriate fee grant does not exist or the chain does + + not support fee grants, this will fail + description: |- + AuthInfo describes the fee and signer modes that are used to sign a + transaction. + signatures: + type: array + items: + type: string + format: byte + description: >- + signatures is a list of signatures that matches the length and order + of + + AuthInfo's signer_infos to allow connecting signature meta information + like + + public key and signing mode by position. + description: Tx is the standard type used for broadcasting transactions. + cosmos.tx.v1beta1.TxBody: + type: object + properties: + messages: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + messages is a list of messages to be executed. The required signers of + + those messages define the number and order of elements in AuthInfo's + + signer_infos and Tx's signatures. Each required signer address is + added to + + the list only the first time it occurs. + + By convention, the first required signer (usually from the first + message) + + is referred to as the primary signer and pays the fee for the whole + + transaction. + memo: + type: string + description: >- + memo is any arbitrary note/comment to be added to the transaction. + + WARNING: in clients, any publicly exposed text should not be called + memo, + + but should be called `note` instead (see + https://github.com/cosmos/cosmos-sdk/issues/9122). + timeout_height: + type: string + format: uint64 + title: |- + timeout is the block height after which this transaction will not + be processed by the chain + extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be added by chains + + when the default options are not sufficient. If any of these are + present + + and can't be handled, the transaction will be rejected + non_critical_extension_options: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + title: >- + extension_options are arbitrary options that can be added by chains + + when the default options are not sufficient. If any of these are + present + + and can't be handled, they will be ignored + description: TxBody is the body of a transaction that all signers sign over. + tendermint.abci.Event: + type: object + properties: + type: + type: string + attributes: + type: array + items: + type: object + properties: + key: + type: string + format: byte + value: + type: string + format: byte + index: + type: boolean + description: EventAttribute is a single key-value pair, associated with an event. + description: >- + Event allows application developers to attach additional information to + + ResponseBeginBlock, ResponseEndBlock, ResponseCheckTx and + ResponseDeliverTx. + + Later, transactions may be queried using these events. + tendermint.abci.EventAttribute: + type: object + properties: + key: + type: string + format: byte + value: + type: string + format: byte + index: + type: boolean + description: EventAttribute is a single key-value pair, associated with an event. + intertx.QueryInterchainAccountResponse: + type: object + properties: + interchain_account_address: + type: string + title: >- + QueryInterchainAccountResponse the response type for the + Query/InterchainAccountAddress RPC + cosmwasm.wasm.v1.AbsoluteTxPosition: + type: object + properties: + block_height: + type: string + format: uint64 + title: BlockHeight is the block the contract was created at + tx_index: + type: string + format: uint64 + title: >- + TxIndex is a monotonic counter within the block (actual transaction + index, + + or gas consumed) + description: |- + AbsoluteTxPosition is a unique transaction position that allows for global + ordering of transactions. + cosmwasm.wasm.v1.AccessConfig: + type: object + properties: + permission: + type: string + enum: + - ACCESS_TYPE_UNSPECIFIED + - ACCESS_TYPE_NOBODY + - ACCESS_TYPE_ONLY_ADDRESS + - ACCESS_TYPE_EVERYBODY + - ACCESS_TYPE_ANY_OF_ADDRESSES + default: ACCESS_TYPE_UNSPECIFIED + description: >- + - ACCESS_TYPE_UNSPECIFIED: AccessTypeUnspecified placeholder for empty + value + - ACCESS_TYPE_NOBODY: AccessTypeNobody forbidden + - ACCESS_TYPE_ONLY_ADDRESS: AccessTypeOnlyAddress restricted to a single address + Deprecated: use AccessTypeAnyOfAddresses instead + - ACCESS_TYPE_EVERYBODY: AccessTypeEverybody unrestricted + - ACCESS_TYPE_ANY_OF_ADDRESSES: AccessTypeAnyOfAddresses allow any of the addresses + title: AccessType permission types + address: + type: string + title: |- + Address + Deprecated: replaced by addresses + addresses: + type: array + items: + type: string + description: AccessConfig access control type. + cosmwasm.wasm.v1.AccessType: + type: string + enum: + - ACCESS_TYPE_UNSPECIFIED + - ACCESS_TYPE_NOBODY + - ACCESS_TYPE_ONLY_ADDRESS + - ACCESS_TYPE_EVERYBODY + - ACCESS_TYPE_ANY_OF_ADDRESSES + default: ACCESS_TYPE_UNSPECIFIED + description: >- + - ACCESS_TYPE_UNSPECIFIED: AccessTypeUnspecified placeholder for empty + value + - ACCESS_TYPE_NOBODY: AccessTypeNobody forbidden + - ACCESS_TYPE_ONLY_ADDRESS: AccessTypeOnlyAddress restricted to a single address + Deprecated: use AccessTypeAnyOfAddresses instead + - ACCESS_TYPE_EVERYBODY: AccessTypeEverybody unrestricted + - ACCESS_TYPE_ANY_OF_ADDRESSES: AccessTypeAnyOfAddresses allow any of the addresses + title: AccessType permission types + cosmwasm.wasm.v1.CodeInfoResponse: + type: object + properties: + code_id: + type: string + format: uint64 + creator: + type: string + data_hash: + type: string + format: byte + instantiate_permission: + type: object + properties: + permission: + type: string + enum: + - ACCESS_TYPE_UNSPECIFIED + - ACCESS_TYPE_NOBODY + - ACCESS_TYPE_ONLY_ADDRESS + - ACCESS_TYPE_EVERYBODY + - ACCESS_TYPE_ANY_OF_ADDRESSES + default: ACCESS_TYPE_UNSPECIFIED + description: >- + - ACCESS_TYPE_UNSPECIFIED: AccessTypeUnspecified placeholder for + empty value + - ACCESS_TYPE_NOBODY: AccessTypeNobody forbidden + - ACCESS_TYPE_ONLY_ADDRESS: AccessTypeOnlyAddress restricted to a single address + Deprecated: use AccessTypeAnyOfAddresses instead + - ACCESS_TYPE_EVERYBODY: AccessTypeEverybody unrestricted + - ACCESS_TYPE_ANY_OF_ADDRESSES: AccessTypeAnyOfAddresses allow any of the addresses + title: AccessType permission types + address: + type: string + title: |- + Address + Deprecated: replaced by addresses + addresses: + type: array + items: + type: string + description: AccessConfig access control type. + title: CodeInfoResponse contains code meta data from CodeInfo + cosmwasm.wasm.v1.ContractCodeHistoryEntry: + type: object + properties: + operation: + type: string + enum: + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_UNSPECIFIED + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_INIT + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_MIGRATE + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_GENESIS + default: CONTRACT_CODE_HISTORY_OPERATION_TYPE_UNSPECIFIED + description: >- + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_UNSPECIFIED: + ContractCodeHistoryOperationTypeUnspecified placeholder for empty + value + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_INIT: ContractCodeHistoryOperationTypeInit on chain contract instantiation + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_MIGRATE: ContractCodeHistoryOperationTypeMigrate code migration + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_GENESIS: ContractCodeHistoryOperationTypeGenesis based on genesis data + title: ContractCodeHistoryOperationType actions that caused a code change + code_id: + type: string + format: uint64 + title: CodeID is the reference to the stored WASM code + updated: + description: Updated Tx position when the operation was executed. + type: object + properties: + block_height: + type: string + format: uint64 + title: BlockHeight is the block the contract was created at + tx_index: + type: string + format: uint64 + title: >- + TxIndex is a monotonic counter within the block (actual + transaction index, + + or gas consumed) + msg: + type: string + format: byte + description: ContractCodeHistoryEntry metadata to a contract. + cosmwasm.wasm.v1.ContractCodeHistoryOperationType: + type: string + enum: + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_UNSPECIFIED + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_INIT + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_MIGRATE + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_GENESIS + default: CONTRACT_CODE_HISTORY_OPERATION_TYPE_UNSPECIFIED + description: >- + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_UNSPECIFIED: + ContractCodeHistoryOperationTypeUnspecified placeholder for empty value + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_INIT: ContractCodeHistoryOperationTypeInit on chain contract instantiation + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_MIGRATE: ContractCodeHistoryOperationTypeMigrate code migration + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_GENESIS: ContractCodeHistoryOperationTypeGenesis based on genesis data + title: ContractCodeHistoryOperationType actions that caused a code change + cosmwasm.wasm.v1.ContractInfo: + type: object + properties: + code_id: + type: string + format: uint64 + title: CodeID is the reference to the stored Wasm code + creator: + type: string + title: Creator address who initially instantiated the contract + admin: + type: string + title: Admin is an optional address that can execute migrations + label: + type: string + description: Label is optional metadata to be stored with a contract instance. + created: + description: Created Tx position when the contract was instantiated. + type: object + properties: + block_height: + type: string + format: uint64 + title: BlockHeight is the block the contract was created at + tx_index: + type: string + format: uint64 + title: >- + TxIndex is a monotonic counter within the block (actual + transaction index, + + or gas consumed) + ibc_port_id: + type: string + extension: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: |- + Extension is an extension point to store custom metadata within the + persistence model. + title: ContractInfo stores a WASM contract instance + cosmwasm.wasm.v1.Model: + type: object + properties: + key: + type: string + format: byte + title: hex-encode key to read it better (this is often ascii) + value: + type: string + format: byte + title: base64-encode raw value + title: Model is a struct that holds a KV pair + cosmwasm.wasm.v1.Params: + type: object + properties: + code_upload_access: + type: object + properties: + permission: + type: string + enum: + - ACCESS_TYPE_UNSPECIFIED + - ACCESS_TYPE_NOBODY + - ACCESS_TYPE_ONLY_ADDRESS + - ACCESS_TYPE_EVERYBODY + - ACCESS_TYPE_ANY_OF_ADDRESSES + default: ACCESS_TYPE_UNSPECIFIED + description: >- + - ACCESS_TYPE_UNSPECIFIED: AccessTypeUnspecified placeholder for + empty value + - ACCESS_TYPE_NOBODY: AccessTypeNobody forbidden + - ACCESS_TYPE_ONLY_ADDRESS: AccessTypeOnlyAddress restricted to a single address + Deprecated: use AccessTypeAnyOfAddresses instead + - ACCESS_TYPE_EVERYBODY: AccessTypeEverybody unrestricted + - ACCESS_TYPE_ANY_OF_ADDRESSES: AccessTypeAnyOfAddresses allow any of the addresses + title: AccessType permission types + address: + type: string + title: |- + Address + Deprecated: replaced by addresses + addresses: + type: array + items: + type: string + description: AccessConfig access control type. + instantiate_default_permission: + type: string + enum: + - ACCESS_TYPE_UNSPECIFIED + - ACCESS_TYPE_NOBODY + - ACCESS_TYPE_ONLY_ADDRESS + - ACCESS_TYPE_EVERYBODY + - ACCESS_TYPE_ANY_OF_ADDRESSES + default: ACCESS_TYPE_UNSPECIFIED + description: >- + - ACCESS_TYPE_UNSPECIFIED: AccessTypeUnspecified placeholder for empty + value + - ACCESS_TYPE_NOBODY: AccessTypeNobody forbidden + - ACCESS_TYPE_ONLY_ADDRESS: AccessTypeOnlyAddress restricted to a single address + Deprecated: use AccessTypeAnyOfAddresses instead + - ACCESS_TYPE_EVERYBODY: AccessTypeEverybody unrestricted + - ACCESS_TYPE_ANY_OF_ADDRESSES: AccessTypeAnyOfAddresses allow any of the addresses + title: AccessType permission types + description: Params defines the set of wasm parameters. + cosmwasm.wasm.v1.QueryAllContractStateResponse: + type: object + properties: + models: + type: array + items: + type: object + properties: + key: + type: string + format: byte + title: hex-encode key to read it better (this is often ascii) + value: + type: string + format: byte + title: base64-encode raw value + title: Model is a struct that holds a KV pair + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + title: |- + QueryAllContractStateResponse is the response type for the + Query/AllContractState RPC method + cosmwasm.wasm.v1.QueryCodeResponse: + type: object + properties: + code_info: + type: object + properties: + code_id: + type: string + format: uint64 + creator: + type: string + data_hash: + type: string + format: byte + instantiate_permission: + type: object + properties: + permission: + type: string + enum: + - ACCESS_TYPE_UNSPECIFIED + - ACCESS_TYPE_NOBODY + - ACCESS_TYPE_ONLY_ADDRESS + - ACCESS_TYPE_EVERYBODY + - ACCESS_TYPE_ANY_OF_ADDRESSES + default: ACCESS_TYPE_UNSPECIFIED + description: >- + - ACCESS_TYPE_UNSPECIFIED: AccessTypeUnspecified placeholder + for empty value + - ACCESS_TYPE_NOBODY: AccessTypeNobody forbidden + - ACCESS_TYPE_ONLY_ADDRESS: AccessTypeOnlyAddress restricted to a single address + Deprecated: use AccessTypeAnyOfAddresses instead + - ACCESS_TYPE_EVERYBODY: AccessTypeEverybody unrestricted + - ACCESS_TYPE_ANY_OF_ADDRESSES: AccessTypeAnyOfAddresses allow any of the addresses + title: AccessType permission types + address: + type: string + title: |- + Address + Deprecated: replaced by addresses + addresses: + type: array + items: + type: string + description: AccessConfig access control type. + title: CodeInfoResponse contains code meta data from CodeInfo + data: + type: string + format: byte + title: QueryCodeResponse is the response type for the Query/Code RPC method + cosmwasm.wasm.v1.QueryCodesResponse: + type: object + properties: + code_infos: + type: array + items: + type: object + properties: + code_id: + type: string + format: uint64 + creator: + type: string + data_hash: + type: string + format: byte + instantiate_permission: + type: object + properties: + permission: + type: string + enum: + - ACCESS_TYPE_UNSPECIFIED + - ACCESS_TYPE_NOBODY + - ACCESS_TYPE_ONLY_ADDRESS + - ACCESS_TYPE_EVERYBODY + - ACCESS_TYPE_ANY_OF_ADDRESSES + default: ACCESS_TYPE_UNSPECIFIED + description: >- + - ACCESS_TYPE_UNSPECIFIED: AccessTypeUnspecified placeholder + for empty value + - ACCESS_TYPE_NOBODY: AccessTypeNobody forbidden + - ACCESS_TYPE_ONLY_ADDRESS: AccessTypeOnlyAddress restricted to a single address + Deprecated: use AccessTypeAnyOfAddresses instead + - ACCESS_TYPE_EVERYBODY: AccessTypeEverybody unrestricted + - ACCESS_TYPE_ANY_OF_ADDRESSES: AccessTypeAnyOfAddresses allow any of the addresses + title: AccessType permission types + address: + type: string + title: |- + Address + Deprecated: replaced by addresses + addresses: + type: array + items: + type: string + description: AccessConfig access control type. + title: CodeInfoResponse contains code meta data from CodeInfo + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + title: QueryCodesResponse is the response type for the Query/Codes RPC method + cosmwasm.wasm.v1.QueryContractHistoryResponse: + type: object + properties: + entries: + type: array + items: + type: object + properties: + operation: + type: string + enum: + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_UNSPECIFIED + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_INIT + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_MIGRATE + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_GENESIS + default: CONTRACT_CODE_HISTORY_OPERATION_TYPE_UNSPECIFIED + description: >- + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_UNSPECIFIED: + ContractCodeHistoryOperationTypeUnspecified placeholder for + empty value + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_INIT: ContractCodeHistoryOperationTypeInit on chain contract instantiation + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_MIGRATE: ContractCodeHistoryOperationTypeMigrate code migration + - CONTRACT_CODE_HISTORY_OPERATION_TYPE_GENESIS: ContractCodeHistoryOperationTypeGenesis based on genesis data + title: >- + ContractCodeHistoryOperationType actions that caused a code + change + code_id: + type: string + format: uint64 + title: CodeID is the reference to the stored WASM code + updated: + description: Updated Tx position when the operation was executed. + type: object + properties: + block_height: + type: string + format: uint64 + title: BlockHeight is the block the contract was created at + tx_index: + type: string + format: uint64 + title: >- + TxIndex is a monotonic counter within the block (actual + transaction index, + + or gas consumed) + msg: + type: string + format: byte + description: ContractCodeHistoryEntry metadata to a contract. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + title: |- + QueryContractHistoryResponse is the response type for the + Query/ContractHistory RPC method + cosmwasm.wasm.v1.QueryContractInfoResponse: + type: object + properties: + address: + type: string + title: address is the address of the contract + contract_info: + type: object + properties: + code_id: + type: string + format: uint64 + title: CodeID is the reference to the stored Wasm code + creator: + type: string + title: Creator address who initially instantiated the contract + admin: + type: string + title: Admin is an optional address that can execute migrations + label: + type: string + description: Label is optional metadata to be stored with a contract instance. + created: + description: Created Tx position when the contract was instantiated. + type: object + properties: + block_height: + type: string + format: uint64 + title: BlockHeight is the block the contract was created at + tx_index: + type: string + format: uint64 + title: >- + TxIndex is a monotonic counter within the block (actual + transaction index, + + or gas consumed) + ibc_port_id: + type: string + extension: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + Extension is an extension point to store custom metadata within + the + + persistence model. + title: ContractInfo stores a WASM contract instance + title: >- + QueryContractInfoResponse is the response type for the Query/ContractInfo + RPC + + method + cosmwasm.wasm.v1.QueryContractsByCodeResponse: + type: object + properties: + contracts: + type: array + items: + type: string + title: contracts are a set of contract addresses + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + title: |- + QueryContractsByCodeResponse is the response type for the + Query/ContractsByCode RPC method + cosmwasm.wasm.v1.QueryContractsByCreatorResponse: + type: object + properties: + contract_addresses: + type: array + items: + type: string + title: ContractAddresses result set + pagination: + description: Pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + QueryContractsByCreatorResponse is the response type for the + Query/ContractsByCreator RPC method. + cosmwasm.wasm.v1.QueryParamsResponse: + type: object + properties: + params: + description: params defines the parameters of the module. + type: object + properties: + code_upload_access: + type: object + properties: + permission: + type: string + enum: + - ACCESS_TYPE_UNSPECIFIED + - ACCESS_TYPE_NOBODY + - ACCESS_TYPE_ONLY_ADDRESS + - ACCESS_TYPE_EVERYBODY + - ACCESS_TYPE_ANY_OF_ADDRESSES + default: ACCESS_TYPE_UNSPECIFIED + description: >- + - ACCESS_TYPE_UNSPECIFIED: AccessTypeUnspecified placeholder + for empty value + - ACCESS_TYPE_NOBODY: AccessTypeNobody forbidden + - ACCESS_TYPE_ONLY_ADDRESS: AccessTypeOnlyAddress restricted to a single address + Deprecated: use AccessTypeAnyOfAddresses instead + - ACCESS_TYPE_EVERYBODY: AccessTypeEverybody unrestricted + - ACCESS_TYPE_ANY_OF_ADDRESSES: AccessTypeAnyOfAddresses allow any of the addresses + title: AccessType permission types + address: + type: string + title: |- + Address + Deprecated: replaced by addresses + addresses: + type: array + items: + type: string + description: AccessConfig access control type. + instantiate_default_permission: + type: string + enum: + - ACCESS_TYPE_UNSPECIFIED + - ACCESS_TYPE_NOBODY + - ACCESS_TYPE_ONLY_ADDRESS + - ACCESS_TYPE_EVERYBODY + - ACCESS_TYPE_ANY_OF_ADDRESSES + default: ACCESS_TYPE_UNSPECIFIED + description: >- + - ACCESS_TYPE_UNSPECIFIED: AccessTypeUnspecified placeholder for + empty value + - ACCESS_TYPE_NOBODY: AccessTypeNobody forbidden + - ACCESS_TYPE_ONLY_ADDRESS: AccessTypeOnlyAddress restricted to a single address + Deprecated: use AccessTypeAnyOfAddresses instead + - ACCESS_TYPE_EVERYBODY: AccessTypeEverybody unrestricted + - ACCESS_TYPE_ANY_OF_ADDRESSES: AccessTypeAnyOfAddresses allow any of the addresses + title: AccessType permission types + description: QueryParamsResponse is the response type for the Query/Params RPC method. + cosmwasm.wasm.v1.QueryPinnedCodesResponse: + type: object + properties: + code_ids: + type: array + items: + type: string + format: uint64 + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + title: |- + QueryPinnedCodesResponse is the response type for the + Query/PinnedCodes RPC method + cosmwasm.wasm.v1.QueryRawContractStateResponse: + type: object + properties: + data: + type: string + format: byte + title: Data contains the raw store data + title: |- + QueryRawContractStateResponse is the response type for the + Query/RawContractState RPC method + cosmwasm.wasm.v1.QuerySmartContractStateResponse: + type: object + properties: + data: + type: string + format: byte + title: Data contains the json data returned from the smart contract + title: |- + QuerySmartContractStateResponse is the response type for the + Query/SmartContractState RPC method + cosmos.feegrant.v1beta1.Grant: + type: object + properties: + granter: + type: string + description: >- + granter is the address of the user granting an allowance of their + funds. + grantee: + type: string + description: >- + grantee is the address of the user being granted an allowance of + another user's funds. + allowance: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: allowance can be any of basic and filtered fee allowance. + title: Grant is stored in the KVStore to record a grant with full context + cosmos.feegrant.v1beta1.QueryAllowanceResponse: + type: object + properties: + allowance: + description: allowance is a allowance granted for grantee by granter. + type: object + properties: + granter: + type: string + description: >- + granter is the address of the user granting an allowance of their + funds. + grantee: + type: string + description: >- + grantee is the address of the user being granted an allowance of + another user's funds. + allowance: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: allowance can be any of basic and filtered fee allowance. + title: Grant is stored in the KVStore to record a grant with full context + description: >- + QueryAllowanceResponse is the response type for the Query/Allowance RPC + method. + cosmos.feegrant.v1beta1.QueryAllowancesByGranterResponse: + type: object + properties: + allowances: + type: array + items: + type: object + properties: + granter: + type: string + description: >- + granter is the address of the user granting an allowance of + their funds. + grantee: + type: string + description: >- + grantee is the address of the user being granted an allowance of + another user's funds. + allowance: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: allowance can be any of basic and filtered fee allowance. + title: Grant is stored in the KVStore to record a grant with full context + description: allowances that have been issued by the granter. + pagination: + description: pagination defines an pagination for the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryAllowancesByGranterResponse is the response type for the + Query/AllowancesByGranter RPC method. + cosmos.feegrant.v1beta1.QueryAllowancesResponse: + type: object + properties: + allowances: + type: array + items: + type: object + properties: + granter: + type: string + description: >- + granter is the address of the user granting an allowance of + their funds. + grantee: + type: string + description: >- + grantee is the address of the user being granted an allowance of + another user's funds. + allowance: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: allowance can be any of basic and filtered fee allowance. + title: Grant is stored in the KVStore to record a grant with full context + description: allowances are allowance's granted for grantee by granter. + pagination: + description: pagination defines an pagination for the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryAllowancesResponse is the response type for the Query/Allowances RPC + method. + type: object + properties: + minimum_gas_prices: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: |- + DecCoin defines a token with a denomination and a decimal amount. + + NOTE: The amount field is an Dec which implements the custom method + signatures required by gogoproto. + description: |- + QueryMinimumGasPricesResponse is the response type for the + Query/MinimumGasPrices RPC method. + cosmos.evidence.v1beta1.QueryAllEvidenceResponse: + type: object + properties: + evidence: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: evidence returns all evidences. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryAllEvidenceResponse is the response type for the Query/AllEvidence + RPC + + method. + cosmos.evidence.v1beta1.QueryEvidenceResponse: + type: object + properties: + evidence: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: evidence returns the requested evidence. + description: >- + QueryEvidenceResponse is the response type for the Query/Evidence RPC + method. + cosmos.base.node.v1beta1.ConfigResponse: + type: object + properties: + minimum_gas_price: + type: string + description: ConfigResponse defines the response structure for the Config gRPC query. + cosmos.params.v1beta1.ParamChange: + type: object + properties: + subspace: + type: string + key: + type: string + value: + type: string + description: |- + ParamChange defines an individual parameter change, for use in + ParameterChangeProposal. + cosmos.params.v1beta1.QueryParamsResponse: + type: object + properties: + param: + description: param defines the queried parameter. + type: object + properties: + subspace: + type: string + key: + type: string + value: + type: string + description: QueryParamsResponse is response type for the Query/Params RPC method. + cosmos.gov.v1beta1.Deposit: + type: object + properties: + proposal_id: + type: string + format: uint64 + depositor: + type: string + amount: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: |- + Coin defines a token with a denomination and an amount. + + NOTE: The amount field is an Int which implements the custom method + signatures required by gogoproto. + description: |- + Deposit defines an amount deposited by an account address to an active + proposal. + cosmos.gov.v1beta1.DepositParams: + type: object + properties: + min_deposit: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: |- + Coin defines a token with a denomination and an amount. + + NOTE: The amount field is an Int which implements the custom method + signatures required by gogoproto. + description: Minimum deposit for a proposal to enter voting period. + max_deposit_period: + type: string + description: >- + Maximum period for Atom holders to deposit on a proposal. Initial + value: 2 + months. + description: DepositParams defines the params for deposits on governance proposals. + cosmos.gov.v1beta1.Proposal: + type: object + properties: + proposal_id: + type: string + format: uint64 + content: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + status: + type: string + enum: + - PROPOSAL_STATUS_UNSPECIFIED + - PROPOSAL_STATUS_DEPOSIT_PERIOD + - PROPOSAL_STATUS_VOTING_PERIOD + - PROPOSAL_STATUS_PASSED + - PROPOSAL_STATUS_REJECTED + - PROPOSAL_STATUS_FAILED + default: PROPOSAL_STATUS_UNSPECIFIED + description: |- + ProposalStatus enumerates the valid statuses of a proposal. + + - PROPOSAL_STATUS_UNSPECIFIED: PROPOSAL_STATUS_UNSPECIFIED defines the default propopsal status. + - PROPOSAL_STATUS_DEPOSIT_PERIOD: PROPOSAL_STATUS_DEPOSIT_PERIOD defines a proposal status during the deposit + period. + - PROPOSAL_STATUS_VOTING_PERIOD: PROPOSAL_STATUS_VOTING_PERIOD defines a proposal status during the voting + period. + - PROPOSAL_STATUS_PASSED: PROPOSAL_STATUS_PASSED defines a proposal status of a proposal that has + passed. + - PROPOSAL_STATUS_REJECTED: PROPOSAL_STATUS_REJECTED defines a proposal status of a proposal that has + been rejected. + - PROPOSAL_STATUS_FAILED: PROPOSAL_STATUS_FAILED defines a proposal status of a proposal that has + failed. + final_tally_result: + type: object + properties: + 'yes': + type: string + abstain: + type: string + 'no': + type: string + no_with_veto: + type: string + description: TallyResult defines a standard tally for a governance proposal. + submit_time: + type: string + format: date-time + deposit_end_time: + type: string + format: date-time + total_deposit: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: |- + Coin defines a token with a denomination and an amount. + + NOTE: The amount field is an Int which implements the custom method + signatures required by gogoproto. + voting_start_time: + type: string + format: date-time + voting_end_time: + type: string + format: date-time + description: Proposal defines the core field members of a governance proposal. + cosmos.gov.v1beta1.ProposalStatus: + type: string + enum: + - PROPOSAL_STATUS_UNSPECIFIED + - PROPOSAL_STATUS_DEPOSIT_PERIOD + - PROPOSAL_STATUS_VOTING_PERIOD + - PROPOSAL_STATUS_PASSED + - PROPOSAL_STATUS_REJECTED + - PROPOSAL_STATUS_FAILED + default: PROPOSAL_STATUS_UNSPECIFIED + description: |- + ProposalStatus enumerates the valid statuses of a proposal. + + - PROPOSAL_STATUS_UNSPECIFIED: PROPOSAL_STATUS_UNSPECIFIED defines the default propopsal status. + - PROPOSAL_STATUS_DEPOSIT_PERIOD: PROPOSAL_STATUS_DEPOSIT_PERIOD defines a proposal status during the deposit + period. + - PROPOSAL_STATUS_VOTING_PERIOD: PROPOSAL_STATUS_VOTING_PERIOD defines a proposal status during the voting + period. + - PROPOSAL_STATUS_PASSED: PROPOSAL_STATUS_PASSED defines a proposal status of a proposal that has + passed. + - PROPOSAL_STATUS_REJECTED: PROPOSAL_STATUS_REJECTED defines a proposal status of a proposal that has + been rejected. + - PROPOSAL_STATUS_FAILED: PROPOSAL_STATUS_FAILED defines a proposal status of a proposal that has + failed. + cosmos.gov.v1beta1.QueryDepositResponse: + type: object + properties: + deposit: + type: object + properties: + proposal_id: + type: string + format: uint64 + depositor: + type: string + amount: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom + method + + signatures required by gogoproto. + description: |- + Deposit defines an amount deposited by an account address to an active + proposal. + description: >- + QueryDepositResponse is the response type for the Query/Deposit RPC + method. + cosmos.gov.v1beta1.QueryDepositsResponse: + type: object + properties: + deposits: + type: array + items: + type: object + properties: + proposal_id: + type: string + format: uint64 + depositor: + type: string + amount: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom + method + + signatures required by gogoproto. + description: >- + Deposit defines an amount deposited by an account address to an + active + + proposal. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + QueryDepositsResponse is the response type for the Query/Deposits RPC + method. + cosmos.gov.v1beta1.QueryParamsResponse: + type: object + properties: + voting_params: + description: voting_params defines the parameters related to voting. + type: object + properties: + voting_period: + type: string + description: Length of the voting period. + deposit_params: + description: deposit_params defines the parameters related to deposit. + type: object + properties: + min_deposit: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom + method + + signatures required by gogoproto. + description: Minimum deposit for a proposal to enter voting period. + max_deposit_period: + type: string + description: >- + Maximum period for Atom holders to deposit on a proposal. Initial + value: 2 + months. + tally_params: + description: tally_params defines the parameters related to tally. + type: object + properties: + quorum: + type: string + format: byte + description: >- + Minimum percentage of total stake needed to vote for a result to + be + considered valid. + threshold: + type: string + format: byte + description: >- + Minimum proportion of Yes votes for proposal to pass. Default + value: 0.5. + veto_threshold: + type: string + format: byte + description: >- + Minimum value of Veto votes to Total votes ratio for proposal to + be + vetoed. Default value: 1/3. + description: QueryParamsResponse is the response type for the Query/Params RPC method. + cosmos.gov.v1beta1.QueryProposalResponse: + type: object + properties: + proposal: + type: object + properties: + proposal_id: + type: string + format: uint64 + content: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + status: + type: string + enum: + - PROPOSAL_STATUS_UNSPECIFIED + - PROPOSAL_STATUS_DEPOSIT_PERIOD + - PROPOSAL_STATUS_VOTING_PERIOD + - PROPOSAL_STATUS_PASSED + - PROPOSAL_STATUS_REJECTED + - PROPOSAL_STATUS_FAILED + default: PROPOSAL_STATUS_UNSPECIFIED + description: |- + ProposalStatus enumerates the valid statuses of a proposal. + + - PROPOSAL_STATUS_UNSPECIFIED: PROPOSAL_STATUS_UNSPECIFIED defines the default propopsal status. + - PROPOSAL_STATUS_DEPOSIT_PERIOD: PROPOSAL_STATUS_DEPOSIT_PERIOD defines a proposal status during the deposit + period. + - PROPOSAL_STATUS_VOTING_PERIOD: PROPOSAL_STATUS_VOTING_PERIOD defines a proposal status during the voting + period. + - PROPOSAL_STATUS_PASSED: PROPOSAL_STATUS_PASSED defines a proposal status of a proposal that has + passed. + - PROPOSAL_STATUS_REJECTED: PROPOSAL_STATUS_REJECTED defines a proposal status of a proposal that has + been rejected. + - PROPOSAL_STATUS_FAILED: PROPOSAL_STATUS_FAILED defines a proposal status of a proposal that has + failed. + final_tally_result: + type: object + properties: + 'yes': + type: string + abstain: + type: string + 'no': + type: string + no_with_veto: + type: string + description: TallyResult defines a standard tally for a governance proposal. + submit_time: + type: string + format: date-time + deposit_end_time: + type: string + format: date-time + total_deposit: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom + method + + signatures required by gogoproto. + voting_start_time: + type: string + format: date-time + voting_end_time: + type: string + format: date-time + description: Proposal defines the core field members of a governance proposal. + description: >- + QueryProposalResponse is the response type for the Query/Proposal RPC + method. + cosmos.gov.v1beta1.QueryProposalsResponse: + type: object + properties: + proposals: + type: array + items: + type: object + properties: + proposal_id: + type: string + format: uint64 + content: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + status: + type: string + enum: + - PROPOSAL_STATUS_UNSPECIFIED + - PROPOSAL_STATUS_DEPOSIT_PERIOD + - PROPOSAL_STATUS_VOTING_PERIOD + - PROPOSAL_STATUS_PASSED + - PROPOSAL_STATUS_REJECTED + - PROPOSAL_STATUS_FAILED + default: PROPOSAL_STATUS_UNSPECIFIED + description: |- + ProposalStatus enumerates the valid statuses of a proposal. + + - PROPOSAL_STATUS_UNSPECIFIED: PROPOSAL_STATUS_UNSPECIFIED defines the default propopsal status. + - PROPOSAL_STATUS_DEPOSIT_PERIOD: PROPOSAL_STATUS_DEPOSIT_PERIOD defines a proposal status during the deposit + period. + - PROPOSAL_STATUS_VOTING_PERIOD: PROPOSAL_STATUS_VOTING_PERIOD defines a proposal status during the voting + period. + - PROPOSAL_STATUS_PASSED: PROPOSAL_STATUS_PASSED defines a proposal status of a proposal that has + passed. + - PROPOSAL_STATUS_REJECTED: PROPOSAL_STATUS_REJECTED defines a proposal status of a proposal that has + been rejected. + - PROPOSAL_STATUS_FAILED: PROPOSAL_STATUS_FAILED defines a proposal status of a proposal that has + failed. + final_tally_result: + type: object + properties: + 'yes': + type: string + abstain: + type: string + 'no': + type: string + no_with_veto: + type: string + description: TallyResult defines a standard tally for a governance proposal. + submit_time: + type: string + format: date-time + deposit_end_time: + type: string + format: date-time + total_deposit: + type: array + items: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom + method + + signatures required by gogoproto. + voting_start_time: + type: string + format: date-time + voting_end_time: + type: string + format: date-time + description: Proposal defines the core field members of a governance proposal. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + QueryProposalsResponse is the response type for the Query/Proposals RPC + method. + cosmos.gov.v1beta1.QueryTallyResultResponse: + type: object + properties: + tally: + type: object + properties: + 'yes': + type: string + abstain: + type: string + 'no': + type: string + no_with_veto: + type: string + description: TallyResult defines a standard tally for a governance proposal. + description: >- + QueryTallyResultResponse is the response type for the Query/Tally RPC + method. + cosmos.gov.v1beta1.QueryVoteResponse: + type: object + properties: + vote: + type: object + properties: + proposal_id: + type: string + format: uint64 + voter: + type: string + option: + description: >- + Deprecated: Prefer to use `options` instead. This field is set in + queries + + if and only if `len(options) == 1` and that option has weight 1. + In all + + other cases, this field will default to VOTE_OPTION_UNSPECIFIED. + type: string + enum: + - VOTE_OPTION_UNSPECIFIED + - VOTE_OPTION_YES + - VOTE_OPTION_ABSTAIN + - VOTE_OPTION_NO + - VOTE_OPTION_NO_WITH_VETO + default: VOTE_OPTION_UNSPECIFIED + options: + type: array + items: + type: object + properties: + option: + type: string + enum: + - VOTE_OPTION_UNSPECIFIED + - VOTE_OPTION_YES + - VOTE_OPTION_ABSTAIN + - VOTE_OPTION_NO + - VOTE_OPTION_NO_WITH_VETO + default: VOTE_OPTION_UNSPECIFIED + description: >- + VoteOption enumerates the valid vote options for a given + governance proposal. + + - VOTE_OPTION_UNSPECIFIED: VOTE_OPTION_UNSPECIFIED defines a no-op vote option. + - VOTE_OPTION_YES: VOTE_OPTION_YES defines a yes vote option. + - VOTE_OPTION_ABSTAIN: VOTE_OPTION_ABSTAIN defines an abstain vote option. + - VOTE_OPTION_NO: VOTE_OPTION_NO defines a no vote option. + - VOTE_OPTION_NO_WITH_VETO: VOTE_OPTION_NO_WITH_VETO defines a no with veto vote option. + weight: + type: string + description: |- + WeightedVoteOption defines a unit of vote for vote split. + + Since: cosmos-sdk 0.43 + title: 'Since: cosmos-sdk 0.43' + description: |- + Vote defines a vote on a governance proposal. + A Vote consists of a proposal ID, the voter, and the vote option. + description: QueryVoteResponse is the response type for the Query/Vote RPC method. + cosmos.gov.v1beta1.QueryVotesResponse: + type: object + properties: + votes: + type: array + items: + type: object + properties: + proposal_id: + type: string + format: uint64 + voter: + type: string + option: + description: >- + Deprecated: Prefer to use `options` instead. This field is set + in queries + + if and only if `len(options) == 1` and that option has weight 1. + In all + + other cases, this field will default to VOTE_OPTION_UNSPECIFIED. + type: string + enum: + - VOTE_OPTION_UNSPECIFIED + - VOTE_OPTION_YES + - VOTE_OPTION_ABSTAIN + - VOTE_OPTION_NO + - VOTE_OPTION_NO_WITH_VETO + default: VOTE_OPTION_UNSPECIFIED + options: + type: array + items: + type: object + properties: + option: + type: string + enum: + - VOTE_OPTION_UNSPECIFIED + - VOTE_OPTION_YES + - VOTE_OPTION_ABSTAIN + - VOTE_OPTION_NO + - VOTE_OPTION_NO_WITH_VETO + default: VOTE_OPTION_UNSPECIFIED + description: >- + VoteOption enumerates the valid vote options for a given + governance proposal. + + - VOTE_OPTION_UNSPECIFIED: VOTE_OPTION_UNSPECIFIED defines a no-op vote option. + - VOTE_OPTION_YES: VOTE_OPTION_YES defines a yes vote option. + - VOTE_OPTION_ABSTAIN: VOTE_OPTION_ABSTAIN defines an abstain vote option. + - VOTE_OPTION_NO: VOTE_OPTION_NO defines a no vote option. + - VOTE_OPTION_NO_WITH_VETO: VOTE_OPTION_NO_WITH_VETO defines a no with veto vote option. + weight: + type: string + description: |- + WeightedVoteOption defines a unit of vote for vote split. + + Since: cosmos-sdk 0.43 + title: 'Since: cosmos-sdk 0.43' + description: |- + Vote defines a vote on a governance proposal. + A Vote consists of a proposal ID, the voter, and the vote option. + description: votes defined the queried votes. + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: QueryVotesResponse is the response type for the Query/Votes RPC method. + cosmos.gov.v1beta1.TallyParams: + type: object + properties: + quorum: + type: string + format: byte + description: |- + Minimum percentage of total stake needed to vote for a result to be + considered valid. + threshold: + type: string + format: byte + description: >- + Minimum proportion of Yes votes for proposal to pass. Default value: + 0.5. + veto_threshold: + type: string + format: byte + description: |- + Minimum value of Veto votes to Total votes ratio for proposal to be + vetoed. Default value: 1/3. + description: TallyParams defines the params for tallying votes on governance proposals. + cosmos.gov.v1beta1.TallyResult: + type: object + properties: + 'yes': + type: string + abstain: + type: string + 'no': + type: string + no_with_veto: + type: string + description: TallyResult defines a standard tally for a governance proposal. + cosmos.gov.v1beta1.Vote: + type: object + properties: + proposal_id: + type: string + format: uint64 + voter: + type: string + option: + description: >- + Deprecated: Prefer to use `options` instead. This field is set in + queries + + if and only if `len(options) == 1` and that option has weight 1. In + all + + other cases, this field will default to VOTE_OPTION_UNSPECIFIED. + type: string + enum: + - VOTE_OPTION_UNSPECIFIED + - VOTE_OPTION_YES + - VOTE_OPTION_ABSTAIN + - VOTE_OPTION_NO + - VOTE_OPTION_NO_WITH_VETO + default: VOTE_OPTION_UNSPECIFIED + options: + type: array + items: + type: object + properties: + option: + type: string + enum: + - VOTE_OPTION_UNSPECIFIED + - VOTE_OPTION_YES + - VOTE_OPTION_ABSTAIN + - VOTE_OPTION_NO + - VOTE_OPTION_NO_WITH_VETO + default: VOTE_OPTION_UNSPECIFIED + description: >- + VoteOption enumerates the valid vote options for a given + governance proposal. + + - VOTE_OPTION_UNSPECIFIED: VOTE_OPTION_UNSPECIFIED defines a no-op vote option. + - VOTE_OPTION_YES: VOTE_OPTION_YES defines a yes vote option. + - VOTE_OPTION_ABSTAIN: VOTE_OPTION_ABSTAIN defines an abstain vote option. + - VOTE_OPTION_NO: VOTE_OPTION_NO defines a no vote option. + - VOTE_OPTION_NO_WITH_VETO: VOTE_OPTION_NO_WITH_VETO defines a no with veto vote option. + weight: + type: string + description: |- + WeightedVoteOption defines a unit of vote for vote split. + + Since: cosmos-sdk 0.43 + title: 'Since: cosmos-sdk 0.43' + description: |- + Vote defines a vote on a governance proposal. + A Vote consists of a proposal ID, the voter, and the vote option. + cosmos.gov.v1beta1.VoteOption: + type: string + enum: + - VOTE_OPTION_UNSPECIFIED + - VOTE_OPTION_YES + - VOTE_OPTION_ABSTAIN + - VOTE_OPTION_NO + - VOTE_OPTION_NO_WITH_VETO + default: VOTE_OPTION_UNSPECIFIED + description: >- + VoteOption enumerates the valid vote options for a given governance + proposal. + + - VOTE_OPTION_UNSPECIFIED: VOTE_OPTION_UNSPECIFIED defines a no-op vote option. + - VOTE_OPTION_YES: VOTE_OPTION_YES defines a yes vote option. + - VOTE_OPTION_ABSTAIN: VOTE_OPTION_ABSTAIN defines an abstain vote option. + - VOTE_OPTION_NO: VOTE_OPTION_NO defines a no vote option. + - VOTE_OPTION_NO_WITH_VETO: VOTE_OPTION_NO_WITH_VETO defines a no with veto vote option. + cosmos.gov.v1beta1.VotingParams: + type: object + properties: + voting_period: + type: string + description: Length of the voting period. + description: VotingParams defines the params for voting on governance proposals. + cosmos.gov.v1beta1.WeightedVoteOption: + type: object + properties: + option: + type: string + enum: + - VOTE_OPTION_UNSPECIFIED + - VOTE_OPTION_YES + - VOTE_OPTION_ABSTAIN + - VOTE_OPTION_NO + - VOTE_OPTION_NO_WITH_VETO + default: VOTE_OPTION_UNSPECIFIED + description: >- + VoteOption enumerates the valid vote options for a given governance + proposal. + + - VOTE_OPTION_UNSPECIFIED: VOTE_OPTION_UNSPECIFIED defines a no-op vote option. + - VOTE_OPTION_YES: VOTE_OPTION_YES defines a yes vote option. + - VOTE_OPTION_ABSTAIN: VOTE_OPTION_ABSTAIN defines an abstain vote option. + - VOTE_OPTION_NO: VOTE_OPTION_NO defines a no vote option. + - VOTE_OPTION_NO_WITH_VETO: VOTE_OPTION_NO_WITH_VETO defines a no with veto vote option. + weight: + type: string + description: |- + WeightedVoteOption defines a unit of vote for vote split. + + Since: cosmos-sdk 0.43 + type: object + properties: + contract_addresses: + type: array + items: + type: string + title: |- + contract_addresses is the slice of registered contract addresses for a + withdrawer + pagination: + description: pagination defines the pagination in the response. + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + QueryWithdrawerFeeSharesResponse is the response type for the + Query/WithdrawerFeeShares RPC method. + cosmos.slashing.v1beta1.Params: + type: object + properties: + signed_blocks_window: + type: string + format: int64 + min_signed_per_window: + type: string + format: byte + downtime_jail_duration: + type: string + slash_fraction_double_sign: + type: string + format: byte + slash_fraction_downtime: + type: string + format: byte + description: Params represents the parameters used for by the slashing module. + cosmos.slashing.v1beta1.QueryParamsResponse: + type: object + properties: + params: + type: object + properties: + signed_blocks_window: + type: string + format: int64 + min_signed_per_window: + type: string + format: byte + downtime_jail_duration: + type: string + slash_fraction_double_sign: + type: string + format: byte + slash_fraction_downtime: + type: string + format: byte + description: Params represents the parameters used for by the slashing module. + title: QueryParamsResponse is the response type for the Query/Params RPC method + cosmos.slashing.v1beta1.QuerySigningInfoResponse: + type: object + properties: + val_signing_info: + type: object + properties: + address: + type: string + start_height: + type: string + format: int64 + title: Height at which validator was first a candidate OR was unjailed + index_offset: + type: string + format: int64 + description: >- + Index which is incremented each time the validator was a bonded + + in a block and may have signed a precommit or not. This in + conjunction with the + + `SignedBlocksWindow` param determines the index in the + `MissedBlocksBitArray`. + jailed_until: + type: string + format: date-time + description: >- + Timestamp until which the validator is jailed due to liveness + downtime. + tombstoned: + type: boolean + description: >- + Whether or not a validator has been tombstoned (killed out of + validator set). It is set + + once the validator commits an equivocation or for any other + configured misbehiavor. + missed_blocks_counter: + type: string + format: int64 + description: >- + A counter kept to avoid unnecessary array reads. + + Note that `Sum(MissedBlocksBitArray)` always equals + `MissedBlocksCounter`. + description: >- + ValidatorSigningInfo defines a validator's signing info for monitoring + their + + liveness activity. + title: val_signing_info is the signing info of requested val cons address + title: >- + QuerySigningInfoResponse is the response type for the Query/SigningInfo + RPC + + method + cosmos.slashing.v1beta1.QuerySigningInfosResponse: + type: object + properties: + info: + type: array + items: + type: object + properties: + address: + type: string + start_height: + type: string + format: int64 + title: Height at which validator was first a candidate OR was unjailed + index_offset: + type: string + format: int64 + description: >- + Index which is incremented each time the validator was a bonded + + in a block and may have signed a precommit or not. This in + conjunction with the + + `SignedBlocksWindow` param determines the index in the + `MissedBlocksBitArray`. + jailed_until: + type: string + format: date-time + description: >- + Timestamp until which the validator is jailed due to liveness + downtime. + tombstoned: + type: boolean + description: >- + Whether or not a validator has been tombstoned (killed out of + validator set). It is set + + once the validator commits an equivocation or for any other + configured misbehiavor. + missed_blocks_counter: + type: string + format: int64 + description: >- + A counter kept to avoid unnecessary array reads. + + Note that `Sum(MissedBlocksBitArray)` always equals + `MissedBlocksCounter`. + description: >- + ValidatorSigningInfo defines a validator's signing info for + monitoring their + + liveness activity. + title: info is the signing info of all validators + pagination: + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + PageResponse is to be embedded in gRPC response messages where the + corresponding request message has used PageRequest. + + message SomeResponse { + repeated Bar results = 1; + PageResponse page = 2; + } + title: >- + QuerySigningInfosResponse is the response type for the Query/SigningInfos + RPC + + method + cosmos.slashing.v1beta1.ValidatorSigningInfo: + type: object + properties: + address: + type: string + start_height: + type: string + format: int64 + title: Height at which validator was first a candidate OR was unjailed + index_offset: + type: string + format: int64 + description: >- + Index which is incremented each time the validator was a bonded + + in a block and may have signed a precommit or not. This in conjunction + with the + + `SignedBlocksWindow` param determines the index in the + `MissedBlocksBitArray`. + jailed_until: + type: string + format: date-time + description: >- + Timestamp until which the validator is jailed due to liveness + downtime. + tombstoned: + type: boolean + description: >- + Whether or not a validator has been tombstoned (killed out of + validator set). It is set + + once the validator commits an equivocation or for any other configured + misbehiavor. + missed_blocks_counter: + type: string + format: int64 + description: >- + A counter kept to avoid unnecessary array reads. + + Note that `Sum(MissedBlocksBitArray)` always equals + `MissedBlocksCounter`. + description: >- + ValidatorSigningInfo defines a validator's signing info for monitoring + their + + liveness activity. + cosmos.upgrade.v1beta1.ModuleVersion: + type: object + properties: + name: + type: string + title: name of the app module + version: + type: string + format: uint64 + title: consensus version of the app module + description: |- + ModuleVersion specifies a module and its consensus version. + + Since: cosmos-sdk 0.43 + cosmos.upgrade.v1beta1.Plan: + type: object + properties: + name: + type: string + description: >- + Sets the name for the upgrade. This name will be used by the upgraded + + version of the software to apply any special "on-upgrade" commands + during + + the first BeginBlock method after the upgrade is applied. It is also + used + + to detect whether a software version can handle a given upgrade. If no + + upgrade handler with this name has been set in the software, it will + be + + assumed that the software is out-of-date when the upgrade Time or + Height is + + reached and the software will exit. + time: + type: string + format: date-time + description: >- + Deprecated: Time based upgrades have been deprecated. Time based + upgrade logic + + has been removed from the SDK. + + If this field is not empty, an error will be thrown. + height: + type: string + format: int64 + description: |- + The height at which the upgrade must be performed. + Only used if Time is not set. + info: + type: string + title: |- + Any application specific upgrade info to be included on-chain + such as a git commit that validators could automatically upgrade to + upgraded_client_state: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + Deprecated: UpgradedClientState field has been deprecated. IBC upgrade + logic has been + + moved to the IBC module in the sub module 02-client. + + If this field is not empty, an error will be thrown. + description: >- + Plan specifies information about a planned upgrade and when it should + occur. + cosmos.upgrade.v1beta1.QueryAppliedPlanResponse: + type: object + properties: + height: + type: string + format: int64 + description: height is the block height at which the plan was applied. + description: >- + QueryAppliedPlanResponse is the response type for the Query/AppliedPlan + RPC + + method. + cosmos.upgrade.v1beta1.QueryCurrentPlanResponse: + type: object + properties: + plan: + description: plan is the current upgrade plan. + type: object + properties: + name: + type: string + description: >- + Sets the name for the upgrade. This name will be used by the + upgraded + + version of the software to apply any special "on-upgrade" commands + during + + the first BeginBlock method after the upgrade is applied. It is + also used + + to detect whether a software version can handle a given upgrade. + If no + + upgrade handler with this name has been set in the software, it + will be + + assumed that the software is out-of-date when the upgrade Time or + Height is + + reached and the software will exit. + time: + type: string + format: date-time + description: >- + Deprecated: Time based upgrades have been deprecated. Time based + upgrade logic + + has been removed from the SDK. + + If this field is not empty, an error will be thrown. + height: + type: string + format: int64 + description: |- + The height at which the upgrade must be performed. + Only used if Time is not set. + info: + type: string + title: >- + Any application specific upgrade info to be included on-chain + + such as a git commit that validators could automatically upgrade + to + upgraded_client_state: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + description: >- + Deprecated: UpgradedClientState field has been deprecated. IBC + upgrade logic has been + + moved to the IBC module in the sub module 02-client. + + If this field is not empty, an error will be thrown. + description: >- + QueryCurrentPlanResponse is the response type for the Query/CurrentPlan + RPC + + method. + cosmos.upgrade.v1beta1.QueryModuleVersionsResponse: + type: object + properties: + module_versions: + type: array + items: + type: object + properties: + name: + type: string + title: name of the app module + version: + type: string + format: uint64 + title: consensus version of the app module + description: |- + ModuleVersion specifies a module and its consensus version. + + Since: cosmos-sdk 0.43 + description: >- + module_versions is a list of module names with their consensus + versions. + description: >- + QueryModuleVersionsResponse is the response type for the + Query/ModuleVersions + + RPC method. + + + Since: cosmos-sdk 0.43 + cosmos.upgrade.v1beta1.QueryUpgradedConsensusStateResponse: + type: object + properties: + upgraded_consensus_state: + type: string + format: byte + title: 'Since: cosmos-sdk 0.43' + description: >- + QueryUpgradedConsensusStateResponse is the response type for the + Query/UpgradedConsensusState + + RPC method. + cosmos.authz.v1beta1.Grant: + type: object + properties: + authorization: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + expiration: + type: string + format: date-time + description: |- + Grant gives permissions to execute + the provide method with expiration time. + cosmos.authz.v1beta1.GrantAuthorization: + type: object + properties: + granter: + type: string + grantee: + type: string + authorization: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + expiration: + type: string + format: date-time + description: 'Since: cosmos-sdk 0.45.2' + title: >- + GrantAuthorization extends a grant with both the addresses of the grantee + and granter. + + It is used in genesis.proto and query.proto + cosmos.authz.v1beta1.QueryGranteeGrantsResponse: + type: object + properties: + grants: + type: array + items: + type: object + properties: + granter: + type: string + grantee: + type: string + authorization: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + expiration: + type: string + format: date-time + description: 'Since: cosmos-sdk 0.45.2' + title: >- + GrantAuthorization extends a grant with both the addresses of the + grantee and granter. + + It is used in genesis.proto and query.proto + description: grants is a list of grants granted to the grantee. + pagination: + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + PageResponse is to be embedded in gRPC response messages where the + corresponding request message has used PageRequest. + + message SomeResponse { + repeated Bar results = 1; + PageResponse page = 2; + } + description: >- + QueryGranteeGrantsResponse is the response type for the + Query/GranteeGrants RPC method. + cosmos.authz.v1beta1.QueryGranterGrantsResponse: + type: object + properties: + grants: + type: array + items: + type: object + properties: + granter: + type: string + grantee: + type: string + authorization: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + expiration: + type: string + format: date-time + description: 'Since: cosmos-sdk 0.45.2' + title: >- + GrantAuthorization extends a grant with both the addresses of the + grantee and granter. + + It is used in genesis.proto and query.proto + description: grants is a list of grants granted by the granter. + pagination: + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + PageResponse is to be embedded in gRPC response messages where the + corresponding request message has used PageRequest. + + message SomeResponse { + repeated Bar results = 1; + PageResponse page = 2; + } + description: >- + QueryGranterGrantsResponse is the response type for the + Query/GranterGrants RPC method. + cosmos.authz.v1beta1.QueryGrantsResponse: + type: object + properties: + grants: + type: array + items: + type: object + properties: + authorization: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + expiration: + type: string + format: date-time + description: |- + Grant gives permissions to execute + the provide method with expiration time. + description: authorizations is a list of grants granted for grantee by granter. + pagination: + type: object + properties: + next_key: + type: string + format: byte + title: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + PageResponse is to be embedded in gRPC response messages where the + corresponding request message has used PageRequest. + + message SomeResponse { + repeated Bar results = 1; + PageResponse page = 2; + } + description: >- + QueryGrantsResponse is the response type for the Query/Authorizations RPC + method. + type: object + properties: + params: + description: params defines the parameters of the module. + type: object + properties: + mint_denom: + type: string + title: type of coin to mint + blocks_per_year: + type: string + format: uint64 + title: expected blocks per year + description: QueryParamsResponse is the response type for the Query/Params RPC method. diff --git a/go.mod b/go.mod index ddd2450..df929f2 100644 --- a/go.mod +++ b/go.mod @@ -1,45 +1,48 @@ -module github.com/terpnetwork/terp-core +module github.com/terpnetwork/terp-core/v2 -go 1.19 +go 1.20 require ( - github.com/CosmWasm/wasmvm v1.2.4 + github.com/CosmWasm/wasmd v0.40.2 + github.com/CosmWasm/wasmvm v1.2.4 // indirect github.com/cometbft/cometbft v0.37.1 github.com/cometbft/cometbft-db v0.7.0 - github.com/cosmos/cosmos-proto v1.0.0-beta.3 + github.com/cosmos/cosmos-proto v1.0.0-beta.3 // indirect github.com/cosmos/cosmos-sdk v0.47.3 github.com/cosmos/gogogateway v1.2.0 // indirect - github.com/cosmos/gogoproto v1.4.10 - github.com/cosmos/iavl v0.20.0 + github.com/cosmos/gogoproto v1.4.10 // indirect + github.com/cosmos/iavl v0.20.0 // indirect github.com/cosmos/ibc-go/v7 v7.0.1 github.com/cosmos/ics23/go v0.9.1-0.20221207100636-b1abd8678aab // indirect - github.com/docker/distribution v2.8.2+incompatible + github.com/docker/distribution v2.8.2+incompatible // indirect github.com/dvsekhvalnov/jose2go v1.5.0 // indirect - github.com/golang/protobuf v1.5.3 - github.com/google/gofuzz v1.2.0 + github.com/golang/protobuf v1.5.3 // indirect + github.com/google/gofuzz v1.2.0 // indirect github.com/gorilla/mux v1.8.0 github.com/grpc-ecosystem/grpc-gateway v1.16.0 - github.com/pkg/errors v0.9.1 + github.com/pkg/errors v0.9.1 // indirect github.com/prometheus/client_golang v1.15.0 github.com/rakyll/statik v0.1.7 // indirect github.com/snikch/goodman v0.0.0-20171125024755-10e37e294daa github.com/spf13/cast v1.5.1 - github.com/spf13/cobra v1.6.1 - github.com/spf13/pflag v1.0.5 + github.com/spf13/cobra v1.7.0 + github.com/spf13/pflag v1.0.5 // indirect github.com/stretchr/testify v1.8.3 github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d // indirect - google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 - google.golang.org/grpc v1.55.0 - gopkg.in/yaml.v2 v2.4.0 + google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 // indirect + google.golang.org/grpc v1.55.0 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect ) require ( cosmossdk.io/api v0.3.1 - cosmossdk.io/core v0.6.1 cosmossdk.io/errors v1.0.0-beta.7 + cosmossdk.io/log v1.1.0 cosmossdk.io/math v1.0.1 cosmossdk.io/tools/rosetta v0.2.1 github.com/spf13/viper v1.16.0 + github.com/strangelove-ventures/async-icq/v7 v7.0.0-20230413165143-a3b65ccdc897 + github.com/strangelove-ventures/packet-forward-middleware/v7 v7.0.0-20230523193151-73dea436e53f ) require ( @@ -48,8 +51,8 @@ require ( cloud.google.com/go/compute/metadata v0.2.3 // indirect cloud.google.com/go/iam v0.13.0 // indirect cloud.google.com/go/storage v1.29.0 // indirect + cosmossdk.io/core v0.6.1 // indirect cosmossdk.io/depinject v1.0.0-alpha.3 // indirect - cosmossdk.io/log v1.1.0 // indirect filippo.io/edwards25519 v1.0.0 // indirect github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect github.com/99designs/keyring v1.2.1 // indirect @@ -69,7 +72,7 @@ require ( github.com/confio/ics23/go v0.9.0 // indirect github.com/cosmos/btcutil v1.0.5 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect - github.com/cosmos/ledger-cosmos-go v0.12.1 // indirect + github.com/cosmos/ledger-cosmos-go v0.12.2 // indirect github.com/cosmos/rosetta-sdk-go v0.10.0 // indirect github.com/creachadair/taskgroup v0.4.2 // indirect github.com/danieljoos/wincred v1.1.2 // indirect @@ -114,6 +117,7 @@ require ( github.com/hashicorp/hcl v1.0.0 // indirect github.com/hdevalence/ed25519consensus v0.1.0 // indirect github.com/huandu/skiplist v1.2.0 // indirect + github.com/iancoleman/orderedmap v0.2.0 // indirect github.com/improbable-eng/grpc-web v0.15.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/jmespath/go-jmespath v0.4.0 // indirect diff --git a/go.sum b/go.sum index 46920d3..2a139df 100644 --- a/go.sum +++ b/go.sum @@ -212,6 +212,8 @@ github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03 github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/ChainSafe/go-schnorrkel v0.0.0-20200405005733-88cbf1b4c40d h1:nalkkPQcITbvhmL4+C4cKA87NW0tfm3Kl9VXRoPywFg= github.com/ChainSafe/go-schnorrkel v0.0.0-20200405005733-88cbf1b4c40d/go.mod h1:URdX5+vg25ts3aCh8H5IFZybJYKWhJHYMTnf+ULtoC4= +github.com/CosmWasm/wasmd v0.40.2 h1:GSDHIaeJI7fcDF5mkzSXQI5IZLtvpNq5t3TjJ9bDpPw= +github.com/CosmWasm/wasmd v0.40.2/go.mod h1:vqI238yb4D6aNuigS8mCqTyyCV9HN5eBEZARKRoK3ts= github.com/CosmWasm/wasmvm v1.2.4 h1:6OfeZuEcEH/9iqwrg2pkeVtDCkMoj9U6PpKtcrCyVrQ= github.com/CosmWasm/wasmvm v1.2.4/go.mod h1:vW/E3h8j9xBQs9bCoijDuawKo9kCtxOaS8N8J7KFtkc= github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ= @@ -339,8 +341,8 @@ github.com/cosmos/ics23/go v0.9.1-0.20221207100636-b1abd8678aab h1:I9ialKTQo7248 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/ledger-cosmos-go v0.12.2 h1:/XYaBlE2BJxtvpkHiBm97gFGSGmYGKunKyF3nNqAXZA= +github.com/cosmos/ledger-cosmos-go v0.12.2/go.mod h1:ZcqYgnfNJ6lAXe4HPtWgarNEY+B74i+2/8MhZw4ziiI= github.com/cosmos/rosetta-sdk-go v0.10.0 h1:E5RhTruuoA7KTIXUcMicL76cffyeoyvNybzUGSKFTcM= github.com/cosmos/rosetta-sdk-go v0.10.0/go.mod h1:SImAZkb96YbwvoRkzSMQB6noNJXFgWl/ENIznEoYQI4= github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= @@ -649,12 +651,13 @@ github.com/huandu/go-assert v1.1.5/go.mod h1:yOLvuqZwmcHIC5rIzrBhT7D3Q9c3GFnd0Jr github.com/huandu/skiplist v1.2.0 h1:gox56QD77HzSC0w+Ws3MH3iie755GBJU1OER3h5VsYw= github.com/huandu/skiplist v1.2.0/go.mod h1:7v3iFjLcSAzO4fN5B8dvebvo/qsfumiLiDXMrPiHF9w= github.com/hudl/fargo v1.3.0/go.mod h1:y3CKSmjA+wD2gak7sUSXTAoopbhU08POFhmITJgmKTg= +github.com/iancoleman/orderedmap v0.2.0 h1:sq1N/TFpYH++aViPcaKjys3bDClUEU7s5B+z6jq8pNA= +github.com/iancoleman/orderedmap v0.2.0/go.mod h1:N0Wam8K1arqPXNWjMo21EXnBPOPp36vB07FNRdD2geA= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/improbable-eng/grpc-web v0.15.0 h1:BN+7z6uNXZ1tQGcNAuaU1YjsLTApzkjt2tzCixLaUPQ= github.com/improbable-eng/grpc-web v0.15.0/go.mod h1:1sy9HKV4Jt9aEs9JSnkWlRJPuPtwNr0l57L4f878wP8= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= -github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/influxdata/influxdb1-client v0.0.0-20191209144304-8bf82d3c094d/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo= @@ -905,8 +908,8 @@ github.com/spf13/cast v1.5.1 h1:R+kOtfhWQE6TVQzY+4D7wJLBgkdVasCEFxSUBYBYIlA= github.com/spf13/cast v1.5.1/go.mod h1:b9PdjNptOpzXr7Rq1q9gJML/2cdGQAo69NKzQ10KN48= github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= -github.com/spf13/cobra v1.6.1 h1:o94oiPyS4KD1mPy2fmcYYHHfCxLqYjJOhGsCHFZtEzA= -github.com/spf13/cobra v1.6.1/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY= +github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= +github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= @@ -917,6 +920,10 @@ github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s= github.com/spf13/viper v1.16.0 h1:rGGH0XDZhdUOryiDWjmIvUSWpbNqisK8Wk0Vyefw8hc= github.com/spf13/viper v1.16.0/go.mod h1:yg78JgCJcbrQOvV9YLXgkLaZqUidkY9K+Dd1FofRzQg= +github.com/strangelove-ventures/async-icq/v7 v7.0.0-20230413165143-a3b65ccdc897 h1:lCTD5L1v1K1KC6KXjyt4o1X+yzV14RbbrPZaF29n8uI= +github.com/strangelove-ventures/async-icq/v7 v7.0.0-20230413165143-a3b65ccdc897/go.mod h1:ag05Q54Wkr0jVwfe+14sxnuWbw0gBOxtPQv9afBBnr0= +github.com/strangelove-ventures/packet-forward-middleware/v7 v7.0.0-20230523193151-73dea436e53f h1:NJdZ+YJ9Vf2t286L20IjFK0SxGpobF1xIp5ZQlxWetk= +github.com/strangelove-ventures/packet-forward-middleware/v7 v7.0.0-20230523193151-73dea436e53f/go.mod h1:DJNSVK8NCYHM+aZHCFkcAqPwjzwHYAjhjSMlhAGtJ3c= 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= diff --git a/interchaintest/chain_start_test.go b/interchaintest/chain_start_test.go new file mode 100644 index 0000000..310bd79 --- /dev/null +++ b/interchaintest/chain_start_test.go @@ -0,0 +1,27 @@ +package interchaintest + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +// TestBasicTerpStart is a basic test to assert that spinning up a Terp network with one validator works properly. +func TestBasicTerpStart(t *testing.T) { + if testing.Short() { + t.Skip() + } + + t.Parallel() + + // Base setup + chains := CreateThisBranchChain(t, 1, 0) + ic, ctx, _, _ := BuildInitialChain(t, chains) + + require.NotNil(t, ic) + require.NotNil(t, ctx) + + t.Cleanup(func() { + _ = ic.Close() + }) +} diff --git a/interchaintest/chain_upgrade_test.go b/interchaintest/chain_upgrade_test.go new file mode 100644 index 0000000..1c320e5 --- /dev/null +++ b/interchaintest/chain_upgrade_test.go @@ -0,0 +1,230 @@ +package interchaintest + +import ( + "context" + "fmt" + "testing" + "time" + + "github.com/strangelove-ventures/interchaintest/v7" + "github.com/strangelove-ventures/interchaintest/v7/chain/cosmos" + "github.com/strangelove-ventures/interchaintest/v7/ibc" + "github.com/strangelove-ventures/interchaintest/v7/testutil" + "github.com/stretchr/testify/require" + helpers "github.com/terpnetwork/terp-core/tests/interchaintest/helpers" + "go.uber.org/zap/zaptest" +) + +const ( + haltHeightDelta = uint64(10) // will propose upgrade this many blocks in the future + blocksAfterUpgrade = uint64(7) +) + +func TestBasicTerpUpgrade(t *testing.T) { + repo, version := GetDockerImageInfo() + // TODO: Use v15 version in the future after we get PR https://github.com/CosmosContracts/juno/pull/693 on mainnet + startVersion := "huckleberry" + upgradeName := "v2.0.0" + CosmosChainUpgradeTest(t, "terp-core", startVersion, version, repo, upgradeName) +} + +func CosmosChainUpgradeTest(t *testing.T, chainName, initialVersion, upgradeBranchVersion, upgradeRepo, upgradeName string) { + if testing.Short() { + t.Skip("skipping in short mode") + } + + t.Parallel() + + t.Log(chainName, initialVersion, upgradeBranchVersion, upgradeRepo, upgradeName) + + // v45 genesis params + genesisKVs := []cosmos.GenesisKV{ + { + Key: "app_state.gov.voting_params.voting_period", + Value: VotingPeriod, + }, + { + Key: "app_state.gov.deposit_params.max_deposit_period", + Value: MaxDepositPeriod, + }, + { + Key: "app_state.gov.deposit_params.min_deposit.0.denom", + Value: Denom, + }, + } + + cf := interchaintest.NewBuiltinChainFactory(zaptest.NewLogger(t), []*interchaintest.ChainSpec{ + { + Name: chainName, + ChainName: chainName, + Version: initialVersion, + ChainConfig: ibc.ChainConfig{ + Images: []ibc.DockerImage{ + { + Repository: TerpE2ERepo, + Version: initialVersion, + UidGid: TerpImage.UidGid, + }, + }, + GasPrices: fmt.Sprintf("0%s", Denom), + ModifyGenesis: cosmos.ModifyGenesis(genesisKVs), + }, + }, + }) + + chains, err := cf.Chains(t.Name()) + require.NoError(t, err) + + chain := chains[0].(*cosmos.CosmosChain) + + ic := interchaintest.NewInterchain(). + AddChain(chain) + + ctx := context.Background() + client, network := interchaintest.DockerSetup(t) + + err = ic.Build(ctx, nil, interchaintest.InterchainBuildOptions{ + TestName: t.Name(), + Client: client, + NetworkID: network, + SkipPathCreation: true, + }) + require.NoError(t, err) + + t.Cleanup(func() { + _ = ic.Close() + }) + + const userFunds = int64(10_000_000_000) + users := interchaintest.GetAndFundTestUsers(t, ctx, t.Name(), userFunds, chain) + chainUser := users[0] + + // // create a tokenfactory denom before upgrade (invalid genesis for hard forking due to x/bank validation) + // emptyFullDenom := helpers.CreateTokenFactoryDenom(t, ctx, chain, chainUser, "empty") + + // mintedDenom := helpers.CreateTokenFactoryDenom(t, ctx, chain, chainUser, "minted") + // helpers.MintToTokenFactoryDenom(t, ctx, chain, chainUser, chainUser, 100, mintedDenom) + + // mintedAndModified := helpers.CreateTokenFactoryDenom(t, ctx, chain, chainUser, "mandm") + // helpers.MintToTokenFactoryDenom(t, ctx, chain, chainUser, chainUser, 100, mintedAndModified) + + // ticker, desc, exponent := "TICKER", "desc", "6" + // helpers.UpdateTokenFactoryMetadata(t, ctx, chain, chainUser, mintedAndModified, ticker, desc, exponent) + + // // Validate pre upgrade denoms do not have the proper metadata + // // metadata: base:"factory/juno1hql0qadnznq8skf5q2psqmwj4thl2ajnvr3qrx/empty" > + // res := helpers.GetTokenFactoryDenomMetadata(t, ctx, chain, emptyFullDenom) + // require.Equal(t, res.DenomUnits[0].Denom, emptyFullDenom) + // require.Equal(t, res.Base, emptyFullDenom) + // require.Empty(t, res.Description) + // require.Empty(t, res.Display) + // require.Empty(t, res.Name) + // require.Empty(t, res.Symbol) + + // res = helpers.GetTokenFactoryDenomMetadata(t, ctx, chain, mintedDenom) + // require.Equal(t, res.DenomUnits[0].Denom, mintedDenom) + // require.Equal(t, res.Base, mintedDenom) + // require.Empty(t, res.Description) + // require.Empty(t, res.Display) + // require.Empty(t, res.Name) + // require.Empty(t, res.Symbol) + + // // Denom data should be as modified above + // modifiedRes := helpers.GetTokenFactoryDenomMetadata(t, ctx, chain, mintedAndModified) + // require.Equal(t, modifiedRes.DenomUnits[0].Denom, mintedAndModified) + // require.Equal(t, modifiedRes.Base, mintedAndModified) + // require.Equal(t, modifiedRes.Name, mintedAndModified) + // require.Equal(t, modifiedRes.Symbol, ticker) + // require.NotEmpty(t, modifiedRes.Description) + + // upgrade + height, err := chain.Height(ctx) + require.NoError(t, err, "error fetching height before submit upgrade proposal") + + haltHeight := height + haltHeightDelta + + proposal := cosmos.SoftwareUpgradeProposal{ + Deposit: "500000000" + chain.Config().Denom, // greater than min deposit + Title: "Chain Upgrade 1", + Name: upgradeName, + Description: "First chain software upgrade", + Height: haltHeight, + } + + upgradeTx, err := chain.UpgradeProposal(ctx, chainUser.KeyName(), proposal) + require.NoError(t, err, "error submitting software upgrade proposal tx") + + err = chain.VoteOnProposalAllValidators(ctx, upgradeTx.ProposalID, cosmos.ProposalVoteYes) + require.NoError(t, err, "failed to submit votes") + + _, err = cosmos.PollForProposalStatus(ctx, chain, height, height+haltHeightDelta, upgradeTx.ProposalID, cosmos.ProposalStatusPassed) + require.NoError(t, err, "proposal status did not change to passed in expected number of blocks") + + timeoutCtx, timeoutCtxCancel := context.WithTimeout(ctx, time.Second*45) + defer timeoutCtxCancel() + + height, err = chain.Height(ctx) + require.NoError(t, err, "error fetching height before upgrade") + + // this should timeout due to chain halt at upgrade height. + _ = testutil.WaitForBlocks(timeoutCtx, int(haltHeight-height), chain) + + height, err = chain.Height(ctx) + require.NoError(t, err, "error fetching height after chain should have halted") + + // make sure that chain is halted + require.Equal(t, haltHeight, height, "height is not equal to halt height") + + // bring down nodes to prepare for upgrade + t.Log("stopping node(s)") + err = chain.StopAllNodes(ctx) + require.NoError(t, err, "error stopping node(s)") + + // upgrade version on all nodes + t.Log("upgrading node(s)") + chain.UpgradeVersion(ctx, client, upgradeRepo, upgradeBranchVersion) + + // start all nodes back up. + // validators reach consensus on first block after upgrade height + // and chain block production resumes. + t.Log("starting node(s)") + err = chain.StartAllNodes(ctx) + require.NoError(t, err, "error starting upgraded node(s)") + + timeoutCtx, timeoutCtxCancel = context.WithTimeout(ctx, time.Second*60) + defer timeoutCtxCancel() + + err = testutil.WaitForBlocks(timeoutCtx, int(blocksAfterUpgrade), chain) + require.NoError(t, err, "chain did not produce blocks after upgrade") + + height, err = chain.Height(ctx) + require.NoError(t, err, "error fetching height after upgrade") + + require.GreaterOrEqual(t, height, haltHeight+blocksAfterUpgrade, "height did not increment enough after upgrade") + + // // Check that the tokenfactory denom's properly migrated + // postRes := helpers.GetTokenFactoryDenomMetadata(t, ctx, chain, emptyFullDenom) + // require.Equal(t, postRes.DenomUnits[0].Denom, emptyFullDenom) + // require.Equal(t, postRes.Base, emptyFullDenom) + // require.Equal(t, postRes.Display, emptyFullDenom) + // require.Equal(t, postRes.Name, emptyFullDenom) + // require.Equal(t, postRes.Symbol, emptyFullDenom) + + // postRes = helpers.GetTokenFactoryDenomMetadata(t, ctx, chain, mintedDenom) + // require.Equal(t, postRes.DenomUnits[0].Denom, mintedDenom) + // require.Equal(t, postRes.Base, mintedDenom) + // require.Equal(t, postRes.Display, mintedDenom) + // require.Equal(t, postRes.Name, mintedDenom) + // require.Equal(t, postRes.Symbol, mintedDenom) + + // // since we already set it, the should remain the same. + // postModified := helpers.GetTokenFactoryDenomMetadata(t, ctx, chain, mintedAndModified) + // require.Equal(t, postModified, modifiedRes) + + // // Ensure after the upgrade, the denoms are properly set with the Denom Metadata. + // afterUpgrade := helpers.CreateTokenFactoryDenom(t, ctx, chain, chainUser, "post") + // newRes := helpers.GetTokenFactoryDenomMetadata(t, ctx, chain, afterUpgrade) + // require.Equal(t, newRes.Display, afterUpgrade) + // require.Equal(t, newRes.Name, afterUpgrade) + // require.Equal(t, newRes.Symbol, afterUpgrade) +} diff --git a/interchaintest/ci_integration.go b/interchaintest/ci_integration.go new file mode 100644 index 0000000..d3389b0 --- /dev/null +++ b/interchaintest/ci_integration.go @@ -0,0 +1,23 @@ +package interchaintest + +import ( + "os" + "strings" +) + +// GetDockerImageInfo returns the appropriate repo and branch version string for integration with the CI pipeline. +// The remote runner sets the BRANCH_CI env var. If present, interchaintest will use the docker image pushed up to the repo. +// If testing locally, user should run `make local-image` and interchaintest will use the local image. +func GetDockerImageInfo() (repo, version string) { + branchVersion, found := os.LookupEnv("BRANCH_CI") + repo = TerpE2ERepo + if !found { + // make local-image + repo = "terp-core" + branchVersion = "local" + } + + // github converts / to - for pushed docker images + branchVersion = strings.ReplaceAll(branchVersion, "/", "-") + return repo, branchVersion +} diff --git a/interchaintest/contracts/ibchooks_counter.wasm b/interchaintest/contracts/ibchooks_counter.wasm new file mode 100644 index 0000000..938171e Binary files /dev/null and b/interchaintest/contracts/ibchooks_counter.wasm differ diff --git a/interchaintest/go.mod b/interchaintest/go.mod new file mode 100644 index 0000000..4dc24fd --- /dev/null +++ b/interchaintest/go.mod @@ -0,0 +1,24 @@ +module github.com/terpnework/terp-core/tests/interchaintest + +go 1.19 + +replace ( + // interchaintest supports ICS features so we need this for now + // github.com/cosmos/cosmos-sdk => github.com/cosmos/cosmos-sdk v0.45.13-ics + github.com/ChainSafe/go-schnorrkel => github.com/ChainSafe/go-schnorrkel v0.0.0-20200405005733-88cbf1b4c40d + github.com/ChainSafe/go-schnorrkel/1 => github.com/ChainSafe/go-schnorrkel v1.0.0 + // For this nested module, you always want to replace the parent reference with the current worktree. + // For now, we can not do this due to pulling tokenfactory in. + // github.com/terpnetwork/terp-core => ../../ + github.com/terpnetwork/terp-core/v2 v2.0.0 + github.com/btcsuite/btcd => github.com/btcsuite/btcd v0.22.2 //indirect + github.com/gogo/protobuf => github.com/regen-network/protobuf v1.3.3-alpha.regen.1 + + github.com/vedhavyas/go-subkey => github.com/strangelove-ventures/go-subkey v1.0.7 +) + +require ( + + github.com/strangelove-ventures/interchaintest/v7 v7.0.0-20230622193330-220ce33823c0 + go.uber.org/zap v1.24.0 +) \ No newline at end of file diff --git a/interchaintest/helpers/cosmwasm.go b/interchaintest/helpers/cosmwasm.go new file mode 100644 index 0000000..96c2ce9 --- /dev/null +++ b/interchaintest/helpers/cosmwasm.go @@ -0,0 +1,81 @@ +package helpers + +import ( + "context" + "testing" + + "github.com/cosmos/cosmos-sdk/crypto/keyring" + "github.com/strangelove-ventures/interchaintest/v7/chain/cosmos" + "github.com/strangelove-ventures/interchaintest/v7/ibc" + "github.com/strangelove-ventures/interchaintest/v7/testutil" + "github.com/stretchr/testify/require" +) + +func SetupContract(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain, keyname string, fileLoc string, message string) (codeId, contract string) { + codeId, err := chain.StoreContract(ctx, keyname, fileLoc) + if err != nil { + t.Fatal(err) + } + + contractAddr, err := chain.InstantiateContract(ctx, keyname, codeId, message, true) + if err != nil { + t.Fatal(err) + } + + return codeId, contractAddr +} + +func ExecuteMsgWithAmount(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain, user ibc.Wallet, contractAddr, amount, message string) { + // amount is #utoken + + // There has to be a way to do this in ictest? + cmd := []string{"terpd", "tx", "wasm", "execute", contractAddr, message, + "--node", chain.GetRPCAddress(), + "--home", chain.HomeDir(), + "--chain-id", chain.Config().ChainID, + "--from", user.KeyName(), + "--gas", "500000", + "--amount", amount, + "--keyring-dir", chain.HomeDir(), + "--keyring-backend", keyring.BackendTest, + "-y", + } + stdout, _, err := chain.Exec(ctx, cmd, nil) + require.NoError(t, err) + + debugOutput(t, string(stdout)) + + if err := testutil.WaitForBlocks(ctx, 2, chain); err != nil { + t.Fatal(err) + } +} + +func ExecuteMsgWithFee(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain, user ibc.Wallet, contractAddr, amount, feeCoin, message string) { + // amount is #utoken + + // There has to be a way to do this in ictest? + cmd := []string{"terpd", "tx", "wasm", "execute", contractAddr, message, + "--node", chain.GetRPCAddress(), + "--home", chain.HomeDir(), + "--chain-id", chain.Config().ChainID, + "--from", user.KeyName(), + "--gas", "500000", + "--fees", feeCoin, + "--keyring-dir", chain.HomeDir(), + "--keyring-backend", keyring.BackendTest, + "-y", + } + + if amount != "" { + cmd = append(cmd, "--amount", amount) + } + + stdout, _, err := chain.Exec(ctx, cmd, nil) + require.NoError(t, err) + + debugOutput(t, string(stdout)) + + if err := testutil.WaitForBlocks(ctx, 2, chain); err != nil { + t.Fatal(err) + } +} diff --git a/interchaintest/helpers/ibchooks.go b/interchaintest/helpers/ibchooks.go new file mode 100644 index 0000000..bb00af8 --- /dev/null +++ b/interchaintest/helpers/ibchooks.go @@ -0,0 +1,40 @@ +package helpers + +import ( + "context" + "strings" + "testing" + + "github.com/strangelove-ventures/interchaintest/v7/chain/cosmos" + "github.com/stretchr/testify/require" +) + +func GetIBCHooksUserAddress(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain, channel, uaddr string) string { + // terpd q ibchooks wasm-sender channel-0 "juno1hj5fveer5cjtn4wd6wstzugjfdxzl0xps73ftl" --node http://localhost:26657 + cmd := []string{"terpd", "query", "ibchooks", "wasm-sender", channel, uaddr, + "--node", chain.GetRPCAddress(), + "--chain-id", chain.Config().ChainID, + "--output", "json", + } + + // This query does not return a type, just prints the string. + stdout, _, err := chain.Exec(ctx, cmd, nil) + require.NoError(t, err) + + address := strings.Replace(string(stdout), "\n", "", -1) + return address +} + +func GetIBCHookTotalFunds(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain, contract string, uaddr string) GetTotalFundsResponse { + var res GetTotalFundsResponse + err := chain.QueryContract(ctx, contract, QueryMsg{GetTotalFunds: &GetTotalFundsQuery{Addr: uaddr}}, &res) + require.NoError(t, err) + return res +} + +func GetIBCHookCount(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain, contract string, uaddr string) GetCountResponse { + var res GetCountResponse + err := chain.QueryContract(ctx, contract, QueryMsg{GetCount: &GetCountQuery{Addr: uaddr}}, &res) + require.NoError(t, err) + return res +} diff --git a/interchaintest/helpers/query_helpers.go b/interchaintest/helpers/query_helpers.go new file mode 100644 index 0000000..511cd7e --- /dev/null +++ b/interchaintest/helpers/query_helpers.go @@ -0,0 +1,24 @@ +package helpers + +import ( + "context" + "testing" + + "github.com/strangelove-ventures/interchaintest/v7/chain/cosmos" + "github.com/stretchr/testify/require" +) + +func GetUserTokenFactoryBalances(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain, contract string, uaddr string) GetAllBalancesResponse { + var res GetAllBalancesResponse + err := chain.QueryContract(ctx, contract, QueryMsg{GetAllBalances: &GetAllBalancesQuery{Address: uaddr}}, &res) + require.NoError(t, err) + return res +} + +func GetUnityContractWithdrawalReadyTime(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain, contract string) WithdrawalTimestampResponse { + // terpd query wasm contract-state smart '{"get_withdrawal_ready_time":{}}' --output json + var res WithdrawalTimestampResponse + err := chain.QueryContract(ctx, contract, QueryMsg{GetWithdrawalReadyTime: &struct{}{}}, &res) + require.NoError(t, err) + return res +} diff --git a/interchaintest/helpers/types.go b/interchaintest/helpers/types.go new file mode 100644 index 0000000..d3d49d7 --- /dev/null +++ b/interchaintest/helpers/types.go @@ -0,0 +1,78 @@ +package helpers + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// Go based data types for querying on the contract. +// Execute types are not needed here. We just use strings. Could add though in the future and to_string it + +// EntryPoint +type QueryMsg struct { + // Tokenfactory Core + GetConfig *struct{} `json:"get_config,omitempty"` + GetBalance *GetBalanceQuery `json:"get_balance,omitempty"` + GetAllBalances *GetAllBalancesQuery `json:"get_all_balances,omitempty"` + + // Unity Contract + GetWithdrawalReadyTime *struct{} `json:"get_withdrawal_ready_time,omitempty"` + + // IBCHooks + GetCount *GetCountQuery `json:"get_count,omitempty"` + GetTotalFunds *GetTotalFundsQuery `json:"get_total_funds,omitempty"` +} + +type GetAllBalancesQuery struct { + Address string `json:"address"` +} +type GetAllBalancesResponse struct { + // or is it wasm Coin type? + Data []sdk.Coin `json:"data"` +} + +type GetBalanceQuery struct { + // {"get_balance":{"address":"terp1...","denom":"factory/terp1.../RcqfWz"}} + Address string `json:"address"` + Denom string `json:"denom"` +} +type GetBalanceResponse struct { + // or is it wasm Coin type? + Data sdk.Coin `json:"data"` +} + +type WithdrawalTimestampResponse struct { + // {"data":{"withdrawal_ready_timestamp":"1686146048614053435"}} + Data *WithdrawalTimestampObj `json:"data"` +} +type WithdrawalTimestampObj struct { + WithdrawalReadyTimestamp string `json:"withdrawal_ready_timestamp"` +} + +type GetTotalFundsQuery struct { + // {"get_total_funds":{"addr":"terp1..."}} + Addr string `json:"addr"` +} +type GetTotalFundsResponse struct { + // {"data":{"total_funds":[{"denom":"ibc/04F5F501207C3626A2C14BFEF654D51C2E0B8F7CA578AB8ED272A66FE4E48097","amount":"1"}]}} + Data *GetTotalFundsObj `json:"data"` +} +type GetTotalFundsObj struct { + TotalFunds []WasmCoin `json:"total_funds"` +} + +type WasmCoin struct { + Denom string `json:"denom"` + Amount string `json:"amount"` +} + +type GetCountQuery struct { + // {"get_total_funds":{"addr":"terp1..."}} + Addr string `json:"addr"` +} +type GetCountResponse struct { + // {"data":{"count":0}} + Data *GetCountObj `json:"data"` +} +type GetCountObj struct { + Count int64 `json:"count"` +} diff --git a/interchaintest/ibc_transfer_test.go b/interchaintest/ibc_transfer_test.go new file mode 100644 index 0000000..ee743a8 --- /dev/null +++ b/interchaintest/ibc_transfer_test.go @@ -0,0 +1,185 @@ +package interchaintest + +import ( + "context" + "testing" + + transfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" + "github.com/strangelove-ventures/interchaintest/v7" + "github.com/strangelove-ventures/interchaintest/v7/chain/cosmos" + "github.com/strangelove-ventures/interchaintest/v7/ibc" + interchaintestrelayer "github.com/strangelove-ventures/interchaintest/v7/relayer" + "github.com/strangelove-ventures/interchaintest/v7/testreporter" + "github.com/strangelove-ventures/interchaintest/v7/testutil" + "github.com/stretchr/testify/require" + "go.uber.org/zap/zaptest" +) + +// TestTerpGaiaIBCTransfer spins up a Terp and Gaia network, initializes an IBC connection between them, +// and sends an ICS20 token transfer from Terp->Gaia and then back from Gaia->Terp. +func TestTerpGaiaIBCTransfer(t *testing.T) { + if testing.Short() { + t.Skip() + } + + t.Parallel() + + // Create chain factory with Terp and Gaia + numVals := 1 + numFullNodes := 1 + + cf := interchaintest.NewBuiltinChainFactory(zaptest.NewLogger(t), []*interchaintest.ChainSpec{ + { + Name: "terp", + ChainConfig: terpConfig, + NumValidators: &numVals, + NumFullNodes: &numFullNodes, + }, + { + Name: "gaia", + Version: "v9.1.0", + NumValidators: &numVals, + NumFullNodes: &numFullNodes, + }, + }) + + const ( + path = "ibc-path" + ) + + // Get chains from the chain factory + chains, err := cf.Chains(t.Name()) + require.NoError(t, err) + + client, network := interchaintest.DockerSetup(t) + + terp, gaia := chains[0].(*cosmos.CosmosChain), chains[1].(*cosmos.CosmosChain) + + relayerType, relayerName := ibc.CosmosRly, "relay" + + // Get a relayer instance + rf := interchaintest.NewBuiltinRelayerFactory( + relayerType, + zaptest.NewLogger(t), + interchaintestrelayer.CustomDockerImage(IBCRelayerImage, IBCRelayerVersion, "100:1000"), + interchaintestrelayer.StartupFlags("--processor", "events", "--block-history", "100"), + ) + + r := rf.Build(t, client, network) + + ic := interchaintest.NewInterchain(). + AddChain(terp). + AddChain(gaia). + AddRelayer(r, relayerName). + AddLink(interchaintest.InterchainLink{ + Chain1: terp, + Chain2: gaia, + Relayer: r, + Path: path, + }) + + ctx := context.Background() + + rep := testreporter.NewNopReporter() + eRep := rep.RelayerExecReporter(t) + + require.NoError(t, ic.Build(ctx, eRep, interchaintest.InterchainBuildOptions{ + TestName: t.Name(), + Client: client, + NetworkID: network, + BlockDatabaseFile: interchaintest.DefaultBlockDatabaseFilepath(), + SkipPathCreation: false, + })) + t.Cleanup(func() { + _ = ic.Close() + }) + + // Create some user accounts on both chains + users := interchaintest.GetAndFundTestUsers(t, ctx, t.Name(), genesisWalletAmount, terp, gaia) + + // Wait a few blocks for relayer to start and for user accounts to be created + err = testutil.WaitForBlocks(ctx, 5, terp, gaia) + require.NoError(t, err) + + // Get our Bech32 encoded user addresses + terpUser, gaiaUser := users[0], users[1] + + terpUserAddr := terpUser.FormattedAddress() + gaiaUserAddr := gaiaUser.FormattedAddress() + + // Get original account balances + terpOrigBal, err := terp.GetBalance(ctx, terpUserAddr, terp.Config().Denom) + require.NoError(t, err) + require.Equal(t, genesisWalletAmount, terpOrigBal) + + gaiaOrigBal, err := gaia.GetBalance(ctx, gaiaUserAddr, gaia.Config().Denom) + require.NoError(t, err) + require.Equal(t, genesisWalletAmount, gaiaOrigBal) + + // Compose an IBC transfer and send from Terp -> Gaia + const transferAmount = int64(1_000) + transfer := ibc.WalletAmount{ + Address: gaiaUserAddr, + Denom: terp.Config().Denom, + Amount: transferAmount, + } + + channel, err := ibc.GetTransferChannel(ctx, r, eRep, terp.Config().ChainID, gaia.Config().ChainID) + require.NoError(t, err) + + transferTx, err := terp.SendIBCTransfer(ctx, channel.ChannelID, terpUserAddr, transfer, ibc.TransferOptions{}) + require.NoError(t, err) + + terpHeight, err := terp.Height(ctx) + require.NoError(t, err) + + // Poll for the ack to know the transfer was successful + // TODO: Remove after auto transfer is fixed in the relayer + r.Flush(ctx, eRep, path, channel.ChannelID) + _, err = testutil.PollForAck(ctx, terp, terpHeight-5, terpHeight+50, transferTx.Packet) + require.NoError(t, err) + + err = testutil.WaitForBlocks(ctx, 10, terp) + require.NoError(t, err) + + // Get the IBC denom for uterp on Gaia + terpTokenDenom := transfertypes.GetPrefixedDenom(channel.Counterparty.PortID, channel.Counterparty.ChannelID, terp.Config().Denom) + terpIBCDenom := transfertypes.ParseDenomTrace(terpTokenDenom).IBCDenom() + + // Assert that the funds are no longer present in user acc on Terp and are in the user acc on Gaia + terpUpdateBal, err := terp.GetBalance(ctx, terpUserAddr, terp.Config().Denom) + require.NoError(t, err) + require.Equal(t, terpOrigBal-transferAmount, terpUpdateBal) + + gaiaUpdateBal, err := gaia.GetBalance(ctx, gaiaUserAddr, terpIBCDenom) + require.NoError(t, err) + require.Equal(t, transferAmount, gaiaUpdateBal) + + // Compose an IBC transfer and send from Gaia -> Terp + transfer = ibc.WalletAmount{ + Address: terpUserAddr, + Denom: terpIBCDenom, + Amount: transferAmount, + } + + transferTx, err = gaia.SendIBCTransfer(ctx, channel.Counterparty.ChannelID, gaiaUserAddr, transfer, ibc.TransferOptions{}) + require.NoError(t, err) + + gaiaHeight, err := gaia.Height(ctx) + require.NoError(t, err) + + // Poll for the ack to know the transfer was successful + // TODO: Remove after auto transfer is fixed in the relayer + r.Flush(ctx, eRep, path, channel.Counterparty.ChannelID) + _, err = testutil.PollForAck(ctx, gaia, gaiaHeight, gaiaHeight+25, transferTx.Packet) + require.NoError(t, err) + + // Assert that the funds are now back on Terp and not on Gaia + terpUpdateBal, err = terp.GetBalance(ctx, terpUserAddr, terp.Config().Denom) + require.NoError(t, err) + require.Equal(t, terpOrigBal, terpUpdateBal) + + gaiaUpdateBal, err = gaia.GetBalance(ctx, gaiaUserAddr, terpIBCDenom) + require.NoError(t, err) + require.Equal(t, int64(0), gaiaUpdateBal) +} diff --git a/interchaintest/module_ibchooks_test.go b/interchaintest/module_ibchooks_test.go new file mode 100644 index 0000000..0195448 --- /dev/null +++ b/interchaintest/module_ibchooks_test.go @@ -0,0 +1,173 @@ +package interchaintest + +import ( + "context" + "fmt" + "strings" + "testing" + + "github.com/strangelove-ventures/interchaintest/v7" + "github.com/strangelove-ventures/interchaintest/v7/chain/cosmos" + "github.com/strangelove-ventures/interchaintest/v7/ibc" + interchaintestrelayer "github.com/strangelove-ventures/interchaintest/v7/relayer" + "github.com/strangelove-ventures/interchaintest/v7/testreporter" + "github.com/strangelove-ventures/interchaintest/v7/testutil" + "github.com/stretchr/testify/require" + helpers "github.com/terpnetwork/terp-core/tests/interchaintest/helpers" + "go.uber.org/zap/zaptest" +) + +// TestTerpIBCHooks ensures the ibc-hooks middleware from osmosis works. +func TestTerpIBCHooks(t *testing.T) { + if testing.Short() { + t.Skip() + } + + t.Parallel() + + // Create chain factory with Terp and terp2 + numVals := 1 + numFullNodes := 0 + + cfg2 := terpConfig.Clone() + cfg2.Name = "terp-counterparty" + cfg2.ChainID = "counterparty-2" + + cf := interchaintest.NewBuiltinChainFactory(zaptest.NewLogger(t), []*interchaintest.ChainSpec{ + { + Name: "terp", + ChainConfig: terpConfig, + NumValidators: &numVals, + NumFullNodes: &numFullNodes, + }, + { + Name: "terp", + ChainConfig: cfg2, + NumValidators: &numVals, + NumFullNodes: &numFullNodes, + }, + }) + + const ( + path = "ibc-path" + ) + + // Get chains from the chain factory + chains, err := cf.Chains(t.Name()) + require.NoError(t, err) + + client, network := interchaintest.DockerSetup(t) + + terp, terp2 := chains[0].(*cosmos.CosmosChain), chains[1].(*cosmos.CosmosChain) + + relayerType, relayerName := ibc.CosmosRly, "relay" + + // Get a relayer instance + rf := interchaintest.NewBuiltinRelayerFactory( + relayerType, + zaptest.NewLogger(t), + interchaintestrelayer.CustomDockerImage(IBCRelayerImage, IBCRelayerVersion, "100:1000"), + interchaintestrelayer.StartupFlags("--processor", "events", "--block-history", "100"), + ) + + r := rf.Build(t, client, network) + + ic := interchaintest.NewInterchain(). + AddChain(terp). + AddChain(terp2). + AddRelayer(r, relayerName). + AddLink(interchaintest.InterchainLink{ + Chain1: terp, + Chain2: terp2, + Relayer: r, + Path: path, + }) + + ctx := context.Background() + + rep := testreporter.NewNopReporter() + eRep := rep.RelayerExecReporter(t) + + require.NoError(t, ic.Build(ctx, eRep, interchaintest.InterchainBuildOptions{ + TestName: t.Name(), + Client: client, + NetworkID: network, + BlockDatabaseFile: interchaintest.DefaultBlockDatabaseFilepath(), + SkipPathCreation: false, + })) + t.Cleanup(func() { + _ = ic.Close() + }) + + // Create some user accounts on both chains + users := interchaintest.GetAndFundTestUsers(t, ctx, t.Name(), genesisWalletAmount, terp, terp2) + + // Wait a few blocks for relayer to start and for user accounts to be created + err = testutil.WaitForBlocks(ctx, 5, terp, terp2) + require.NoError(t, err) + + // Get our Bech32 encoded user addresses + terpUser, terp2User := users[0], users[1] + + terpUserAddr := terpUser.FormattedAddress() + // terp2UserAddr := terp2User.FormattedAddress() + + channel, err := ibc.GetTransferChannel(ctx, r, eRep, terp.Config().ChainID, terp2.Config().ChainID) + require.NoError(t, err) + + _, contractAddr := helpers.SetupContract(t, ctx, terp2, terp2User.KeyName(), "contracts/ibchooks_counter.wasm", `{"count":0}`) + + // do an ibc transfer through the memo to the other chain. + transfer := ibc.WalletAmount{ + Address: contractAddr, + Denom: terp.Config().Denom, + Amount: int64(1), + } + + memo := ibc.TransferOptions{ + Memo: fmt.Sprintf(`{"wasm":{"contract":"%s","msg":%s}}`, contractAddr, `{"increment":{}}`), + } + + // Initial transfer. Account is created by the wasm execute is not so we must do this twice to properly set up + transferTx, err := terp.SendIBCTransfer(ctx, channel.ChannelID, terpUser.KeyName(), transfer, memo) + require.NoError(t, err) + terpHeight, err := terp.Height(ctx) + require.NoError(t, err) + + // TODO: Remove when the relayer is fixed + r.Flush(ctx, eRep, path, channel.ChannelID) + _, err = testutil.PollForAck(ctx, terp, terpHeight-5, terpHeight+25, transferTx.Packet) + require.NoError(t, err) + + // Second time, this will make the counter == 1 since the account is now created. + transferTx, err = terp.SendIBCTransfer(ctx, channel.ChannelID, terpUser.KeyName(), transfer, memo) + require.NoError(t, err) + terpHeight, err = terp.Height(ctx) + require.NoError(t, err) + + // TODO: Remove when the relayer is fixed + r.Flush(ctx, eRep, path, channel.ChannelID) + _, err = testutil.PollForAck(ctx, terp, terpHeight-5, terpHeight+25, transferTx.Packet) + require.NoError(t, err) + + // Get the address on the other chain's side + addr := helpers.GetIBCHooksUserAddress(t, ctx, terp, channel.ChannelID, terpUserAddr) + require.NotEmpty(t, addr) + + // Get funds on the receiving chain + funds := helpers.GetIBCHookTotalFunds(t, ctx, terp2, contractAddr, addr) + require.Equal(t, int(1), len(funds.Data.TotalFunds)) + + var ibcDenom string + for _, coin := range funds.Data.TotalFunds { + if strings.HasPrefix(coin.Denom, "ibc/") { + ibcDenom = coin.Denom + break + } + } + require.NotEmpty(t, ibcDenom) + + // ensure the count also increased to 1 as expected. + count := helpers.GetIBCHookCount(t, ctx, terp2, contractAddr, addr) + require.Equal(t, int64(1), count.Data.Count) +} diff --git a/interchaintest/module_pfm_test.go b/interchaintest/module_pfm_test.go new file mode 100644 index 0000000..9176dca --- /dev/null +++ b/interchaintest/module_pfm_test.go @@ -0,0 +1,694 @@ +package interchaintest + +import ( + "context" + "encoding/json" + "testing" + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" + transfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" + "github.com/strangelove-ventures/interchaintest/v7" + "github.com/strangelove-ventures/interchaintest/v7/chain/cosmos" + "github.com/strangelove-ventures/interchaintest/v7/ibc" + interchaintestrelayer "github.com/strangelove-ventures/interchaintest/v7/relayer" + "github.com/strangelove-ventures/interchaintest/v7/testreporter" + "github.com/strangelove-ventures/interchaintest/v7/testutil" + "github.com/stretchr/testify/require" + "go.uber.org/zap/zaptest" +) + +type PacketMetadata struct { + Forward *ForwardMetadata `json:"forward"` +} + +type ForwardMetadata struct { + Receiver string `json:"receiver"` + Port string `json:"port"` + Channel string `json:"channel"` + Timeout time.Duration `json:"timeout"` + Retries *uint8 `json:"retries,omitempty"` + Next *string `json:"next,omitempty"` + RefundSequence *uint64 `json:"refund_sequence,omitempty"` +} + +// TestPacketForwardMiddlewareRouter ensures the PFM module is set up properly and works as expected. +func TestPacketForwardMiddlewareRouter(t *testing.T) { + if testing.Short() { + t.Skip() + } + + var ( + ctx = context.Background() + client, network = interchaintest.DockerSetup(t) + rep = testreporter.NewNopReporter() + eRep = rep.RelayerExecReporter(t) + chainID_A, chainID_B, chainID_C, chainID_D = "chain-a", "chain-b", "chain-c", "chain-d" + chainA, chainB, chainC, chainD *cosmos.CosmosChain + ) + + // base config which all networks will use as defaults. + baseCfg := ibc.ChainConfig{ + Type: "cosmos", + Name: "terp", + ChainID: "", // change this for each + Images: []ibc.DockerImage{TerpImage}, + Bin: "terpd", + Bech32Prefix: "terp", + Denom: "uterp", + CoinType: "118", + GasPrices: "0uterp", + GasAdjustment: 2.0, + TrustingPeriod: "112h", + NoHostMount: false, + ConfigFileOverrides: nil, + EncodingConfig: terpEncoding(), + UsingNewGenesisCommand: true, + ModifyGenesis: cosmos.ModifyGenesis(defaultGenesisKV), + } + + // Set specific chain ids for each so they are their own unique networks + baseCfg.ChainID = chainID_A + configA := baseCfg + + baseCfg.ChainID = chainID_B + configB := baseCfg + + baseCfg.ChainID = chainID_C + configC := baseCfg + + baseCfg.ChainID = chainID_D + configD := baseCfg + + // Create chain factory with multiple Terp individual networks. + numVals := 1 + numFullNodes := 0 + + cf := interchaintest.NewBuiltinChainFactory(zaptest.NewLogger(t), []*interchaintest.ChainSpec{ + { + Name: "terp", + ChainConfig: configA, + NumValidators: &numVals, + NumFullNodes: &numFullNodes, + }, + { + Name: "terp", + ChainConfig: configB, + NumValidators: &numVals, + NumFullNodes: &numFullNodes, + }, + { + Name: "terp", + ChainConfig: configC, + NumValidators: &numVals, + NumFullNodes: &numFullNodes, + }, + { + Name: "terp", + ChainConfig: configD, + NumValidators: &numVals, + NumFullNodes: &numFullNodes, + }, + }) + + // Get chains from the chain factory + chains, err := cf.Chains(t.Name()) + require.NoError(t, err) + + chainA, chainB, chainC, chainD = chains[0].(*cosmos.CosmosChain), chains[1].(*cosmos.CosmosChain), chains[2].(*cosmos.CosmosChain), chains[3].(*cosmos.CosmosChain) + + r := interchaintest.NewBuiltinRelayerFactory( + ibc.CosmosRly, + zaptest.NewLogger(t), + interchaintestrelayer.CustomDockerImage(IBCRelayerImage, IBCRelayerVersion, "100:1000"), + interchaintestrelayer.StartupFlags("--processor", "events", "--block-history", "100"), + ).Build(t, client, network) + + const pathAB = "ab" + const pathBC = "bc" + const pathCD = "cd" + + ic := interchaintest.NewInterchain(). + AddChain(chainA). + AddChain(chainB). + AddChain(chainC). + AddChain(chainD). + AddRelayer(r, "relayer"). + AddLink(interchaintest.InterchainLink{ + Chain1: chainA, + Chain2: chainB, + Relayer: r, + Path: pathAB, + }). + AddLink(interchaintest.InterchainLink{ + Chain1: chainB, + Chain2: chainC, + Relayer: r, + Path: pathBC, + }). + AddLink(interchaintest.InterchainLink{ + Chain1: chainC, + Chain2: chainD, + Relayer: r, + Path: pathCD, + }) + + require.NoError(t, ic.Build(ctx, eRep, interchaintest.InterchainBuildOptions{ + TestName: t.Name(), + Client: client, + NetworkID: network, + BlockDatabaseFile: interchaintest.DefaultBlockDatabaseFilepath(), + + SkipPathCreation: false, + })) + t.Cleanup(func() { + _ = ic.Close() + }) + + const userFunds = int64(10_000_000_000) + users := interchaintest.GetAndFundTestUsers(t, ctx, t.Name(), userFunds, chainA, chainB, chainC, chainD) + + abChan, err := ibc.GetTransferChannel(ctx, r, eRep, chainID_A, chainID_B) + require.NoError(t, err) + + baChan := abChan.Counterparty + + cbChan, err := ibc.GetTransferChannel(ctx, r, eRep, chainID_C, chainID_B) + require.NoError(t, err) + + bcChan := cbChan.Counterparty + + dcChan, err := ibc.GetTransferChannel(ctx, r, eRep, chainID_D, chainID_C) + require.NoError(t, err) + + cdChan := dcChan.Counterparty + + // Start the relayer on all paths + err = r.StartRelayer(ctx, eRep, pathAB, pathBC, pathCD) + require.NoError(t, err) + + t.Cleanup( + func() { + err := r.StopRelayer(ctx, eRep) + if err != nil { + t.Logf("an error occured while stopping the relayer: %s", err) + } + }, + ) + + // Get original account balances + userA, userB, userC, userD := users[0], users[1], users[2], users[3] + + const transferAmount int64 = 100000 + + // Compose the prefixed denoms and ibc denom for asserting balances + firstHopDenom := transfertypes.GetPrefixedDenom(baChan.PortID, baChan.ChannelID, chainA.Config().Denom) + secondHopDenom := transfertypes.GetPrefixedDenom(cbChan.PortID, cbChan.ChannelID, firstHopDenom) + thirdHopDenom := transfertypes.GetPrefixedDenom(dcChan.PortID, dcChan.ChannelID, secondHopDenom) + + firstHopDenomTrace := transfertypes.ParseDenomTrace(firstHopDenom) + secondHopDenomTrace := transfertypes.ParseDenomTrace(secondHopDenom) + thirdHopDenomTrace := transfertypes.ParseDenomTrace(thirdHopDenom) + + firstHopIBCDenom := firstHopDenomTrace.IBCDenom() + secondHopIBCDenom := secondHopDenomTrace.IBCDenom() + thirdHopIBCDenom := thirdHopDenomTrace.IBCDenom() + + firstHopEscrowAccount := sdk.MustBech32ifyAddressBytes(chainA.Config().Bech32Prefix, transfertypes.GetEscrowAddress(abChan.PortID, abChan.ChannelID)) + secondHopEscrowAccount := sdk.MustBech32ifyAddressBytes(chainB.Config().Bech32Prefix, transfertypes.GetEscrowAddress(bcChan.PortID, bcChan.ChannelID)) + thirdHopEscrowAccount := sdk.MustBech32ifyAddressBytes(chainC.Config().Bech32Prefix, transfertypes.GetEscrowAddress(cdChan.PortID, abChan.ChannelID)) + + t.Run("multi-hop a->b->c->d", func(t *testing.T) { + // Send packet from Chain A->Chain B->Chain C->Chain D + + transfer := ibc.WalletAmount{ + Address: userB.FormattedAddress(), + Denom: chainA.Config().Denom, + Amount: transferAmount, + } + + secondHopMetadata := &PacketMetadata{ + Forward: &ForwardMetadata{ + Receiver: userD.FormattedAddress(), + Channel: cdChan.ChannelID, + Port: cdChan.PortID, + }, + } + nextBz, err := json.Marshal(secondHopMetadata) + require.NoError(t, err) + next := string(nextBz) + + firstHopMetadata := &PacketMetadata{ + Forward: &ForwardMetadata{ + Receiver: userC.FormattedAddress(), + Channel: bcChan.ChannelID, + Port: bcChan.PortID, + Next: &next, + }, + } + + memo, err := json.Marshal(firstHopMetadata) + require.NoError(t, err) + + chainAHeight, err := chainA.Height(ctx) + require.NoError(t, err) + + transferTx, err := chainA.SendIBCTransfer(ctx, abChan.ChannelID, userA.KeyName(), transfer, ibc.TransferOptions{Memo: string(memo)}) + require.NoError(t, err) + _, err = testutil.PollForAck(ctx, chainA, chainAHeight, chainAHeight+30, transferTx.Packet) + require.NoError(t, err) + err = testutil.WaitForBlocks(ctx, 1, chainA) + require.NoError(t, err) + + chainABalance, err := chainA.GetBalance(ctx, userA.FormattedAddress(), chainA.Config().Denom) + require.NoError(t, err) + + chainBBalance, err := chainB.GetBalance(ctx, userB.FormattedAddress(), firstHopIBCDenom) + require.NoError(t, err) + + chainCBalance, err := chainC.GetBalance(ctx, userC.FormattedAddress(), secondHopIBCDenom) + require.NoError(t, err) + + chainDBalance, err := chainD.GetBalance(ctx, userD.FormattedAddress(), thirdHopIBCDenom) + require.NoError(t, err) + + require.Equal(t, userFunds-transferAmount, chainABalance) + require.Equal(t, int64(0), chainBBalance) + require.Equal(t, int64(0), chainCBalance) + require.Equal(t, transferAmount, chainDBalance) + + firstHopEscrowBalance, err := chainA.GetBalance(ctx, firstHopEscrowAccount, chainA.Config().Denom) + require.NoError(t, err) + + secondHopEscrowBalance, err := chainB.GetBalance(ctx, secondHopEscrowAccount, firstHopIBCDenom) + require.NoError(t, err) + + thirdHopEscrowBalance, err := chainC.GetBalance(ctx, thirdHopEscrowAccount, secondHopIBCDenom) + require.NoError(t, err) + + require.Equal(t, transferAmount, firstHopEscrowBalance) + require.Equal(t, transferAmount, secondHopEscrowBalance) + require.Equal(t, transferAmount, thirdHopEscrowBalance) + }) + + t.Run("multi-hop denom unwind d->c->b->a", func(t *testing.T) { + // Send packet back from Chain D->Chain C->Chain B->Chain A + transfer := ibc.WalletAmount{ + Address: userC.FormattedAddress(), + Denom: thirdHopIBCDenom, + Amount: transferAmount, + } + + secondHopMetadata := &PacketMetadata{ + Forward: &ForwardMetadata{ + Receiver: userA.FormattedAddress(), + Channel: baChan.ChannelID, + Port: baChan.PortID, + }, + } + + nextBz, err := json.Marshal(secondHopMetadata) + require.NoError(t, err) + + next := string(nextBz) + + firstHopMetadata := &PacketMetadata{ + Forward: &ForwardMetadata{ + Receiver: userB.FormattedAddress(), + Channel: cbChan.ChannelID, + Port: cbChan.PortID, + Next: &next, + }, + } + + memo, err := json.Marshal(firstHopMetadata) + require.NoError(t, err) + + chainDHeight, err := chainD.Height(ctx) + require.NoError(t, err) + + transferTx, err := chainD.SendIBCTransfer(ctx, dcChan.ChannelID, userD.KeyName(), transfer, ibc.TransferOptions{Memo: string(memo)}) + require.NoError(t, err) + _, err = testutil.PollForAck(ctx, chainD, chainDHeight, chainDHeight+30, transferTx.Packet) + require.NoError(t, err) + err = testutil.WaitForBlocks(ctx, 1, chainA) + require.NoError(t, err) + + // assert balances for user controlled wallets + chainDBalance, err := chainD.GetBalance(ctx, userD.FormattedAddress(), thirdHopIBCDenom) + require.NoError(t, err) + + chainCBalance, err := chainC.GetBalance(ctx, userC.FormattedAddress(), secondHopIBCDenom) + require.NoError(t, err) + + chainBBalance, err := chainB.GetBalance(ctx, userB.FormattedAddress(), firstHopIBCDenom) + require.NoError(t, err) + + chainABalance, err := chainA.GetBalance(ctx, userA.FormattedAddress(), chainA.Config().Denom) + require.NoError(t, err) + + require.Equal(t, int64(0), chainDBalance) + require.Equal(t, int64(0), chainCBalance) + require.Equal(t, int64(0), chainBBalance) + require.Equal(t, userFunds, chainABalance) + + // assert balances for IBC escrow accounts + firstHopEscrowBalance, err := chainA.GetBalance(ctx, firstHopEscrowAccount, chainA.Config().Denom) + require.NoError(t, err) + + secondHopEscrowBalance, err := chainB.GetBalance(ctx, secondHopEscrowAccount, firstHopIBCDenom) + require.NoError(t, err) + + thirdHopEscrowBalance, err := chainC.GetBalance(ctx, thirdHopEscrowAccount, secondHopIBCDenom) + require.NoError(t, err) + + require.Equal(t, int64(0), firstHopEscrowBalance) + require.Equal(t, int64(0), secondHopEscrowBalance) + require.Equal(t, int64(0), thirdHopEscrowBalance) + }) + + t.Run("forward ack error refund", func(t *testing.T) { + // Send a malformed packet with invalid receiver address from Chain A->Chain B->Chain C + // This should succeed in the first hop and fail to make the second hop; funds should then be refunded to Chain A. + transfer := ibc.WalletAmount{ + Address: userB.FormattedAddress(), + Denom: chainA.Config().Denom, + Amount: transferAmount, + } + + metadata := &PacketMetadata{ + Forward: &ForwardMetadata{ + Receiver: "xyz1t8eh66t2w5k67kwurmn5gqhtq6d2ja0vp7jmmq", // malformed receiver address on Chain C + Channel: bcChan.ChannelID, + Port: bcChan.PortID, + }, + } + + memo, err := json.Marshal(metadata) + require.NoError(t, err) + + chainAHeight, err := chainA.Height(ctx) + require.NoError(t, err) + + transferTx, err := chainA.SendIBCTransfer(ctx, abChan.ChannelID, userA.KeyName(), transfer, ibc.TransferOptions{Memo: string(memo)}) + require.NoError(t, err) + _, err = testutil.PollForAck(ctx, chainA, chainAHeight, chainAHeight+25, transferTx.Packet) + require.NoError(t, err) + err = testutil.WaitForBlocks(ctx, 1, chainA) + require.NoError(t, err) + + // assert balances for user controlled wallets + chainABalance, err := chainA.GetBalance(ctx, userA.FormattedAddress(), chainA.Config().Denom) + require.NoError(t, err) + + chainBBalance, err := chainB.GetBalance(ctx, userB.FormattedAddress(), firstHopIBCDenom) + require.NoError(t, err) + + chainCBalance, err := chainC.GetBalance(ctx, userC.FormattedAddress(), secondHopIBCDenom) + require.NoError(t, err) + + require.Equal(t, userFunds, chainABalance) + require.Equal(t, int64(0), chainBBalance) + require.Equal(t, int64(0), chainCBalance) + + // assert balances for IBC escrow accounts + firstHopEscrowBalance, err := chainA.GetBalance(ctx, firstHopEscrowAccount, chainA.Config().Denom) + require.NoError(t, err) + + secondHopEscrowBalance, err := chainB.GetBalance(ctx, secondHopEscrowAccount, firstHopIBCDenom) + require.NoError(t, err) + + require.Equal(t, int64(0), firstHopEscrowBalance) + require.Equal(t, int64(0), secondHopEscrowBalance) + }) + + t.Run("forward timeout refund", func(t *testing.T) { + // Send packet from Chain A->Chain B->Chain C with the timeout so low for B->C transfer that it can not make it from B to C, which should result in a refund from B to A after two retries. + transfer := ibc.WalletAmount{ + Address: userB.FormattedAddress(), + Denom: chainA.Config().Denom, + Amount: transferAmount, + } + + retries := uint8(2) + metadata := &PacketMetadata{ + Forward: &ForwardMetadata{ + Receiver: userC.FormattedAddress(), + Channel: bcChan.ChannelID, + Port: bcChan.PortID, + Retries: &retries, + Timeout: 1 * time.Second, + }, + } + + memo, err := json.Marshal(metadata) + require.NoError(t, err) + + chainAHeight, err := chainA.Height(ctx) + require.NoError(t, err) + + transferTx, err := chainA.SendIBCTransfer(ctx, abChan.ChannelID, userA.KeyName(), transfer, ibc.TransferOptions{Memo: string(memo)}) + require.NoError(t, err) + _, err = testutil.PollForAck(ctx, chainA, chainAHeight, chainAHeight+25, transferTx.Packet) + require.NoError(t, err) + err = testutil.WaitForBlocks(ctx, 1, chainA) + require.NoError(t, err) + + // assert balances for user controlled wallets + chainABalance, err := chainA.GetBalance(ctx, userA.FormattedAddress(), chainA.Config().Denom) + require.NoError(t, err) + + chainBBalance, err := chainB.GetBalance(ctx, userB.FormattedAddress(), firstHopIBCDenom) + require.NoError(t, err) + + chainCBalance, err := chainC.GetBalance(ctx, userC.FormattedAddress(), secondHopIBCDenom) + require.NoError(t, err) + + require.Equal(t, userFunds, chainABalance) + require.Equal(t, int64(0), chainBBalance) + require.Equal(t, int64(0), chainCBalance) + + firstHopEscrowBalance, err := chainA.GetBalance(ctx, firstHopEscrowAccount, chainA.Config().Denom) + require.NoError(t, err) + + secondHopEscrowBalance, err := chainB.GetBalance(ctx, secondHopEscrowAccount, firstHopIBCDenom) + require.NoError(t, err) + + require.Equal(t, int64(0), firstHopEscrowBalance) + require.Equal(t, int64(0), secondHopEscrowBalance) + }) + + t.Run("multi-hop ack error refund", func(t *testing.T) { + // Send a malformed packet with invalid receiver address from Chain A->Chain B->Chain C->Chain D + // This should succeed in the first hop and second hop, then fail to make the third hop. + // Funds should be refunded to Chain B and then to Chain A via acknowledgements with errors. + transfer := ibc.WalletAmount{ + Address: userB.FormattedAddress(), + Denom: chainA.Config().Denom, + Amount: transferAmount, + } + + secondHopMetadata := &PacketMetadata{ + Forward: &ForwardMetadata{ + Receiver: "xyz1t8eh66t2w5k67kwurmn5gqhtq6d2ja0vp7jmmq", // malformed receiver address on chain D + Channel: cdChan.ChannelID, + Port: cdChan.PortID, + }, + } + + nextBz, err := json.Marshal(secondHopMetadata) + require.NoError(t, err) + + next := string(nextBz) + + firstHopMetadata := &PacketMetadata{ + Forward: &ForwardMetadata{ + Receiver: userC.FormattedAddress(), + Channel: bcChan.ChannelID, + Port: bcChan.PortID, + Next: &next, + }, + } + + memo, err := json.Marshal(firstHopMetadata) + require.NoError(t, err) + + chainAHeight, err := chainA.Height(ctx) + require.NoError(t, err) + + transferTx, err := chainA.SendIBCTransfer(ctx, abChan.ChannelID, userA.KeyName(), transfer, ibc.TransferOptions{Memo: string(memo)}) + require.NoError(t, err) + _, err = testutil.PollForAck(ctx, chainA, chainAHeight, chainAHeight+30, transferTx.Packet) + require.NoError(t, err) + err = testutil.WaitForBlocks(ctx, 1, chainA) + require.NoError(t, err) + + // assert balances for user controlled wallets + chainDBalance, err := chainD.GetBalance(ctx, userD.FormattedAddress(), thirdHopIBCDenom) + require.NoError(t, err) + + chainCBalance, err := chainC.GetBalance(ctx, userC.FormattedAddress(), secondHopIBCDenom) + require.NoError(t, err) + + chainBBalance, err := chainB.GetBalance(ctx, userB.FormattedAddress(), firstHopIBCDenom) + require.NoError(t, err) + + chainABalance, err := chainA.GetBalance(ctx, userA.FormattedAddress(), chainA.Config().Denom) + require.NoError(t, err) + + require.Equal(t, userFunds, chainABalance) + require.Equal(t, int64(0), chainBBalance) + require.Equal(t, int64(0), chainCBalance) + require.Equal(t, int64(0), chainDBalance) + + // assert balances for IBC escrow accounts + firstHopEscrowBalance, err := chainA.GetBalance(ctx, firstHopEscrowAccount, chainA.Config().Denom) + require.NoError(t, err) + + secondHopEscrowBalance, err := chainB.GetBalance(ctx, secondHopEscrowAccount, firstHopIBCDenom) + require.NoError(t, err) + + thirdHopEscrowBalance, err := chainC.GetBalance(ctx, thirdHopEscrowAccount, secondHopIBCDenom) + require.NoError(t, err) + + require.Equal(t, int64(0), firstHopEscrowBalance) + require.Equal(t, int64(0), secondHopEscrowBalance) + require.Equal(t, int64(0), thirdHopEscrowBalance) + }) + + t.Run("multi-hop through native chain ack error refund", func(t *testing.T) { + // send normal IBC transfer from B->A to get funds in IBC denom, then do multihop A->B(native)->C->D + // this lets us test the burn from escrow account on chain C and the escrow to escrow transfer on chain B. + + // Compose the prefixed denoms and ibc denom for asserting balances + baDenom := transfertypes.GetPrefixedDenom(abChan.PortID, abChan.ChannelID, chainB.Config().Denom) + bcDenom := transfertypes.GetPrefixedDenom(cbChan.PortID, cbChan.ChannelID, chainB.Config().Denom) + cdDenom := transfertypes.GetPrefixedDenom(dcChan.PortID, dcChan.ChannelID, bcDenom) + + baDenomTrace := transfertypes.ParseDenomTrace(baDenom) + bcDenomTrace := transfertypes.ParseDenomTrace(bcDenom) + cdDenomTrace := transfertypes.ParseDenomTrace(cdDenom) + + baIBCDenom := baDenomTrace.IBCDenom() + bcIBCDenom := bcDenomTrace.IBCDenom() + cdIBCDenom := cdDenomTrace.IBCDenom() + + transfer := ibc.WalletAmount{ + Address: userA.FormattedAddress(), + Denom: chainB.Config().Denom, + Amount: transferAmount, + } + + chainBHeight, err := chainB.Height(ctx) + require.NoError(t, err) + + transferTx, err := chainB.SendIBCTransfer(ctx, baChan.ChannelID, userB.KeyName(), transfer, ibc.TransferOptions{}) + require.NoError(t, err) + _, err = testutil.PollForAck(ctx, chainB, chainBHeight, chainBHeight+10, transferTx.Packet) + require.NoError(t, err) + err = testutil.WaitForBlocks(ctx, 1, chainB) + require.NoError(t, err) + + // assert balance for user controlled wallet + chainABalance, err := chainA.GetBalance(ctx, userA.FormattedAddress(), baIBCDenom) + require.NoError(t, err) + + baEscrowBalance, err := chainB.GetBalance( + ctx, + sdk.MustBech32ifyAddressBytes(chainB.Config().Bech32Prefix, transfertypes.GetEscrowAddress(baChan.PortID, baChan.ChannelID)), + chainB.Config().Denom, + ) + require.NoError(t, err) + + require.Equal(t, transferAmount, chainABalance) + require.Equal(t, transferAmount, baEscrowBalance) + + // Send a malformed packet with invalid receiver address from Chain A->Chain B->Chain C->Chain D + // This should succeed in the first hop and second hop, then fail to make the third hop. + // Funds should be refunded to Chain B and then to Chain A via acknowledgements with errors. + transfer = ibc.WalletAmount{ + Address: userB.FormattedAddress(), + Denom: baIBCDenom, + Amount: transferAmount, + } + + secondHopMetadata := &PacketMetadata{ + Forward: &ForwardMetadata{ + Receiver: "xyz1t8eh66t2w5k67kwurmn5gqhtq6d2ja0vp7jmmq", // malformed receiver address on chain D + Channel: cdChan.ChannelID, + Port: cdChan.PortID, + }, + } + + nextBz, err := json.Marshal(secondHopMetadata) + require.NoError(t, err) + + next := string(nextBz) + + firstHopMetadata := &PacketMetadata{ + Forward: &ForwardMetadata{ + Receiver: userC.FormattedAddress(), + Channel: bcChan.ChannelID, + Port: bcChan.PortID, + Next: &next, + }, + } + + memo, err := json.Marshal(firstHopMetadata) + require.NoError(t, err) + + chainAHeight, err := chainA.Height(ctx) + require.NoError(t, err) + + transferTx, err = chainA.SendIBCTransfer(ctx, abChan.ChannelID, userA.KeyName(), transfer, ibc.TransferOptions{Memo: string(memo)}) + require.NoError(t, err) + _, err = testutil.PollForAck(ctx, chainA, chainAHeight, chainAHeight+30, transferTx.Packet) + require.NoError(t, err) + err = testutil.WaitForBlocks(ctx, 1, chainA) + require.NoError(t, err) + + // assert balances for user controlled wallets + chainDBalance, err := chainD.GetBalance(ctx, userD.FormattedAddress(), cdIBCDenom) + require.NoError(t, err) + + chainCBalance, err := chainC.GetBalance(ctx, userC.FormattedAddress(), bcIBCDenom) + require.NoError(t, err) + + chainBBalance, err := chainB.GetBalance(ctx, userB.FormattedAddress(), chainB.Config().Denom) + require.NoError(t, err) + + chainABalance, err = chainA.GetBalance(ctx, userA.FormattedAddress(), baIBCDenom) + require.NoError(t, err) + + require.Equal(t, transferAmount, chainABalance) + require.Equal(t, userFunds-transferAmount, chainBBalance) + require.Equal(t, int64(0), chainCBalance) + require.Equal(t, int64(0), chainDBalance) + + // assert balances for IBC escrow accounts + cdEscrowBalance, err := chainC.GetBalance( + ctx, + sdk.MustBech32ifyAddressBytes(chainC.Config().Bech32Prefix, transfertypes.GetEscrowAddress(cdChan.PortID, cdChan.ChannelID)), + bcIBCDenom, + ) + require.NoError(t, err) + + bcEscrowBalance, err := chainB.GetBalance( + ctx, + sdk.MustBech32ifyAddressBytes(chainB.Config().Bech32Prefix, transfertypes.GetEscrowAddress(bcChan.PortID, bcChan.ChannelID)), + chainB.Config().Denom, + ) + require.NoError(t, err) + + baEscrowBalance, err = chainB.GetBalance( + ctx, + sdk.MustBech32ifyAddressBytes(chainB.Config().Bech32Prefix, transfertypes.GetEscrowAddress(baChan.PortID, baChan.ChannelID)), + chainB.Config().Denom, + ) + require.NoError(t, err) + + require.Equal(t, transferAmount, baEscrowBalance) + require.Equal(t, int64(0), bcEscrowBalance) + require.Equal(t, int64(0), cdEscrowBalance) + }) +} diff --git a/interchaintest/setup.go b/interchaintest/setup.go new file mode 100644 index 0000000..4fac950 --- /dev/null +++ b/interchaintest/setup.go @@ -0,0 +1,150 @@ +package interchaintest + +import ( + "context" + "fmt" + "testing" + + wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" + ibclocalhost "github.com/cosmos/ibc-go/v7/modules/light-clients/09-localhost" + + "github.com/docker/docker/client" + + interchaintest "github.com/strangelove-ventures/interchaintest/v7" + "github.com/strangelove-ventures/interchaintest/v7/chain/cosmos" + "github.com/strangelove-ventures/interchaintest/v7/ibc" + "github.com/strangelove-ventures/interchaintest/v7/testreporter" + + "github.com/stretchr/testify/require" + "go.uber.org/zap/zaptest" + + testutil "github.com/cosmos/cosmos-sdk/types/module/testutil" +) + +var ( + VotingPeriod = "15s" + MaxDepositPeriod = "10s" + BondDenom = "uterp" + FeeDenom = "uthiol" + + TerpE2ERepo = "ghcr.io/terpnetwork/terp-core-e2e" + TerpMainRepo = "ghcr.io/terpnetwork/terp-core" + + IBCRelayerImage = "ghcr.io/cosmos/relayer" + IBCRelayerVersion = "justin-localhost-ibc" + + terpRepo, terpVersion = GetDockerImageInfo() + + TerpImage = ibc.DockerImage{ + Repository: terpRepo, + Version: terpVersion, + UidGid: "1025:1025", + } + + // SDK v47 Genesis + defaultGenesisKV = []cosmos.GenesisKV{ + { + Key: "app_state.gov.params.voting_period", + Value: VotingPeriod, + }, + { + Key: "app_state.gov.params.max_deposit_period", + Value: MaxDepositPeriod, + }, + { + Key: "app_state.gov.params.min_deposit.0.denom", + Value: Denom, + }, + } + + terpConfig = ibc.ChainConfig{ + Type: "cosmos", + Name: "terpnetwork", + ChainID: "terp-2", + Images: []ibc.DockerImage{TerpImage}, + Bin: "terpd", + Bech32Prefix: "terp", + Denom: BondDenom, + FeeDenom: FeeDenom, + CoinType: "118", + GasPrices: fmt.Sprintf("0%s", FeeDenom), + GasAdjustment: 2.0, + TrustingPeriod: "112h", + NoHostMount: false, + ConfigFileOverrides: nil, + EncodingConfig: terpEncoding(), + UsingNewGenesisCommand: true, + ModifyGenesis: cosmos.ModifyGenesis(defaultGenesisKV), + } + + genesisWalletAmount = int64(10_000_000) +) + +// terpEncoding registers the Juno specific module codecs so that the associated types and msgs +// will be supported when writing to the blocksdb sqlite database. +func terpEncoding() *testutil.TestEncodingConfig { + cfg := cosmos.DefaultEncoding() + + // register custom types + ibclocalhost.RegisterInterfaces(cfg.InterfaceRegistry) + wasmtypes.RegisterInterfaces(cfg.InterfaceRegistry) + + //github.com/cosmos/cosmos-sdk/types/module/testutil + + return &cfg +} + +// This allows for us to test +func FundSpecificUsers() { + +} + +// Base chain, no relaying off this branch (or juno:local if no branch is provided.) +func CreateThisBranchChain(t *testing.T, numVals, numFull int) []ibc.Chain { + // Create chain factory with Juno on this current branch + + cf := interchaintest.NewBuiltinChainFactory(zaptest.NewLogger(t), []*interchaintest.ChainSpec{ + { + Name: "terp", + ChainName: "terpnetwork", + Version: terpVersion, + ChainConfig: terpConfig, + NumValidators: &numVals, + NumFullNodes: &numFull, + }, + }) + + // Get chains from the chain factory + chains, err := cf.Chains(t.Name()) + require.NoError(t, err) + + // chain := chains[0].(*cosmos.CosmosChain) + return chains +} + +func BuildInitialChain(t *testing.T, chains []ibc.Chain) (*interchaintest.Interchain, context.Context, *client.Client, string) { + // Create a new Interchain object which describes the chains, relayers, and IBC connections we want to use + ic := interchaintest.NewInterchain() + + for _, chain := range chains { + ic = ic.AddChain(chain) + } + + rep := testreporter.NewNopReporter() + eRep := rep.RelayerExecReporter(t) + + ctx := context.Background() + client, network := interchaintest.DockerSetup(t) + + err := ic.Build(ctx, eRep, interchaintest.InterchainBuildOptions{ + TestName: t.Name(), + Client: client, + NetworkID: network, + SkipPathCreation: true, + // This can be used to write to the block database which will index all block data e.g. txs, msgs, events, etc. + // BlockDatabaseFile: interchaintest.DefaultBlockDatabaseFilepath(), + }) + require.NoError(t, err) + + return ic, ctx, client, network +} diff --git a/osmoutils/ibc.go b/osmoutils/ibc.go new file mode 100644 index 0000000..56e97ef --- /dev/null +++ b/osmoutils/ibc.go @@ -0,0 +1,72 @@ +package osmoutils + +import ( + "encoding/json" + + transfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" + channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" + ibcexported "github.com/cosmos/ibc-go/v7/modules/core/exported" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// NewEmitErrorAcknowledgement creates a new error acknowledgement after having emitted an event with the +// details of the error. +func NewEmitErrorAcknowledgement(ctx sdk.Context, err error, errorContexts ...string) channeltypes.Acknowledgement { + attributes := make([]sdk.Attribute, len(errorContexts)+1) + attributes[0] = sdk.NewAttribute("error", err.Error()) + for i, s := range errorContexts { + attributes[i+1] = sdk.NewAttribute("error-context", s) + } + + ctx.EventManager().EmitEvents(sdk.Events{ + sdk.NewEvent( + "ibc-acknowledgement-error", + attributes..., + ), + }) + + return channeltypes.NewErrorAcknowledgement(err) +} + +// MustExtractDenomFromPacketOnRecv takes a packet with a valid ICS20 token data in the Data field and returns the +// denom as represented in the local chain. +// If the data cannot be unmarshalled this function will panic +func MustExtractDenomFromPacketOnRecv(packet ibcexported.PacketI) string { + var data transfertypes.FungibleTokenPacketData + if err := json.Unmarshal(packet.GetData(), &data); err != nil { + panic("unable to unmarshal ICS20 packet data") + } + + var denom string + if transfertypes.ReceiverChainIsSource(packet.GetSourcePort(), packet.GetSourceChannel(), data.Denom) { + // remove prefix added by sender chain + voucherPrefix := transfertypes.GetDenomPrefix(packet.GetSourcePort(), packet.GetSourceChannel()) + + unprefixedDenom := data.Denom[len(voucherPrefix):] + + // coin denomination used in sending from the escrow address + denom = unprefixedDenom + + // The denomination used to send the coins is either the native denom or the hash of the path + // if the denomination is not native. + denomTrace := transfertypes.ParseDenomTrace(unprefixedDenom) + if denomTrace.Path != "" { + denom = denomTrace.IBCDenom() + } + } else { + prefixedDenom := transfertypes.GetDenomPrefix(packet.GetDestPort(), packet.GetDestChannel()) + data.Denom + denom = transfertypes.ParseDenomTrace(prefixedDenom).IBCDenom() + } + return denom +} + +// IsAckError checks an IBC acknowledgement to see if it's an error. +// This is a replacement for ack.Success() which is currently not working on some circumstances +func IsAckError(acknowledgement []byte) bool { + var ackErr channeltypes.Acknowledgement_Error + if err := json.Unmarshal(acknowledgement, &ackErr); err == nil && len(ackErr.Error) > 0 { + return true + } + return false +} diff --git a/proto/buf.gen.gogo.yml b/proto/buf.gen.gogo.yml deleted file mode 100644 index 855ea25..0000000 --- a/proto/buf.gen.gogo.yml +++ /dev/null @@ -1,8 +0,0 @@ -version: v1 -plugins: - - name: gocosmos - out: .. - opt: plugins=grpc,Mgoogle/protobuf/any.proto=github.com/cosmos/cosmos-sdk/codec/types - - name: grpc-gateway - out: .. - opt: logtostderr=true,allow_colon_final_segments=true \ No newline at end of file diff --git a/proto/cosmwasm/tokenfactory/v1beta1/authority_metadata.proto b/proto/cosmwasm/tokenfactory/v1beta1/authority_metadata.proto deleted file mode 100644 index 3d27b3d..0000000 --- a/proto/cosmwasm/tokenfactory/v1beta1/authority_metadata.proto +++ /dev/null @@ -1,17 +0,0 @@ -syntax = "proto3"; -package osmosis.tokenfactory.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "gogoproto/gogo.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 deleted file mode 100644 index 8b123c5..0000000 --- a/proto/cosmwasm/tokenfactory/v1beta1/genesis.proto +++ /dev/null @@ -1,32 +0,0 @@ -syntax = "proto3"; -package osmosis.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 deleted file mode 100644 index 2871b8b..0000000 --- a/proto/cosmwasm/tokenfactory/v1beta1/params.proto +++ /dev/null @@ -1,18 +0,0 @@ -syntax = "proto3"; -package osmosis.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 deleted file mode 100644 index d7e4c42..0000000 --- a/proto/cosmwasm/tokenfactory/v1beta1/query.proto +++ /dev/null @@ -1,71 +0,0 @@ -syntax = "proto3"; -package osmosis.tokenfactory.v1beta1; - -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "cosmos/base/query/v1beta1/pagination.proto"; -import "cosmwasm/tokenfactory/v1beta1/authority_metadata.proto"; -import "cosmwasm/tokenfactory/v1beta1/params.proto"; - -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 = "/osmosis/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 = - "/osmosis/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 = - "/osmosis/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 deleted file mode 100644 index 365bf5f..0000000 --- a/proto/cosmwasm/tokenfactory/v1beta1/tx.proto +++ /dev/null @@ -1,120 +0,0 @@ -syntax = "proto3"; -package osmosis.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 deleted file mode 100644 index ce10a3d..0000000 --- a/proto/cosmwasm/wasm/v1/authz.proto +++ /dev/null @@ -1,131 +0,0 @@ -syntax = "proto3"; -package cosmwasm.wasm.v1; - -import "gogoproto/gogo.proto"; -import "cosmos_proto/cosmos.proto"; -import "cosmos/base/v1beta1/coin.proto"; -import "google/protobuf/any.proto"; -import "amino/amino.proto"; - -option go_package = "github.com/terpnetwork/terp-core/x/wasm/types"; -option (gogoproto.goproto_getters_all) = false; - -// ContractExecutionAuthorization defines authorization for wasm execute. -// Since: wasmd 0.30 -message ContractExecutionAuthorization { - option (amino.name) = "wasm/ContractExecutionAuthorization"; - option (cosmos_proto.implements_interface) = - "cosmos.authz.v1beta1.Authorization"; - - // Grants for contract executions - repeated ContractGrant grants = 1 - [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; -} - -// ContractMigrationAuthorization defines authorization for wasm contract -// migration. Since: wasmd 0.30 -message ContractMigrationAuthorization { - option (amino.name) = "wasm/ContractMigrationAuthorization"; - option (cosmos_proto.implements_interface) = - "cosmos.authz.v1beta1.Authorization"; - - // Grants for contract migrations - repeated ContractGrant grants = 1 - [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; -} - -// ContractGrant a granted permission for a single contract -// Since: wasmd 0.30 -message ContractGrant { - // Contract is the bech32 address of the smart contract - string contract = 1; - - // Limit defines execution limits that are enforced and updated when the grant - // is applied. When the limit lapsed the grant is removed. - google.protobuf.Any limit = 2 [ (cosmos_proto.accepts_interface) = - "cosmwasm.wasm.v1.ContractAuthzLimitX" ]; - - // Filter define more fine-grained control on the message payload passed - // to the contract in the operation. When no filter applies on execution, the - // operation is prohibited. - google.protobuf.Any filter = 3 - [ (cosmos_proto.accepts_interface) = - "cosmwasm.wasm.v1.ContractAuthzFilterX" ]; -} - -// MaxCallsLimit limited number of calls to the contract. No funds transferable. -// Since: wasmd 0.30 -message MaxCallsLimit { - option (amino.name) = "wasm/MaxCallsLimit"; - option (cosmos_proto.implements_interface) = - "cosmwasm.wasm.v1.ContractAuthzLimitX"; - - // Remaining number that is decremented on each execution - uint64 remaining = 1; -} - -// MaxFundsLimit defines the maximal amounts that can be sent to the contract. -// Since: wasmd 0.30 -message MaxFundsLimit { - option (amino.name) = "wasm/MaxFundsLimit"; - option (cosmos_proto.implements_interface) = - "cosmwasm.wasm.v1.ContractAuthzLimitX"; - - // Amounts is the maximal amount of tokens transferable to the contract. - repeated cosmos.base.v1beta1.Coin amounts = 1 [ - (gogoproto.nullable) = false, - (amino.dont_omitempty) = true, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} - -// CombinedLimit defines the maximal amounts that can be sent to a contract and -// the maximal number of calls executable. Both need to remain >0 to be valid. -// Since: wasmd 0.30 -message CombinedLimit { - option (amino.name) = "wasm/CombinedLimit"; - option (cosmos_proto.implements_interface) = - "cosmwasm.wasm.v1.ContractAuthzLimitX"; - - // Remaining number that is decremented on each execution - uint64 calls_remaining = 1; - // Amounts is the maximal amount of tokens transferable to the contract. - repeated cosmos.base.v1beta1.Coin amounts = 2 [ - (gogoproto.nullable) = false, - (amino.dont_omitempty) = true, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} - -// AllowAllMessagesFilter is a wildcard to allow any type of contract payload -// message. -// Since: wasmd 0.30 -message AllowAllMessagesFilter { - option (amino.name) = "wasm/AllowAllMessagesFilter"; - option (cosmos_proto.implements_interface) = - "cosmwasm.wasm.v1.ContractAuthzFilterX"; -} - -// AcceptedMessageKeysFilter accept only the specific contract message keys in -// the json object to be executed. -// Since: wasmd 0.30 -message AcceptedMessageKeysFilter { - option (amino.name) = "wasm/AcceptedMessageKeysFilter"; - option (cosmos_proto.implements_interface) = - "cosmwasm.wasm.v1.ContractAuthzFilterX"; - - // Messages is the list of unique keys - repeated string keys = 1; -} - -// AcceptedMessagesFilter accept only the specific raw contract messages to be -// executed. -// Since: wasmd 0.30 -message AcceptedMessagesFilter { - option (amino.name) = "wasm/AcceptedMessagesFilter"; - option (cosmos_proto.implements_interface) = - "cosmwasm.wasm.v1.ContractAuthzFilterX"; - - // Messages is the list of raw contract messages - repeated bytes messages = 1 [ (gogoproto.casttype) = "RawContractMessage" ]; -} \ No newline at end of file diff --git a/proto/cosmwasm/wasm/v1/genesis.proto b/proto/cosmwasm/wasm/v1/genesis.proto deleted file mode 100644 index 898ccee..0000000 --- a/proto/cosmwasm/wasm/v1/genesis.proto +++ /dev/null @@ -1,56 +0,0 @@ -syntax = "proto3"; -package cosmwasm.wasm.v1; - -import "gogoproto/gogo.proto"; -import "cosmwasm/wasm/v1/types.proto"; -import "amino/amino.proto"; - -option go_package = "github.com/terpnetwork/terp-core/x/wasm/types"; - -// GenesisState - genesis state of x/wasm -message GenesisState { - Params params = 1 - [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; - repeated Code codes = 2 [ - (gogoproto.nullable) = false, - (amino.dont_omitempty) = true, - (gogoproto.jsontag) = "codes,omitempty" - ]; - repeated Contract contracts = 3 [ - (gogoproto.nullable) = false, - (amino.dont_omitempty) = true, - (gogoproto.jsontag) = "contracts,omitempty" - ]; - repeated Sequence sequences = 4 [ - (gogoproto.nullable) = false, - (amino.dont_omitempty) = true, - (gogoproto.jsontag) = "sequences,omitempty" - ]; -} - -// Code struct encompasses CodeInfo and CodeBytes -message Code { - uint64 code_id = 1 [ (gogoproto.customname) = "CodeID" ]; - CodeInfo code_info = 2 - [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; - bytes code_bytes = 3; - // Pinned to wasmvm cache - bool pinned = 4; -} - -// Contract struct encompasses ContractAddress, ContractInfo, and ContractState -message Contract { - string contract_address = 1; - ContractInfo contract_info = 2 - [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; - repeated Model contract_state = 3 - [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; - repeated ContractCodeHistoryEntry contract_code_history = 4 - [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; -} - -// Sequence key and value of an id generation counter -message Sequence { - bytes id_key = 1 [ (gogoproto.customname) = "IDKey" ]; - uint64 value = 2; -} \ No newline at end of file diff --git a/proto/cosmwasm/wasm/v1/ibc.proto b/proto/cosmwasm/wasm/v1/ibc.proto deleted file mode 100644 index 196387b..0000000 --- a/proto/cosmwasm/wasm/v1/ibc.proto +++ /dev/null @@ -1,37 +0,0 @@ -syntax = "proto3"; -package cosmwasm.wasm.v1; - -import "gogoproto/gogo.proto"; - -option go_package = "github.com/terpnetwork/terp-core/x/wasm/types"; -option (gogoproto.goproto_getters_all) = false; - -// MsgIBCSend -message MsgIBCSend { - // the channel by which the packet will be sent - string channel = 2 [ (gogoproto.moretags) = "yaml:\"source_channel\"" ]; - - // Timeout height relative to the current block height. - // The timeout is disabled when set to 0. - uint64 timeout_height = 4 - [ (gogoproto.moretags) = "yaml:\"timeout_height\"" ]; - // Timeout timestamp (in nanoseconds) relative to the current block timestamp. - // The timeout is disabled when set to 0. - uint64 timeout_timestamp = 5 - [ (gogoproto.moretags) = "yaml:\"timeout_timestamp\"" ]; - - // Data is the payload to transfer. We must not make assumption what format or - // content is in here. - bytes data = 6; -} - -// MsgIBCSendResponse -message MsgIBCSendResponse { - // Sequence number of the IBC packet sent - uint64 sequence = 1; -} - -// MsgIBCCloseChannel port and channel need to be owned by the contract -message MsgIBCCloseChannel { - string channel = 2 [ (gogoproto.moretags) = "yaml:\"source_channel\"" ]; -} \ No newline at end of file diff --git a/proto/cosmwasm/wasm/v1/proposal.proto b/proto/cosmwasm/wasm/v1/proposal.proto deleted file mode 100644 index f411345..0000000 --- a/proto/cosmwasm/wasm/v1/proposal.proto +++ /dev/null @@ -1,329 +0,0 @@ -syntax = "proto3"; -package cosmwasm.wasm.v1; - -import "gogoproto/gogo.proto"; -import "cosmos_proto/cosmos.proto"; -import "cosmos/base/v1beta1/coin.proto"; -import "cosmwasm/wasm/v1/types.proto"; -import "amino/amino.proto"; - -option go_package = "github.com/terpnetwork/terp-core/x/wasm/types"; -option (gogoproto.goproto_stringer_all) = false; -option (gogoproto.goproto_getters_all) = false; -option (gogoproto.equal_all) = true; - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit StoreCodeProposal. To submit WASM code to the system, -// a simple MsgStoreCode can be invoked from the x/gov module via -// a v1 governance proposal. -message StoreCodeProposal { - option deprecated = true; - option (amino.name) = "wasm/StoreCodeProposal"; - option (cosmos_proto.implements_interface) = "cosmos.gov.v1beta1.Content"; - - // Title is a short summary - string title = 1; - // Description is a human readable text - string description = 2; - // RunAs is the address that is passed to the contract's environment as sender - string run_as = 3; - // WASMByteCode can be raw or gzip compressed - bytes wasm_byte_code = 4 [ (gogoproto.customname) = "WASMByteCode" ]; - // Used in v1beta1 - reserved 5, 6; - // InstantiatePermission to apply on contract creation, optional - AccessConfig instantiate_permission = 7; - // UnpinCode code on upload, optional - bool unpin_code = 8; - // Source is the URL where the code is hosted - string source = 9; - // Builder is the docker image used to build the code deterministically, used - // for smart contract verification - string builder = 10; - // CodeHash is the SHA256 sum of the code outputted by builder, used for smart - // contract verification - bytes code_hash = 11; -} - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit InstantiateContractProposal. To instantiate a contract, -// a simple MsgInstantiateContract can be invoked from the x/gov module via -// a v1 governance proposal. -message InstantiateContractProposal { - option deprecated = true; - option (amino.name) = "wasm/InstantiateContractProposal"; - option (cosmos_proto.implements_interface) = "cosmos.gov.v1beta1.Content"; - - // Title is a short summary - string title = 1; - // Description is a human readable text - string description = 2; - // RunAs is the address that is passed to the contract's environment as sender - string run_as = 3; - // Admin is an optional address that can execute migrations - string admin = 4; - // CodeID is the reference to the stored WASM code - uint64 code_id = 5 [ (gogoproto.customname) = "CodeID" ]; - // Label is optional metadata to be stored with a constract instance. - string label = 6; - // Msg json encoded message to be passed to the contract on instantiation - bytes msg = 7 [ (gogoproto.casttype) = "RawContractMessage" ]; - // Funds coins that are transferred to the contract on instantiation - repeated cosmos.base.v1beta1.Coin funds = 8 [ - (gogoproto.nullable) = false, - (amino.dont_omitempty) = true, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit InstantiateContract2Proposal. To instantiate contract 2, -// a simple MsgInstantiateContract2 can be invoked from the x/gov module via -// a v1 governance proposal. -message InstantiateContract2Proposal { - option deprecated = true; - option (amino.name) = "wasm/InstantiateContract2Proposal"; - option (cosmos_proto.implements_interface) = "cosmos.gov.v1beta1.Content"; - - // Title is a short summary - string title = 1; - // Description is a human readable text - string description = 2; - // RunAs is the address that is passed to the contract's enviroment as sender - string run_as = 3; - // Admin is an optional address that can execute migrations - string admin = 4; - // CodeID is the reference to the stored WASM code - uint64 code_id = 5 [ (gogoproto.customname) = "CodeID" ]; - // Label is optional metadata to be stored with a constract instance. - string label = 6; - // Msg json encode message to be passed to the contract on instantiation - bytes msg = 7 [ (gogoproto.casttype) = "RawContractMessage" ]; - // Funds coins that are transferred to the contract on instantiation - repeated cosmos.base.v1beta1.Coin funds = 8 [ - (gogoproto.nullable) = false, - (amino.dont_omitempty) = true, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; - // Salt is an arbitrary value provided by the sender. Size can be 1 to 64. - bytes salt = 9; - // FixMsg include the msg value into the hash for the predictable address. - // Default is false - bool fix_msg = 10; -} - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit MigrateContractProposal. To migrate a contract, -// a simple MsgMigrateContract can be invoked from the x/gov module via -// a v1 governance proposal. -message MigrateContractProposal { - option deprecated = true; - option (amino.name) = "wasm/MigrateContractProposal"; - option (cosmos_proto.implements_interface) = "cosmos.gov.v1beta1.Content"; - - // Title is a short summary - string title = 1; - // Description is a human readable text - string description = 2; - // Note: skipping 3 as this was previously used for unneeded run_as - - // Contract is the address of the smart contract - string contract = 4; - // CodeID references the new WASM code - uint64 code_id = 5 [ (gogoproto.customname) = "CodeID" ]; - // Msg json encoded message to be passed to the contract on migration - bytes msg = 6 [ (gogoproto.casttype) = "RawContractMessage" ]; -} - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit SudoContractProposal. To call sudo on a contract, -// a simple MsgSudoContract can be invoked from the x/gov module via -// a v1 governance proposal. -message SudoContractProposal { - option deprecated = true; - option (amino.name) = "wasm/SudoContractProposal"; - option (cosmos_proto.implements_interface) = "cosmos.gov.v1beta1.Content"; - - // Title is a short summary - string title = 1; - // Description is a human readable text - string description = 2; - // Contract is the address of the smart contract - string contract = 3; - // Msg json encoded message to be passed to the contract as sudo - bytes msg = 4 [ (gogoproto.casttype) = "RawContractMessage" ]; -} - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit ExecuteContractProposal. To call execute on a contract, -// a simple MsgExecuteContract can be invoked from the x/gov module via -// a v1 governance proposal. -message ExecuteContractProposal { - option deprecated = true; - option (amino.name) = "wasm/ExecuteContractProposal"; - option (cosmos_proto.implements_interface) = "cosmos.gov.v1beta1.Content"; - - // Title is a short summary - string title = 1; - // Description is a human readable text - string description = 2; - // RunAs is the address that is passed to the contract's environment as sender - string run_as = 3; - // Contract is the address of the smart contract - string contract = 4; - // Msg json encoded message to be passed to the contract as execute - bytes msg = 5 [ (gogoproto.casttype) = "RawContractMessage" ]; - // Funds coins that are transferred to the contract on instantiation - repeated cosmos.base.v1beta1.Coin funds = 6 [ - (gogoproto.nullable) = false, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit UpdateAdminProposal. To set an admin for a contract, -// a simple MsgUpdateAdmin can be invoked from the x/gov module via -// a v1 governance proposal. -message UpdateAdminProposal { - option deprecated = true; - option (amino.name) = "wasm/UpdateAdminProposal"; - option (cosmos_proto.implements_interface) = "cosmos.gov.v1beta1.Content"; - - // Title is a short summary - string title = 1; - // Description is a human readable text - string description = 2; - // NewAdmin address to be set - string new_admin = 3 [ (gogoproto.moretags) = "yaml:\"new_admin\"" ]; - // Contract is the address of the smart contract - string contract = 4; -} - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit ClearAdminProposal. To clear the admin of a contract, -// a simple MsgClearAdmin can be invoked from the x/gov module via -// a v1 governance proposal. -message ClearAdminProposal { - option deprecated = true; - option (amino.name) = "wasm/ClearAdminProposal"; - option (cosmos_proto.implements_interface) = "cosmos.gov.v1beta1.Content"; - - // Title is a short summary - string title = 1; - // Description is a human readable text - string description = 2; - // Contract is the address of the smart contract - string contract = 3; -} - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit PinCodesProposal. To pin a set of code ids in the wasmvm -// cache, a simple MsgPinCodes can be invoked from the x/gov module via -// a v1 governance proposal. -message PinCodesProposal { - option deprecated = true; - option (amino.name) = "wasm/PinCodesProposal"; - option (cosmos_proto.implements_interface) = "cosmos.gov.v1beta1.Content"; - - // Title is a short summary - string title = 1 [ (gogoproto.moretags) = "yaml:\"title\"" ]; - // Description is a human readable text - string description = 2 [ (gogoproto.moretags) = "yaml:\"description\"" ]; - // CodeIDs references the new WASM codes - repeated uint64 code_ids = 3 [ - (gogoproto.customname) = "CodeIDs", - (gogoproto.moretags) = "yaml:\"code_ids\"" - ]; -} - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit UnpinCodesProposal. To unpin a set of code ids in the wasmvm -// cache, a simple MsgUnpinCodes can be invoked from the x/gov module via -// a v1 governance proposal. -message UnpinCodesProposal { - option deprecated = true; - option (amino.name) = "wasm/UnpinCodesProposal"; - option (cosmos_proto.implements_interface) = "cosmos.gov.v1beta1.Content"; - - // Title is a short summary - string title = 1 [ (gogoproto.moretags) = "yaml:\"title\"" ]; - // Description is a human readable text - string description = 2 [ (gogoproto.moretags) = "yaml:\"description\"" ]; - // CodeIDs references the WASM codes - repeated uint64 code_ids = 3 [ - (gogoproto.customname) = "CodeIDs", - (gogoproto.moretags) = "yaml:\"code_ids\"" - ]; -} - -// AccessConfigUpdate contains the code id and the access config to be -// applied. -message AccessConfigUpdate { - // CodeID is the reference to the stored WASM code to be updated - uint64 code_id = 1 [ (gogoproto.customname) = "CodeID" ]; - // InstantiatePermission to apply to the set of code ids - AccessConfig instantiate_permission = 2 - [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; -} - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit UpdateInstantiateConfigProposal. To update instantiate config -// to a set of code ids, a simple MsgUpdateInstantiateConfig can be invoked from -// the x/gov module via a v1 governance proposal. -message UpdateInstantiateConfigProposal { - option deprecated = true; - option (amino.name) = "wasm/UpdateInstantiateConfigProposal"; - option (cosmos_proto.implements_interface) = "cosmos.gov.v1beta1.Content"; - - // Title is a short summary - string title = 1 [ (gogoproto.moretags) = "yaml:\"title\"" ]; - // Description is a human readable text - string description = 2 [ (gogoproto.moretags) = "yaml:\"description\"" ]; - // AccessConfigUpdate contains the list of code ids and the access config - // to be applied. - repeated AccessConfigUpdate access_config_updates = 3 - [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; -} - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit StoreAndInstantiateContractProposal. To store and instantiate -// the contract, a simple MsgStoreAndInstantiateContract can be invoked from -// the x/gov module via a v1 governance proposal. -message StoreAndInstantiateContractProposal { - option deprecated = true; - option (amino.name) = "wasm/StoreAndInstantiateContractProposal"; - option (cosmos_proto.implements_interface) = "cosmos.gov.v1beta1.Content"; - - // Title is a short summary - string title = 1; - // Description is a human readable text - string description = 2; - // RunAs is the address that is passed to the contract's environment as sender - string run_as = 3; - // WASMByteCode can be raw or gzip compressed - bytes wasm_byte_code = 4 [ (gogoproto.customname) = "WASMByteCode" ]; - // InstantiatePermission to apply on contract creation, optional - AccessConfig instantiate_permission = 5; - // UnpinCode code on upload, optional - bool unpin_code = 6; - // Admin is an optional address that can execute migrations - string admin = 7; - // Label is optional metadata to be stored with a constract instance. - string label = 8; - // Msg json encoded message to be passed to the contract on instantiation - bytes msg = 9 [ (gogoproto.casttype) = "RawContractMessage" ]; - // Funds coins that are transferred to the contract on instantiation - repeated cosmos.base.v1beta1.Coin funds = 10 [ - (gogoproto.nullable) = false, - (amino.dont_omitempty) = true, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; - // Source is the URL where the code is hosted - string source = 11; - // Builder is the docker image used to build the code deterministically, used - // for smart contract verification - string builder = 12; - // CodeHash is the SHA256 sum of the code outputted by builder, used for smart - // contract verification - bytes code_hash = 13; -} diff --git a/proto/cosmwasm/wasm/v1/query.proto b/proto/cosmwasm/wasm/v1/query.proto deleted file mode 100644 index 5a2039b..0000000 --- a/proto/cosmwasm/wasm/v1/query.proto +++ /dev/null @@ -1,268 +0,0 @@ -syntax = "proto3"; -package cosmwasm.wasm.v1; - -import "gogoproto/gogo.proto"; -import "cosmwasm/wasm/v1/types.proto"; -import "google/api/annotations.proto"; -import "cosmos/base/query/v1beta1/pagination.proto"; -import "amino/amino.proto"; - -option go_package = "github.com/terpnetwork/terp-core/x/wasm/types"; -option (gogoproto.goproto_getters_all) = false; -option (gogoproto.equal_all) = false; - -// Query provides defines the gRPC querier service -service Query { - // ContractInfo gets the contract meta data - rpc ContractInfo(QueryContractInfoRequest) - returns (QueryContractInfoResponse) { - option (google.api.http).get = "/cosmwasm/wasm/v1/contract/{address}"; - } - // ContractHistory gets the contract code history - rpc ContractHistory(QueryContractHistoryRequest) - returns (QueryContractHistoryResponse) { - option (google.api.http).get = - "/cosmwasm/wasm/v1/contract/{address}/history"; - } - // ContractsByCode lists all smart contracts for a code id - rpc ContractsByCode(QueryContractsByCodeRequest) - returns (QueryContractsByCodeResponse) { - option (google.api.http).get = "/cosmwasm/wasm/v1/code/{code_id}/contracts"; - } - // AllContractState gets all raw store data for a single contract - rpc AllContractState(QueryAllContractStateRequest) - returns (QueryAllContractStateResponse) { - option (google.api.http).get = "/cosmwasm/wasm/v1/contract/{address}/state"; - } - // RawContractState gets single key from the raw store data of a contract - rpc RawContractState(QueryRawContractStateRequest) - returns (QueryRawContractStateResponse) { - option (google.api.http).get = - "/cosmwasm/wasm/v1/contract/{address}/raw/{query_data}"; - } - // SmartContractState get smart query result from the contract - rpc SmartContractState(QuerySmartContractStateRequest) - returns (QuerySmartContractStateResponse) { - option (google.api.http).get = - "/cosmwasm/wasm/v1/contract/{address}/smart/{query_data}"; - } - // Code gets the binary code and metadata for a singe wasm code - rpc Code(QueryCodeRequest) returns (QueryCodeResponse) { - option (google.api.http).get = "/cosmwasm/wasm/v1/code/{code_id}"; - } - // Codes gets the metadata for all stored wasm codes - rpc Codes(QueryCodesRequest) returns (QueryCodesResponse) { - option (google.api.http).get = "/cosmwasm/wasm/v1/code"; - } - - // PinnedCodes gets the pinned code ids - rpc PinnedCodes(QueryPinnedCodesRequest) returns (QueryPinnedCodesResponse) { - option (google.api.http).get = "/cosmwasm/wasm/v1/codes/pinned"; - } - - // Params gets the module params - rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { - option (google.api.http).get = "/cosmwasm/wasm/v1/codes/params"; - } - - // ContractsByCreator gets the contracts by creator - rpc ContractsByCreator(QueryContractsByCreatorRequest) - returns (QueryContractsByCreatorResponse) { - option (google.api.http).get = - "/cosmwasm/wasm/v1/contracts/creator/{creator_address}"; - } -} - -// QueryContractInfoRequest is the request type for the Query/ContractInfo RPC -// method -message QueryContractInfoRequest { - // address is the address of the contract to query - string address = 1; -} -// QueryContractInfoResponse is the response type for the Query/ContractInfo RPC -// method -message QueryContractInfoResponse { - option (gogoproto.equal) = true; - - // address is the address of the contract - string address = 1; - ContractInfo contract_info = 2 [ - (gogoproto.embed) = true, - (gogoproto.nullable) = false, - (amino.dont_omitempty) = true, - (gogoproto.jsontag) = "" - ]; -} - -// QueryContractHistoryRequest is the request type for the Query/ContractHistory -// RPC method -message QueryContractHistoryRequest { - // address is the address of the contract to query - string address = 1; - // pagination defines an optional pagination for the request. - cosmos.base.query.v1beta1.PageRequest pagination = 2; -} - -// QueryContractHistoryResponse is the response type for the -// Query/ContractHistory RPC method -message QueryContractHistoryResponse { - repeated ContractCodeHistoryEntry entries = 1 - [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; - // pagination defines the pagination in the response. - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} - -// QueryContractsByCodeRequest is the request type for the Query/ContractsByCode -// RPC method -message QueryContractsByCodeRequest { - uint64 code_id = 1; // grpc-gateway_out does not support Go style CodID - // pagination defines an optional pagination for the request. - cosmos.base.query.v1beta1.PageRequest pagination = 2; -} - -// QueryContractsByCodeResponse is the response type for the -// Query/ContractsByCode RPC method -message QueryContractsByCodeResponse { - // contracts are a set of contract addresses - repeated string contracts = 1; - - // pagination defines the pagination in the response. - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} - -// QueryAllContractStateRequest is the request type for the -// Query/AllContractState RPC method -message QueryAllContractStateRequest { - // address is the address of the contract - string address = 1; - // pagination defines an optional pagination for the request. - cosmos.base.query.v1beta1.PageRequest pagination = 2; -} - -// QueryAllContractStateResponse is the response type for the -// Query/AllContractState RPC method -message QueryAllContractStateResponse { - repeated Model models = 1 - [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; - // pagination defines the pagination in the response. - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} - -// QueryRawContractStateRequest is the request type for the -// Query/RawContractState RPC method -message QueryRawContractStateRequest { - // address is the address of the contract - string address = 1; - bytes query_data = 2; -} - -// QueryRawContractStateResponse is the response type for the -// Query/RawContractState RPC method -message QueryRawContractStateResponse { - // Data contains the raw store data - bytes data = 1; -} - -// QuerySmartContractStateRequest is the request type for the -// Query/SmartContractState RPC method -message QuerySmartContractStateRequest { - // address is the address of the contract - string address = 1; - // QueryData contains the query data passed to the contract - bytes query_data = 2 [ (gogoproto.casttype) = "RawContractMessage" ]; -} - -// QuerySmartContractStateResponse is the response type for the -// Query/SmartContractState RPC method -message QuerySmartContractStateResponse { - // Data contains the json data returned from the smart contract - bytes data = 1 [ (gogoproto.casttype) = "RawContractMessage" ]; -} - -// QueryCodeRequest is the request type for the Query/Code RPC method -message QueryCodeRequest { - uint64 code_id = 1; // grpc-gateway_out does not support Go style CodID -} - -// CodeInfoResponse contains code meta data from CodeInfo -message CodeInfoResponse { - option (gogoproto.equal) = true; - - uint64 code_id = 1 [ - (gogoproto.customname) = "CodeID", - (gogoproto.jsontag) = "id" - ]; // id for legacy support - string creator = 2; - bytes data_hash = 3 - [ (gogoproto.casttype) = - "github.com/cometbft/cometbft/libs/bytes.HexBytes" ]; - // Used in v1beta1 - reserved 4, 5; - AccessConfig instantiate_permission = 6 - [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; -} - -// QueryCodeResponse is the response type for the Query/Code RPC method -message QueryCodeResponse { - option (gogoproto.equal) = true; - CodeInfoResponse code_info = 1 - [ (gogoproto.embed) = true, (gogoproto.jsontag) = "" ]; - bytes data = 2 [ (gogoproto.jsontag) = "data" ]; -} - -// QueryCodesRequest is the request type for the Query/Codes RPC method -message QueryCodesRequest { - // pagination defines an optional pagination for the request. - cosmos.base.query.v1beta1.PageRequest pagination = 1; -} - -// QueryCodesResponse is the response type for the Query/Codes RPC method -message QueryCodesResponse { - repeated CodeInfoResponse code_infos = 1 - [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; - // pagination defines the pagination in the response. - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} - -// QueryPinnedCodesRequest is the request type for the Query/PinnedCodes -// RPC method -message QueryPinnedCodesRequest { - // pagination defines an optional pagination for the request. - cosmos.base.query.v1beta1.PageRequest pagination = 2; -} - -// QueryPinnedCodesResponse is the response type for the -// Query/PinnedCodes RPC method -message QueryPinnedCodesResponse { - repeated uint64 code_ids = 1 [ (gogoproto.customname) = "CodeIDs" ]; - // pagination defines the pagination in the response. - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} - -// QueryParamsRequest is the request type for the Query/Params RPC method. -message QueryParamsRequest {} - -// QueryParamsResponse is the response type for the Query/Params RPC method. -message QueryParamsResponse { - // params defines the parameters of the module. - Params params = 1 - [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; -} - -// QueryContractsByCreatorRequest is the request type for the -// Query/ContractsByCreator RPC method. -message QueryContractsByCreatorRequest { - // CreatorAddress is the address of contract creator - string creator_address = 1; - // Pagination defines an optional pagination for the request. - cosmos.base.query.v1beta1.PageRequest pagination = 2; -} - -// QueryContractsByCreatorResponse is the response type for the -// Query/ContractsByCreator RPC method. -message QueryContractsByCreatorResponse { - // ContractAddresses result set - repeated string contract_addresses = 1; - // Pagination defines the pagination in the response. - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} \ No newline at end of file diff --git a/proto/cosmwasm/wasm/v1/tx.proto b/proto/cosmwasm/wasm/v1/tx.proto deleted file mode 100644 index 79a9930..0000000 --- a/proto/cosmwasm/wasm/v1/tx.proto +++ /dev/null @@ -1,391 +0,0 @@ -syntax = "proto3"; -package cosmwasm.wasm.v1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos/msg/v1/msg.proto"; -import "gogoproto/gogo.proto"; -import "cosmwasm/wasm/v1/types.proto"; -import "cosmos_proto/cosmos.proto"; -import "amino/amino.proto"; - -option go_package = "github.com/terpnetwork/terp-core/x/wasm/types"; -option (gogoproto.goproto_getters_all) = false; - -// Msg defines the wasm Msg service. -service Msg { - // StoreCode to submit Wasm code to the system - rpc StoreCode(MsgStoreCode) returns (MsgStoreCodeResponse); - // InstantiateContract creates a new smart contract instance for the given - // code id. - rpc InstantiateContract(MsgInstantiateContract) - returns (MsgInstantiateContractResponse); - // InstantiateContract2 creates a new smart contract instance for the given - // code id with a predictable address - rpc InstantiateContract2(MsgInstantiateContract2) - returns (MsgInstantiateContract2Response); - // Execute submits the given message data to a smart contract - rpc ExecuteContract(MsgExecuteContract) returns (MsgExecuteContractResponse); - // Migrate runs a code upgrade/ downgrade for a smart contract - rpc MigrateContract(MsgMigrateContract) returns (MsgMigrateContractResponse); - // UpdateAdmin sets a new admin for a smart contract - rpc UpdateAdmin(MsgUpdateAdmin) returns (MsgUpdateAdminResponse); - // ClearAdmin removes any admin stored for a smart contract - rpc ClearAdmin(MsgClearAdmin) returns (MsgClearAdminResponse); - // UpdateInstantiateConfig updates instantiate config for a smart contract - rpc UpdateInstantiateConfig(MsgUpdateInstantiateConfig) - returns (MsgUpdateInstantiateConfigResponse); - // UpdateParams defines a governance operation for updating the x/wasm - // module parameters. The authority is defined in the keeper. - // - // Since: 0.40 - rpc UpdateParams(MsgUpdateParams) returns (MsgUpdateParamsResponse); - // SudoContract defines a governance operation for calling sudo - // on a contract. The authority is defined in the keeper. - // - // Since: 0.40 - rpc SudoContract(MsgSudoContract) returns (MsgSudoContractResponse); - // PinCodes defines a governance operation for pinning a set of - // code ids in the wasmvm cache. The authority is defined in the keeper. - // - // Since: 0.40 - rpc PinCodes(MsgPinCodes) returns (MsgPinCodesResponse); - // UnpinCodes defines a governance operation for unpinning a set of - // code ids in the wasmvm cache. The authority is defined in the keeper. - // - // Since: 0.40 - rpc UnpinCodes(MsgUnpinCodes) returns (MsgUnpinCodesResponse); - // StoreAndInstantiateContract defines a governance operation for storing - // and instantiating the contract. The authority is defined in the keeper. - // - // Since: 0.40 - rpc StoreAndInstantiateContract(MsgStoreAndInstantiateContract) - returns (MsgStoreAndInstantiateContractResponse); -} - -// MsgStoreCode submit Wasm code to the system -message MsgStoreCode { - option (amino.name) = "wasm/MsgStoreCode"; - option (cosmos.msg.v1.signer) = "sender"; - - // Sender is the actor that signed the messages - string sender = 1; - // WASMByteCode can be raw or gzip compressed - bytes wasm_byte_code = 2 [ (gogoproto.customname) = "WASMByteCode" ]; - // Used in v1beta1 - reserved 3, 4; - // InstantiatePermission access control to apply on contract creation, - // optional - AccessConfig instantiate_permission = 5; -} -// MsgStoreCodeResponse returns store result data. -message MsgStoreCodeResponse { - // CodeID is the reference to the stored WASM code - uint64 code_id = 1 [ (gogoproto.customname) = "CodeID" ]; - // Checksum is the sha256 hash of the stored code - bytes checksum = 2; -} - -// MsgInstantiateContract create a new smart contract instance for the given -// code id. -message MsgInstantiateContract { - option (amino.name) = "wasm/MsgInstantiateContract"; - option (cosmos.msg.v1.signer) = "sender"; - - // Sender is the that actor that signed the messages - string sender = 1; - // Admin is an optional address that can execute migrations - string admin = 2; - // CodeID is the reference to the stored WASM code - uint64 code_id = 3 [ (gogoproto.customname) = "CodeID" ]; - // Label is optional metadata to be stored with a contract instance. - string label = 4; - // Msg json encoded message to be passed to the contract on instantiation - bytes msg = 5 [ (gogoproto.casttype) = "RawContractMessage" ]; - // Funds coins that are transferred to the contract on instantiation - repeated cosmos.base.v1beta1.Coin funds = 6 [ - (gogoproto.nullable) = false, - (amino.dont_omitempty) = true, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} - -// MsgInstantiateContractResponse return instantiation result data -message MsgInstantiateContractResponse { - // Address is the bech32 address of the new contract instance. - string address = 1; - // Data contains bytes to returned from the contract - bytes data = 2; -} - -// MsgInstantiateContract2 create a new smart contract instance for the given -// code id with a predicable address. -message MsgInstantiateContract2 { - option (amino.name) = "wasm/MsgInstantiateContract2"; - option (cosmos.msg.v1.signer) = "sender"; - - // Sender is the that actor that signed the messages - string sender = 1; - // Admin is an optional address that can execute migrations - string admin = 2; - // CodeID is the reference to the stored WASM code - uint64 code_id = 3 [ (gogoproto.customname) = "CodeID" ]; - // Label is optional metadata to be stored with a contract instance. - string label = 4; - // Msg json encoded message to be passed to the contract on instantiation - bytes msg = 5 [ (gogoproto.casttype) = "RawContractMessage" ]; - // Funds coins that are transferred to the contract on instantiation - repeated cosmos.base.v1beta1.Coin funds = 6 [ - (gogoproto.nullable) = false, - (amino.dont_omitempty) = true, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; - // Salt is an arbitrary value provided by the sender. Size can be 1 to 64. - bytes salt = 7; - // FixMsg include the msg value into the hash for the predictable address. - // Default is false - bool fix_msg = 8; -} - -// MsgInstantiateContract2Response return instantiation result data -message MsgInstantiateContract2Response { - // Address is the bech32 address of the new contract instance. - string address = 1; - // Data contains bytes to returned from the contract - bytes data = 2; -} - -// MsgExecuteContract submits the given message data to a smart contract -message MsgExecuteContract { - option (amino.name) = "wasm/MsgExecuteContract"; - option (cosmos.msg.v1.signer) = "sender"; - - // Sender is the that actor that signed the messages - string sender = 1; - // Contract is the address of the smart contract - string contract = 2; - // Msg json encoded message to be passed to the contract - bytes msg = 3 [ (gogoproto.casttype) = "RawContractMessage" ]; - // Funds coins that are transferred to the contract on execution - repeated cosmos.base.v1beta1.Coin funds = 5 [ - (gogoproto.nullable) = false, - (amino.dont_omitempty) = true, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} - -// MsgExecuteContractResponse returns execution result data. -message MsgExecuteContractResponse { - // Data contains bytes to returned from the contract - bytes data = 1; -} - -// MsgMigrateContract runs a code upgrade/ downgrade for a smart contract -message MsgMigrateContract { - option (amino.name) = "wasm/MsgMigrateContract"; - option (cosmos.msg.v1.signer) = "sender"; - - // Sender is the that actor that signed the messages - string sender = 1; - // Contract is the address of the smart contract - string contract = 2; - // CodeID references the new WASM code - uint64 code_id = 3 [ (gogoproto.customname) = "CodeID" ]; - // Msg json encoded message to be passed to the contract on migration - bytes msg = 4 [ (gogoproto.casttype) = "RawContractMessage" ]; -} - -// MsgMigrateContractResponse returns contract migration result data. -message MsgMigrateContractResponse { - // Data contains same raw bytes returned as data from the wasm contract. - // (May be empty) - bytes data = 1; -} - -// MsgUpdateAdmin sets a new admin for a smart contract -message MsgUpdateAdmin { - option (amino.name) = "wasm/MsgUpdateAdmin"; - option (cosmos.msg.v1.signer) = "sender"; - - // Sender is the that actor that signed the messages - string sender = 1; - // NewAdmin address to be set - string new_admin = 2; - // Contract is the address of the smart contract - string contract = 3; -} - -// MsgUpdateAdminResponse returns empty data -message MsgUpdateAdminResponse {} - -// MsgClearAdmin removes any admin stored for a smart contract -message MsgClearAdmin { - option (amino.name) = "wasm/MsgClearAdmin"; - option (cosmos.msg.v1.signer) = "sender"; - - // Sender is the actor that signed the messages - string sender = 1; - // Contract is the address of the smart contract - string contract = 3; -} - -// MsgClearAdminResponse returns empty data -message MsgClearAdminResponse {} - -// MsgUpdateInstantiateConfig updates instantiate config for a smart contract -message MsgUpdateInstantiateConfig { - option (amino.name) = "wasm/MsgUpdateInstantiateConfig"; - option (cosmos.msg.v1.signer) = "sender"; - - // Sender is the that actor that signed the messages - string sender = 1; - // CodeID references the stored WASM code - uint64 code_id = 2 [ (gogoproto.customname) = "CodeID" ]; - // NewInstantiatePermission is the new access control - AccessConfig new_instantiate_permission = 3; -} - -// MsgUpdateInstantiateConfigResponse returns empty data -message MsgUpdateInstantiateConfigResponse {} - -// MsgUpdateParams is the MsgUpdateParams request type. -// -// Since: 0.40 -message MsgUpdateParams { - option (amino.name) = "wasm/MsgUpdateParams"; - option (cosmos.msg.v1.signer) = "authority"; - - // Authority is the address of the governance account. - string authority = 1 [ (cosmos_proto.scalar) = "cosmos.AddressString" ]; - - // params defines the x/wasm parameters to update. - // - // NOTE: All parameters must be supplied. - Params params = 2 - [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; -} - -// MsgUpdateParamsResponse defines the response structure for executing a -// MsgUpdateParams message. -// -// Since: 0.40 -message MsgUpdateParamsResponse {} - -// MsgSudoContract is the MsgSudoContract request type. -// -// Since: 0.40 -message MsgSudoContract { - option (amino.name) = "wasm/MsgSudoContract"; - option (cosmos.msg.v1.signer) = "authority"; - - // Authority is the address of the governance account. - string authority = 1 [ (cosmos_proto.scalar) = "cosmos.AddressString" ]; - - // Contract is the address of the smart contract - string contract = 2; - // Msg json encoded message to be passed to the contract as sudo - bytes msg = 3 [ (gogoproto.casttype) = "RawContractMessage" ]; -} - -// MsgSudoContractResponse defines the response structure for executing a -// MsgSudoContract message. -// -// Since: 0.40 -message MsgSudoContractResponse { - // Data contains bytes to returned from the contract - bytes data = 1; -} - -// MsgPinCodes is the MsgPinCodes request type. -// -// Since: 0.40 -message MsgPinCodes { - option (amino.name) = "wasm/MsgPinCodes"; - option (cosmos.msg.v1.signer) = "authority"; - - // Authority is the address of the governance account. - string authority = 1 [ (cosmos_proto.scalar) = "cosmos.AddressString" ]; - // CodeIDs references the new WASM codes - repeated uint64 code_ids = 2 [ - (gogoproto.customname) = "CodeIDs", - (gogoproto.moretags) = "yaml:\"code_ids\"" - ]; -} - -// MsgPinCodesResponse defines the response structure for executing a -// MsgPinCodes message. -// -// Since: 0.40 -message MsgPinCodesResponse {} - -// MsgUnpinCodes is the MsgUnpinCodes request type. -// -// Since: 0.40 -message MsgUnpinCodes { - option (amino.name) = "wasm/MsgUnpinCodes"; - option (cosmos.msg.v1.signer) = "authority"; - - // Authority is the address of the governance account. - string authority = 1 [ (cosmos_proto.scalar) = "cosmos.AddressString" ]; - // CodeIDs references the WASM codes - repeated uint64 code_ids = 2 [ - (gogoproto.customname) = "CodeIDs", - (gogoproto.moretags) = "yaml:\"code_ids\"" - ]; -} - -// MsgUnpinCodesResponse defines the response structure for executing a -// MsgUnpinCodes message. -// -// Since: 0.40 -message MsgUnpinCodesResponse {} - -// MsgStoreAndInstantiateContract is the MsgStoreAndInstantiateContract -// request type. -// -// Since: 0.40 -message MsgStoreAndInstantiateContract { - option (amino.name) = "wasm/MsgStoreAndInstantiateContract"; - option (cosmos.msg.v1.signer) = "authority"; - - // Authority is the address of the governance account. - string authority = 1 [ (cosmos_proto.scalar) = "cosmos.AddressString" ]; - // WASMByteCode can be raw or gzip compressed - bytes wasm_byte_code = 3 [ (gogoproto.customname) = "WASMByteCode" ]; - // InstantiatePermission to apply on contract creation, optional - AccessConfig instantiate_permission = 4; - // UnpinCode code on upload, optional. As default the uploaded contract is - // pinned to cache. - bool unpin_code = 5; - // Admin is an optional address that can execute migrations - string admin = 6; - // Label is optional metadata to be stored with a constract instance. - string label = 7; - // Msg json encoded message to be passed to the contract on instantiation - bytes msg = 8 [ (gogoproto.casttype) = "RawContractMessage" ]; - // Funds coins that are transferred from the authority account to the contract - // on instantiation - repeated cosmos.base.v1beta1.Coin funds = 9 [ - (gogoproto.nullable) = false, - (amino.dont_omitempty) = true, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; - // Source is the URL where the code is hosted - string source = 10; - // Builder is the docker image used to build the code deterministically, used - // for smart contract verification - string builder = 11; - // CodeHash is the SHA256 sum of the code outputted by builder, used for smart - // contract verification - bytes code_hash = 12; -} - -// MsgStoreAndInstantiateContractResponse defines the response structure -// for executing a MsgStoreAndInstantiateContract message. -// -// Since: 0.40 -message MsgStoreAndInstantiateContractResponse { - // Address is the bech32 address of the new contract instance. - string address = 1; - // Data contains bytes to returned from the contract - bytes data = 2; -} \ No newline at end of file diff --git a/proto/cosmwasm/wasm/v1/types.proto b/proto/cosmwasm/wasm/v1/types.proto deleted file mode 100644 index 1572b5a..0000000 --- a/proto/cosmwasm/wasm/v1/types.proto +++ /dev/null @@ -1,148 +0,0 @@ -syntax = "proto3"; -package cosmwasm.wasm.v1; - -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/protobuf/any.proto"; -import "amino/amino.proto"; - -option go_package = "github.com/terpnetwork/terp-core/x/wasm/types"; -option (gogoproto.goproto_getters_all) = false; -option (gogoproto.equal_all) = true; - -// AccessType permission types -enum AccessType { - option (gogoproto.goproto_enum_prefix) = false; - option (gogoproto.goproto_enum_stringer) = false; - // AccessTypeUnspecified placeholder for empty value - ACCESS_TYPE_UNSPECIFIED = 0 - [ (gogoproto.enumvalue_customname) = "AccessTypeUnspecified" ]; - // AccessTypeNobody forbidden - ACCESS_TYPE_NOBODY = 1 - [ (gogoproto.enumvalue_customname) = "AccessTypeNobody" ]; - // AccessTypeOnlyAddress restricted to a single address - // Deprecated: use AccessTypeAnyOfAddresses instead - ACCESS_TYPE_ONLY_ADDRESS = 2 - [ (gogoproto.enumvalue_customname) = "AccessTypeOnlyAddress" ]; - // AccessTypeEverybody unrestricted - ACCESS_TYPE_EVERYBODY = 3 - [ (gogoproto.enumvalue_customname) = "AccessTypeEverybody" ]; - // AccessTypeAnyOfAddresses allow any of the addresses - ACCESS_TYPE_ANY_OF_ADDRESSES = 4 - [ (gogoproto.enumvalue_customname) = "AccessTypeAnyOfAddresses" ]; -} - -// AccessTypeParam -message AccessTypeParam { - option (gogoproto.goproto_stringer) = true; - AccessType value = 1 [ (gogoproto.moretags) = "yaml:\"value\"" ]; -} - -// AccessConfig access control type. -message AccessConfig { - option (gogoproto.goproto_stringer) = true; - AccessType permission = 1 [ (gogoproto.moretags) = "yaml:\"permission\"" ]; - - // Address - // Deprecated: replaced by addresses - string address = 2 [ (gogoproto.moretags) = "yaml:\"address\"" ]; - repeated string addresses = 3 [ (gogoproto.moretags) = "yaml:\"addresses\"" ]; -} - -// Params defines the set of wasm parameters. -message Params { - option (gogoproto.goproto_stringer) = false; - AccessConfig code_upload_access = 1 [ - (gogoproto.nullable) = false, - (amino.dont_omitempty) = true, - (gogoproto.moretags) = "yaml:\"code_upload_access\"" - ]; - AccessType instantiate_default_permission = 2 - [ (gogoproto.moretags) = "yaml:\"instantiate_default_permission\"" ]; -} - -// CodeInfo is data for the uploaded contract WASM code -message CodeInfo { - // CodeHash is the unique identifier created by wasmvm - bytes code_hash = 1; - // Creator address who initially stored the code - string creator = 2; - // Used in v1beta1 - reserved 3, 4; - // InstantiateConfig access control to apply on contract creation, optional - AccessConfig instantiate_config = 5 - [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; -} - -// ContractInfo stores a WASM contract instance -message ContractInfo { - option (gogoproto.equal) = true; - - // CodeID is the reference to the stored Wasm code - uint64 code_id = 1 [ (gogoproto.customname) = "CodeID" ]; - // Creator address who initially instantiated the contract - string creator = 2; - // Admin is an optional address that can execute migrations - string admin = 3; - // Label is optional metadata to be stored with a contract instance. - string label = 4; - // Created Tx position when the contract was instantiated. - AbsoluteTxPosition created = 5; - string ibc_port_id = 6 [ (gogoproto.customname) = "IBCPortID" ]; - - // Extension is an extension point to store custom metadata within the - // persistence model. - google.protobuf.Any extension = 7 - [ (cosmos_proto.accepts_interface) = - "cosmwasm.wasm.v1.ContractInfoExtension" ]; -} - -// ContractCodeHistoryOperationType actions that caused a code change -enum ContractCodeHistoryOperationType { - option (gogoproto.goproto_enum_prefix) = false; - // ContractCodeHistoryOperationTypeUnspecified placeholder for empty value - CONTRACT_CODE_HISTORY_OPERATION_TYPE_UNSPECIFIED = 0 - [ (gogoproto.enumvalue_customname) = - "ContractCodeHistoryOperationTypeUnspecified" ]; - // ContractCodeHistoryOperationTypeInit on chain contract instantiation - CONTRACT_CODE_HISTORY_OPERATION_TYPE_INIT = 1 - [ (gogoproto.enumvalue_customname) = - "ContractCodeHistoryOperationTypeInit" ]; - // ContractCodeHistoryOperationTypeMigrate code migration - CONTRACT_CODE_HISTORY_OPERATION_TYPE_MIGRATE = 2 - [ (gogoproto.enumvalue_customname) = - "ContractCodeHistoryOperationTypeMigrate" ]; - // ContractCodeHistoryOperationTypeGenesis based on genesis data - CONTRACT_CODE_HISTORY_OPERATION_TYPE_GENESIS = 3 - [ (gogoproto.enumvalue_customname) = - "ContractCodeHistoryOperationTypeGenesis" ]; -} - -// ContractCodeHistoryEntry metadata to a contract. -message ContractCodeHistoryEntry { - ContractCodeHistoryOperationType operation = 1; - // CodeID is the reference to the stored WASM code - uint64 code_id = 2 [ (gogoproto.customname) = "CodeID" ]; - // Updated Tx position when the operation was executed. - AbsoluteTxPosition updated = 3; - bytes msg = 4 [ (gogoproto.casttype) = "RawContractMessage" ]; -} - -// AbsoluteTxPosition is a unique transaction position that allows for global -// ordering of transactions. -message AbsoluteTxPosition { - // BlockHeight is the block the contract was created at - uint64 block_height = 1; - // TxIndex is a monotonic counter within the block (actual transaction index, - // or gas consumed) - uint64 tx_index = 2; -} - -// Model is a struct that holds a KV pair -message Model { - // hex-encode key to read it better (this is often ascii) - bytes key = 1 [ (gogoproto.casttype) = - "github.com/cometbft/cometbft/libs/bytes.HexBytes" ]; - // base64-encode raw value - bytes value = 2; -} \ No newline at end of file diff --git a/scripts/build.sh b/scripts/build.sh new file mode 100644 index 0000000..6582a24 --- /dev/null +++ b/scripts/build.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +set -e + +GIT_TAG=$(git describe --tags) + +echo "> Building $GIT_TAG..." + +docker build . -t terpnetwork/terp-core:$GIT_TAG \ No newline at end of file diff --git a/scripts/build_and_run.sh b/scripts/build_and_run.sh new file mode 100644 index 0000000..7705232 --- /dev/null +++ b/scripts/build_and_run.sh @@ -0,0 +1,6 @@ +#!/bin/bash + +set -e + +./scripts/build.sh +./scripts/run.sh \ No newline at end of file diff --git a/scripts/build_and_run_blocking.sh b/scripts/build_and_run_blocking.sh new file mode 100644 index 0000000..b10a142 --- /dev/null +++ b/scripts/build_and_run_blocking.sh @@ -0,0 +1,6 @@ +#!/bin/bash + +set -e + +./scripts/build.sh +./scripts/run_blocking.sh \ No newline at end of file diff --git a/scripts/merge_protoc.py b/scripts/merge_protoc.py new file mode 100644 index 0000000..a908fc6 --- /dev/null +++ b/scripts/merge_protoc.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 + +# Call this from the ./scripts/protoc_swagger_openapi_gen.sh script + +# merged protoc definitions together into 1 JSON file without duplicate keys +# this is done AFTER swagger-merger has been run, merging the multiple name-#.json files into 1. + +import json +import os +import random +import string + +current_dir = os.path.dirname(os.path.realpath(__file__)) +project_root = os.path.dirname(current_dir) + +all_dir = os.path.join(project_root, "tmp-swagger-gen", "_all") + +# get the go.mod file Version +version = "" +with open(os.path.join(project_root, "go.mod"), "r") as f: + for line in f.readlines(): + if line.startswith("module"): + version = line.split("/")[-1].strip() + break + +if not version: + print("Could not find version in go.mod") + exit(1) + +# What we will save when all combined +output: dict +output = { + "swagger": "2.0", + "info": {"title": "Terp network", "version": version}, + "consumes": ["application/json"], + "produces": ["application/json"], + "paths": {}, + "definitions": {}, +} + +# Combine all individual files calls into 1 massive file. +for file in os.listdir(all_dir): + if not file.endswith(".json"): + continue + + # read file all_dir / file + with open(os.path.join(all_dir, file), "r") as f: + data = json.load(f) + + for key in data["paths"]: + output["paths"][key] = data["paths"][key] + + for key in data["definitions"]: + output["definitions"][key] = data["definitions"][key] + + +# loop through all paths, then alter any keys which are "operationId" to be a random string of 20 characters +# this is done to avoid duplicate keys in the final output (which opens 2 tabs in swagger-ui) +# current-random +for path in output["paths"]: + for method in output["paths"][path]: + if "operationId" in output["paths"][path][method]: + output["paths"][path][method][ + "operationId" + ] = f'{output["paths"][path][method]["operationId"]}_' + "".join( + random.choices(string.ascii_uppercase + string.digits, k=5) + ) + + +# save output into 1 big json file +with open( + os.path.join(project_root, "tmp-swagger-gen", "_all", "FINAL.json"), "w" +) as f: + json.dump(output, f, indent=2) diff --git a/scripts/protoc-swagger-gen.sh b/scripts/protoc-swagger-gen.sh deleted file mode 100755 index f0a6bc8..0000000 --- a/scripts/protoc-swagger-gen.sh +++ /dev/null @@ -1,19 +0,0 @@ -#!/usr/bin/env bash - -set -eo pipefail - -mkdir -p ./docs/client -proto_dirs=$(find ./proto -path -prune -o -name '*.proto' -print0 | xargs -0 -n1 dirname | sort | uniq) -for dir in $proto_dirs; do - - # generate swagger files (filter query files) - query_file=$(find "${dir}" -maxdepth 1 \( -name 'query.proto' -o -name 'service.proto' \)) - if [[ ! -z "$query_file" ]]; then - buf protoc \ - -I "proto" \ - -I "third_party/proto" \ - "$query_file" \ - --swagger_out=./docs/client \ - --swagger_opt=logtostderr=true --swagger_opt=fqn_for_swagger_name=true --swagger_opt=simple_operation_ids=true - fi -done diff --git a/scripts/protoc_swagger_openapi_gen.sh b/scripts/protoc_swagger_openapi_gen.sh new file mode 100644 index 0000000..613ad7c --- /dev/null +++ b/scripts/protoc_swagger_openapi_gen.sh @@ -0,0 +1,97 @@ +#!/usr/bin/env bash + +# Run from the project root directory +# This script generates the swagger & openapi.yaml documentation for the rest API on port 1317 +# +# Install the following:: +# sudo npm install -g swagger2openapi swagger-merger swagger-combine +# go install github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger@v1.16.0 + +# change to the scripts folder +cd "$(dirname `realpath "$0"`)" +# change to the root folder +cd ../ + +mkdir -p ./tmp-swagger-gen + +# Get the paths used repos from go/pkg/mod +cosmos_sdk_dir=$(go list -f '{{ .Dir }}' -m github.com/cosmos/cosmos-sdk) +wasmd=$(go list -f '{{ .Dir }}' -m github.com/CosmWasm/wasmd) +gaia=$(go list -f '{{ .Dir }}' -m github.com/cosmos/gaia/v9) +ica=$(go list -f '{{ .Dir }}' -m github.com/cosmos/interchain-accounts) +pfm=$(go list -fprot '{{ .Dir }}' -m github.com/strangelove-ventures/packet-forward-middleware/v4) + +proto_dirs=$(find ./proto "$cosmos_sdk_dir"/proto "$wasmd"/proto "$gaia"/proto "$ica"/proto "$pfm"/proto -path -prune -o -name '*.proto' -print0 | xargs -0 -n1 dirname | sort | uniq) +for dir in $proto_dirs; do + + # generate swagger files (filter query files) + query_file=$(find "${dir}" -maxdepth 1 \( -name 'query.proto' -o -name 'service.proto' \)) + if [[ ! -z "$query_file" ]]; then + protoc \ + -I "proto" \ + -I "$cosmos_sdk_dir/third_party/proto" \ + -I "$cosmos_sdk_dir/proto" \ + -I "$wasmd/proto" \ + -I "$gaia/proto" \ + -I "$ica/proto" \ + -I "$pfm/proto" \ + "$query_file" \ + --swagger_out ./tmp-swagger-gen \ + --swagger_opt logtostderr=true \ + --swagger_opt fqn_for_swagger_name=true \ + --swagger_opt simple_operation_ids=true + fi +done + +# delete cosmos/mint path since terp uses its own module +rm -rf ./tmp-swagger-gen/cosmos/mint + +# Fix circular definition in cosmos/tx/v1beta1/service.swagger.json +jq 'del(.definitions["cosmos.tx.v1beta1.ModeInfo.Multi"].properties.mode_infos.items["$ref"])' ./tmp-swagger-gen/cosmos/tx/v1beta1/service.swagger.json > ./tmp-swagger-gen/cosmos/tx/v1beta1/fixed-service.swagger.json + +# Tag everything as "gRPC Gateway API" +perl -i -pe 's/"(Query|Service)"/"gRPC Gateway API"/' $(find ./tmp-swagger-gen -name '*.swagger.json' -print0 | xargs -0) + +# Convert all *.swagger.json files into a single folder _all +files=$(find ./tmp-swagger-gen -name '*.swagger.json' -print0 | xargs -0) +mkdir -p ./tmp-swagger-gen/_all +counter=0 +for f in $files; do + echo "[+] $f" + + # check gaia first before cosmos + if [[ "$f" =~ "gaia" ]]; then + cp $f ./tmp-swagger-gen/_all/gaia-$counter.json + elif [[ "$f" =~ "router" ]]; then + cp $f ./tmp-swagger-gen/_all/pfm-$counter.json + elif [[ "$f" =~ "cosmwasm" ]]; then + cp $f ./tmp-swagger-gen/_all/cosmwasm-$counter.json + elif [[ "$f" =~ "osmosis" ]]; then + cp $f ./tmp-swagger-gen/_all/osmosis-$counter.json + elif [[ "$f" =~ "terp" ]]; then + cp $f ./tmp-swagger-gen/_all/terp-$counter.json + elif [[ "$f" =~ "cosmos" ]]; then + cp $f ./tmp-swagger-gen/_all/cosmos-$counter.json + # elif [[ "$f" =~ "intertx" ]]; then + # cp $f ./tmp-swagger-gen/_all/intertx-$counter.json + else + cp $f ./tmp-swagger-gen/_all/other-$counter.json + fi + ((counter++)) +done + +# merges all the above into FINAL.json +python3 ./scripts/merge_protoc.py + +# Makes a swagger temp file with reference pointers +swagger-combine ./tmp-swagger-gen/_all/FINAL.json -o ./docs/_tmp_swagger.yaml -f yaml --continueOnConflictingPaths --includeDefinitions + +# extends out the *ref instances to their full value +swagger-merger --input ./docs/_tmp_swagger.yaml -o ./docs/swagger.yaml + +# Derive openapi from swagger docs +swagger2openapi --patch ./docs/swagger.yaml --outfile ./docs/static/openapi.yml --yaml + +# clean swagger tmp files +rm ./docs/_tmp_swagger.yaml +rm -rf ./tmp-swagger-gen \ No newline at end of file diff --git a/scripts/protocgen2.sh b/scripts/protocgen2.sh new file mode 100644 index 0000000..77ad9c7 --- /dev/null +++ b/scripts/protocgen2.sh @@ -0,0 +1,19 @@ +# this script is for generating protobuf files for the new google.golang.org/protobuf API + +set -eo pipefail + +protoc_install_gopulsar() { + go install github.com/cosmos/cosmos-proto/cmd/protoc-gen-go-pulsar@latest + go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest +} + +protoc_install_gopulsar + +echo "Cleaning API directory" +(cd api; find ./ -type f \( -iname \*.pulsar.go -o -iname \*.pb.go -o -iname \*.cosmos_orm.go -o -iname \*.pb.gw.go \) -delete; find . -empty -type d -delete; cd ..) + +echo "Generating API module" +(cd proto; buf generate --template buf.gen.pulsar.yaml) + +echo "Generate Pulsar Test Data" +(cd testutil/testdata; buf generate --template buf.gen.pulsar.yaml) \ No newline at end of file diff --git a/scripts/run.sh b/scripts/run.sh new file mode 100644 index 0000000..97a2d31 --- /dev/null +++ b/scripts/run.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +set -e + +GIT_TAG=$(git describe --tags) + +echo "> Running $GIT_TAG..." + +docker run --rm -it -p 26657:26657 --name terp-local terpnetwork/terp-core:$GIT_TAG /bin/sh \ No newline at end of file diff --git a/scripts/run_blocking.sh b/scripts/run_blocking.sh new file mode 100644 index 0000000..2d22122 --- /dev/null +++ b/scripts/run_blocking.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +set -e + +GIT_TAG=$(git describe --tags) + +echo "> Running $GIT_TAG..." + +docker run --rm -it -p 26657:26657 --name terp-local terpnetwork/terp-core:$GIT_TAG /bin/sh -c "./setup_and_run.sh" \ No newline at end of file diff --git a/scripts/test_node.sh b/scripts/test_node.sh new file mode 100644 index 0000000..812a929 --- /dev/null +++ b/scripts/test_node.sh @@ -0,0 +1,118 @@ +#!/bin/bash +# Run this script to quickly install, setup, and run the current version of terp without docker. +# +# Example: +# CHAIN_ID="local-1" HOME_DIR="~/.terp1" TIMEOUT_COMMIT="500ms" CLEAN=true sh scripts/test_node.sh +# CHAIN_ID="local-2" HOME_DIR="~/.terp2" CLEAN=true RPC=36657 REST=2317 PROFF=6061 P2P=36656 GRPC=8090 GRPC_WEB=8091 ROSETTA=8081 TIMEOUT_COMMIT="500ms" sh scripts/test_node.sh +# +# To use unoptomized wasm files up to ~5mb, add: MAX_WASM_SIZE=5000000 + +export KEY="terp1" +export KEY2="terp2" + +export CHAIN_ID=${CHAIN_ID:-"local-1"} +export MONIKER="localterp" +export KEYALGO="secp256k1" +export KEYRING=${KEYRING:-"test"} +export HOME_DIR=$(eval echo "${HOME_DIR:-"~/.terp"}") +export BINARY=${BINARY:-terpd} + +export CLEAN=${CLEAN:-"false"} +export RPC=${RPC:-"26657"} +export REST=${REST:-"1317"} +export PROFF=${PROFF:-"6060"} +export P2P=${P2P:-"26656"} +export GRPC=${GRPC:-"9090"} +export GRPC_WEB=${GRPC_WEB:-"9091"} +export ROSETTA=${ROSETTA:-"8080"} +export TIMEOUT_COMMIT=${TIMEOUT_COMMIT:-"5s"} + +alias BINARY="$BINARY --home=$HOME_DIR" + +command -v $BINARY > /dev/null 2>&1 || { echo >&2 "$BINARY command not found. Ensure this is setup / properly installed in your GOPATH (make install)."; exit 1; } +command -v jq > /dev/null 2>&1 || { echo >&2 "jq not installed. More info: https://stedolan.github.io/jq/download/"; exit 1; } + +$BINARY config keyring-backend $KEYRING +$BINARY config chain-id $CHAIN_ID + +from_scratch () { + # Fresh install on current branch + make install + + # remove existing daemon. + rm -rf $HOME_DIR && echo "Removed $HOME_DIR" + + # terp1efd63aw40lxf3n4mhf7dzhjkr453axurajg60e + echo "decorate bright ozone fork gallery riot bus exhaust worth way bone indoor calm squirrel merry zero scheme cotton until shop any excess stage laundry" | BINARY keys add $KEY --keyring-backend $KEYRING --algo $KEYALGO --recover + # terp1hj5fveer5cjtn4wd6wstzugjfdxzl0xppxm7xs + echo "wealth flavor believe regret funny network recall kiss grape useless pepper cram hint member few certain unveil rather brick bargain curious require crowd raise" | BINARY keys add $KEY2 --keyring-backend $KEYRING --algo $KEYALGO --recover + + BINARY init $MONIKER --chain-id $CHAIN_ID --default-denom uterp + + # Function updates the config based on a jq argument as a string + update_test_genesis () { + cat $HOME_DIR/config/genesis.json | jq "$1" > $HOME_DIR/config/tmp_genesis.json && mv $HOME_DIR/config/tmp_genesis.json $HOME_DIR/config/genesis.json + } + + # Block + update_test_genesis '.consensus_params["block"]["max_gas"]="100000000"' + # Gov + update_test_genesis '.app_state["gov"]["params"]["min_deposit"]=[{"denom": "uterp","amount": "1000000"}]' + update_test_genesis '.app_state["gov"]["voting_params"]["voting_period"]="15s"' + # staking + update_test_genesis '.app_state["staking"]["params"]["bond_denom"]="uterp"' + update_test_genesis '.app_state["staking"]["params"]["min_commission_rate"]="0.050000000000000000"' + # mint + update_test_genesis '.app_state["mint"]["params"]["mint_denom"]="uterp"' + # crisis + update_test_genesis '.app_state["crisis"]["constant_fee"]={"denom": "uterp","amount": "1000"}' + + # Custom Modules + + # Allocate genesis accounts + BINARY genesis add-genesis-account $KEY 10000000uterp,1000utest --keyring-backend $KEYRING + BINARY genesis add-genesis-account $KEY2 1000000uterp,1000utest --keyring-backend $KEYRING + + BINARY genesis gentx $KEY 1000000uterp --keyring-backend $KEYRING --chain-id $CHAIN_ID + + # Collect genesis tx + BINARY genesis collect-gentxs + + # Run this to ensure terprything worked and that the genesis file is setup correctly + BINARY genesis validate-genesis +} + +# check if CLEAN is not set to false +if [ "$CLEAN" != "false" ]; then + echo "Starting from a clean state" + from_scratch +fi + +echo "Starting node..." + +# Opens the RPC endpoint to outside connections +sed -i 's/laddr = "tcp:\/\/127.0.0.1:26657"/c\laddr = "tcp:\/\/0.0.0.0:'$RPC'"/g' $HOME_DIR/config/config.toml +sed -i 's/cors_allowed_origins = \[\]/cors_allowed_origins = \["\*"\]/g' $HOME_DIR/config/config.toml + +# REST endpoint +sed -i 's/address = "tcp:\/\/localhost:1317"/address = "tcp:\/\/0.0.0.0:'$REST'"/g' $HOME_DIR/config/app.toml +sed -i 's/enable = false/enable = true/g' $HOME_DIR/config/app.toml + +# replace pprof_laddr = "localhost:6060" binding +sed -i 's/pprof_laddr = "localhost:6060"/pprof_laddr = "localhost:'$PROFF_LADDER'"/g' $HOME_DIR/config/config.toml + +# change p2p addr laddr = "tcp://0.0.0.0:26656" +sed -i 's/laddr = "tcp:\/\/0.0.0.0:26656"/laddr = "tcp:\/\/0.0.0.0:'$P2P'"/g' $HOME_DIR/config/config.toml + +# GRPC +sed -i 's/address = "localhost:9090"/address = "0.0.0.0:'$GRPC'"/g' $HOME_DIR/config/app.toml +sed -i 's/address = "localhost:9091"/address = "0.0.0.0:'$GRPC_WEB'"/g' $HOME_DIR/config/app.toml + +# Rosetta Api +sed -i 's/address = ":8080"/address = "0.0.0.0:'$ROSETTA'"/g' $HOME_DIR/config/app.toml + +# faster blocks +sed -i 's/timeout_commit = "5s"/timeout_commit = "'$TIMEOUT_COMMIT'"/g' $HOME_DIR/config/config.toml + +# Start the node with 0 gas fees +BINARY start --pruning=nothing --minimum-gas-prices=0uterp --rpc.laddr="tcp://0.0.0.0:$RPC" \ No newline at end of file diff --git a/tests/e2e/README.md b/tests/e2e/README.md deleted file mode 100644 index dae38fe..0000000 --- a/tests/e2e/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# End To End Testing - e2e - -Scenario tests that run against on or multiple chain instances. diff --git a/tests/e2e/gov_test.go b/tests/e2e/gov_test.go deleted file mode 100644 index 4054637..0000000 --- a/tests/e2e/gov_test.go +++ /dev/null @@ -1,135 +0,0 @@ -package e2e_test - -import ( - "testing" - "time" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" - sdk "github.com/cosmos/cosmos-sdk/types" - distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/tests/e2e" - "github.com/terpnetwork/terp-core/x/wasm/ibctesting" -) - -func TestGovVoteByContract(t *testing.T) { - // Given a contract with delegation - // And a gov proposal - // When the contract sends a vote for the proposal - // Then the vote is taken into account - - coord := ibctesting.NewCoordinator(t, 1) - chain := coord.GetChain(ibctesting.GetChainID(1)) - contractAddr := e2e.InstantiateReflectContract(t, chain) - chain.Fund(contractAddr, sdk.NewIntFromUint64(1_000_000_000)) - // a contract with a high delegation amount - delegateMsg := wasmvmtypes.CosmosMsg{ - Staking: &wasmvmtypes.StakingMsg{ - Delegate: &wasmvmtypes.DelegateMsg{ - Validator: sdk.ValAddress(chain.Vals.Validators[0].Address).String(), - Amount: wasmvmtypes.Coin{ - Denom: sdk.DefaultBondDenom, - Amount: "1000000000", - }, - }, - }, - } - e2e.MustExecViaReflectContract(t, chain, contractAddr, delegateMsg) - - signer := chain.SenderAccount.GetAddress().String() - govKeeper, accountKeeper := chain.App.GovKeeper, chain.App.AccountKeeper - communityPoolBalance := chain.Balance(accountKeeper.GetModuleAccount(chain.GetContext(), distributiontypes.ModuleName).GetAddress(), sdk.DefaultBondDenom) - require.False(t, communityPoolBalance.IsZero()) - - initialDeposit := govKeeper.GetParams(chain.GetContext()).MinDeposit - govAcctAddr := govKeeper.GetGovernanceAccount(chain.GetContext()).GetAddress() - - specs := map[string]struct { - vote *wasmvmtypes.VoteMsg - expPass bool - }{ - "yes": { - vote: &wasmvmtypes.VoteMsg{ - Vote: wasmvmtypes.Yes, - }, - expPass: true, - }, - "no": { - vote: &wasmvmtypes.VoteMsg{ - Vote: wasmvmtypes.No, - }, - expPass: false, - }, - "abstain": { - vote: &wasmvmtypes.VoteMsg{ - Vote: wasmvmtypes.Abstain, - }, - expPass: true, - }, - "no with veto": { - vote: &wasmvmtypes.VoteMsg{ - Vote: wasmvmtypes.NoWithVeto, - }, - expPass: false, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - // given a unique recipient - recipientAddr := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address().Bytes()) - // and a new proposal - payloadMsg := &distributiontypes.MsgCommunityPoolSpend{ - Authority: govAcctAddr.String(), - Recipient: recipientAddr.String(), - Amount: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.OneInt())), - } - msg, err := v1.NewMsgSubmitProposal( - []sdk.Msg{payloadMsg}, - initialDeposit, - signer, - "", - "my proposal", - "testing", - ) - require.NoError(t, err) - rsp, gotErr := chain.SendMsgs(msg) - require.NoError(t, gotErr) - require.Len(t, rsp.MsgResponses, 1) - got, ok := rsp.MsgResponses[0].GetCachedValue().(*v1.MsgSubmitProposalResponse) - require.True(t, ok) - propID := got.ProposalId - - // with other delegators voted yes - _, err = chain.SendMsgs(v1.NewMsgVote(chain.SenderAccount.GetAddress(), propID, v1.VoteOption_VOTE_OPTION_YES, "")) - require.NoError(t, err) - - // when contract votes - spec.vote.ProposalId = propID - voteMsg := wasmvmtypes.CosmosMsg{ - Gov: &wasmvmtypes.GovMsg{ - Vote: spec.vote, - }, - } - e2e.MustExecViaReflectContract(t, chain, contractAddr, voteMsg) - - // then proposal executed after voting period - proposal, ok := govKeeper.GetProposal(chain.GetContext(), propID) - require.True(t, ok) - coord.IncrementTimeBy(proposal.VotingEndTime.Sub(chain.GetContext().BlockTime()) + time.Minute) - coord.CommitBlock(chain) - - // and recipient balance updated - recipientBalance := chain.Balance(recipientAddr, sdk.DefaultBondDenom) - if !spec.expPass { - assert.True(t, recipientBalance.IsZero()) - return - } - expBalanceAmount := sdk.NewCoin(sdk.DefaultBondDenom, sdk.OneInt()) - assert.Equal(t, expBalanceAmount.String(), recipientBalance.String()) - }) - } -} diff --git a/tests/e2e/grants_test.go b/tests/e2e/grants_test.go deleted file mode 100644 index 0fb4882..0000000 --- a/tests/e2e/grants_test.go +++ /dev/null @@ -1,119 +0,0 @@ -package e2e_test - -import ( - "fmt" - "testing" - "time" - - errorsmod "cosmossdk.io/errors" - "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/authz" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/tests/e2e" - "github.com/terpnetwork/terp-core/x/wasm/ibctesting" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestGrants(t *testing.T) { - // Given a contract by address A - // And a grant for address B by A created - // When B sends an execute with tokens from A - // Then the grant is executed as defined - // And - // - balance A reduced (on success) - // - balance B not touched - - coord := ibctesting.NewCoordinator(t, 1) - chain := coord.GetChain(ibctesting.GetChainID(1)) - contractAddr := e2e.InstantiateReflectContract(t, chain) - require.NotEmpty(t, contractAddr) - - granterAddr := chain.SenderAccount.GetAddress() - granteePrivKey := secp256k1.GenPrivKey() - granteeAddr := sdk.AccAddress(granteePrivKey.PubKey().Address().Bytes()) - otherPrivKey := secp256k1.GenPrivKey() - otherAddr := sdk.AccAddress(otherPrivKey.PubKey().Address().Bytes()) - - chain.Fund(granteeAddr, sdk.NewInt(1_000_000)) - chain.Fund(otherAddr, sdk.NewInt(1_000_000)) - assert.Equal(t, sdk.NewInt(1_000_000), chain.Balance(granteeAddr, sdk.DefaultBondDenom).Amount) - - myAmount := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(2_000_000)) - - specs := map[string]struct { - limit types.ContractAuthzLimitX - filter types.ContractAuthzFilterX - transferAmount sdk.Coin - senderKey cryptotypes.PrivKey - expErr *errorsmod.Error - }{ - "in limits and filter": { - limit: types.NewMaxFundsLimit(myAmount), - filter: types.NewAllowAllMessagesFilter(), - transferAmount: myAmount, - senderKey: granteePrivKey, - }, - "exceed limits": { - limit: types.NewMaxFundsLimit(myAmount), - filter: types.NewAllowAllMessagesFilter(), - transferAmount: myAmount.Add(sdk.NewCoin(sdk.DefaultBondDenom, sdk.OneInt())), - senderKey: granteePrivKey, - expErr: sdkerrors.ErrUnauthorized, - }, - "not match filter": { - limit: types.NewMaxFundsLimit(myAmount), - filter: types.NewAcceptedMessageKeysFilter("foo"), - transferAmount: sdk.NewCoin(sdk.DefaultBondDenom, sdk.OneInt()), - senderKey: granteePrivKey, - expErr: sdkerrors.ErrUnauthorized, - }, - "non authorized sender address": { // sanity check - testing sdk - limit: types.NewMaxFundsLimit(myAmount), - filter: types.NewAllowAllMessagesFilter(), - senderKey: otherPrivKey, - transferAmount: myAmount, - expErr: authz.ErrNoAuthorizationFound, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - // setup grant - grant, err := types.NewContractGrant(contractAddr, spec.limit, spec.filter) - require.NoError(t, err) - authorization := types.NewContractExecutionAuthorization(*grant) - expiry := time.Now().Add(time.Hour) - grantMsg, err := authz.NewMsgGrant(granterAddr, granteeAddr, authorization, &expiry) - require.NoError(t, err) - _, err = chain.SendMsgs(grantMsg) - require.NoError(t, err) - - granterStartBalance := chain.Balance(granterAddr, sdk.DefaultBondDenom).Amount - - // when - anyValidReflectMsg := []byte(fmt.Sprintf(`{"reflect_msg": {"msgs": [{"bank":{"burn":{"amount":[{"denom":%q, "amount": %q}]}}}]}}`, sdk.DefaultBondDenom, myAmount.Amount.String())) - execMsg := authz.NewMsgExec(spec.senderKey.PubKey().Address().Bytes(), []sdk.Msg{&types.MsgExecuteContract{ - Sender: granterAddr.String(), - Contract: contractAddr.String(), - Msg: anyValidReflectMsg, - Funds: sdk.NewCoins(spec.transferAmount), - }}) - _, gotErr := chain.SendNonDefaultSenderMsgs(spec.senderKey, &execMsg) - - // then - if spec.expErr != nil { - require.True(t, spec.expErr.Is(gotErr)) - assert.Equal(t, sdk.NewInt(1_000_000), chain.Balance(granteeAddr, sdk.DefaultBondDenom).Amount) - assert.Equal(t, granterStartBalance, chain.Balance(granterAddr, sdk.DefaultBondDenom).Amount) - return - } - require.NoError(t, gotErr) - assert.Equal(t, sdk.NewInt(1_000_000), chain.Balance(granteeAddr, sdk.DefaultBondDenom).Amount) - assert.Equal(t, granterStartBalance.Sub(spec.transferAmount.Amount), chain.Balance(granterAddr, sdk.DefaultBondDenom).Amount) - }) - } -} diff --git a/tests/e2e/group_test.go b/tests/e2e/group_test.go deleted file mode 100644 index 1b2fc7e..0000000 --- a/tests/e2e/group_test.go +++ /dev/null @@ -1,71 +0,0 @@ -package e2e_test - -import ( - "testing" - "time" - - "github.com/terpnetwork/terp-core/x/wasm/types" - - "github.com/cometbft/cometbft/libs/rand" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/cosmos/cosmos-sdk/x/group" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/tests/e2e" - "github.com/terpnetwork/terp-core/x/wasm/ibctesting" -) - -func TestGroupWithContract(t *testing.T) { - // Given a group with a contract as only member - // When contract submits a proposal with try_execute - // Then the payload msg is executed - - coord := ibctesting.NewCoordinator(t, 1) - chain := coord.GetChain(ibctesting.GetChainID(1)) - contractAddr := e2e.InstantiateReflectContract(t, chain) - chain.Fund(contractAddr, sdk.NewIntFromUint64(1_000_000_000)) - - members := []group.MemberRequest{ - { - Address: contractAddr.String(), - Weight: "1", - Metadata: "my contract", - }, - } - msg, err := group.NewMsgCreateGroupWithPolicy( - chain.SenderAccount.GetAddress().String(), - members, - "my group", - "my metadata", - false, - group.NewPercentageDecisionPolicy("1", time.Second, 0), - ) - require.NoError(t, err) - rsp, err := chain.SendMsgs(msg) - require.NoError(t, err) - - createRsp := rsp.MsgResponses[0].GetCachedValue().(*group.MsgCreateGroupWithPolicyResponse) - groupID, policyAddr := createRsp.GroupId, sdk.MustAccAddressFromBech32(createRsp.GroupPolicyAddress) - require.NotEmpty(t, groupID) - chain.Fund(policyAddr, sdk.NewIntFromUint64(1_000_000_000)) - // and a proposal submitted - recipientAddr := sdk.AccAddress(rand.Bytes(address.Len)) - - payload := []sdk.Msg{banktypes.NewMsgSend(policyAddr, recipientAddr, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.OneInt())))} - propMsg, err := group.NewMsgSubmitProposal(policyAddr.String(), []string{contractAddr.String()}, payload, "my proposal", group.Exec_EXEC_TRY, "my title", "my description") - require.NoError(t, err) - - rsp = e2e.MustExecViaStargateReflectContract(t, chain, contractAddr, propMsg) - bz := rsp.MsgResponses[0].GetCachedValue().(*types.MsgExecuteContractResponse).Data - var groupRsp group.MsgSubmitProposalResponse - require.NoError(t, chain.Codec.Unmarshal(bz, &groupRsp)) - // require.NotEmpty(t, groupRsp.ProposalId) - - // and coins received - recipientBalance := chain.Balance(recipientAddr, sdk.DefaultBondDenom) - expBalanceAmount := sdk.NewCoin(sdk.DefaultBondDenom, sdk.OneInt()) - assert.Equal(t, expBalanceAmount.String(), recipientBalance.String()) -} diff --git a/tests/e2e/ibc_fees_test.go b/tests/e2e/ibc_fees_test.go deleted file mode 100644 index 685880f..0000000 --- a/tests/e2e/ibc_fees_test.go +++ /dev/null @@ -1,214 +0,0 @@ -package e2e - -import ( - "bytes" - "encoding/base64" - "fmt" - "testing" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - ibcfee "github.com/cosmos/ibc-go/v7/modules/apps/29-fee/types" - ibctransfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" - clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - ibctesting "github.com/cosmos/ibc-go/v7/testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/app" - wasmibctesting "github.com/terpnetwork/terp-core/x/wasm/ibctesting" - wasmtypes "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestIBCFeesTransfer(t *testing.T) { - // scenario: - // given 2 chains - // with an ics-20 channel established - // when an ics-29 fee is attached to an ibc package - // then the relayer's payee is receiving the fee(s) on success - marshaler := app.MakeEncodingConfig().Marshaler - coord := wasmibctesting.NewCoordinator(t, 2) - chainA := coord.GetChain(wasmibctesting.GetChainID(1)) - chainB := coord.GetChain(wasmibctesting.GetChainID(2)) - - actorChainA := sdk.AccAddress(chainA.SenderPrivKey.PubKey().Address()) - actorChainB := sdk.AccAddress(chainB.SenderPrivKey.PubKey().Address()) - receiver := sdk.AccAddress(bytes.Repeat([]byte{1}, address.Len)) - payee := sdk.AccAddress(bytes.Repeat([]byte{2}, address.Len)) - oneToken := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))) - - path := wasmibctesting.NewPath(chainA, chainB) - path.EndpointA.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: ibctransfertypes.PortID, - Version: string(marshaler.MustMarshalJSON(&ibcfee.Metadata{FeeVersion: ibcfee.Version, AppVersion: ibctransfertypes.Version})), - Order: channeltypes.UNORDERED, - } - path.EndpointB.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: ibctransfertypes.PortID, - Version: string(marshaler.MustMarshalJSON(&ibcfee.Metadata{FeeVersion: ibcfee.Version, AppVersion: ibctransfertypes.Version})), - Order: channeltypes.UNORDERED, - } - // with an ics-20 transfer channel setup between both chains - coord.Setup(path) - require.True(t, chainA.App.IBCFeeKeeper.IsFeeEnabled(chainA.GetContext(), ibctransfertypes.PortID, path.EndpointA.ChannelID)) - // and with a payee registered on both chains - _, err := chainA.SendMsgs(ibcfee.NewMsgRegisterPayee(ibctransfertypes.PortID, path.EndpointA.ChannelID, actorChainA.String(), payee.String())) - require.NoError(t, err) - _, err = chainB.SendMsgs(ibcfee.NewMsgRegisterCounterpartyPayee(ibctransfertypes.PortID, path.EndpointB.ChannelID, actorChainB.String(), payee.String())) - require.NoError(t, err) - - // when a transfer package is sent - transferCoin := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1)) - ibcPayloadMsg := ibctransfertypes.NewMsgTransfer(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID, transferCoin, actorChainA.String(), receiver.String(), clienttypes.Height{}, uint64(time.Now().Add(time.Minute).UnixNano()), "testing") - ibcPackageFee := ibcfee.NewFee(oneToken, oneToken, sdk.Coins{}) - feeMsg := ibcfee.NewMsgPayPacketFee(ibcPackageFee, ibctransfertypes.PortID, path.EndpointA.ChannelID, actorChainA.String(), nil) - _, err = chainA.SendMsgs(feeMsg, ibcPayloadMsg) - require.NoError(t, err) - pendingIncentivisedPackages := chainA.App.IBCFeeKeeper.GetIdentifiedPacketFeesForChannel(chainA.GetContext(), ibctransfertypes.PortID, path.EndpointA.ChannelID) - assert.Len(t, pendingIncentivisedPackages, 1) - - // and packages relayed - require.NoError(t, coord.RelayAndAckPendingPackets(path)) - - // then - expBalance := ibctransfertypes.GetTransferCoin(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID, transferCoin.Denom, transferCoin.Amount) - gotBalance := chainB.Balance(receiver, expBalance.Denom) - assert.Equal(t, expBalance.String(), gotBalance.String()) - payeeBalance := chainA.AllBalances(payee) - assert.Equal(t, oneToken.Add(oneToken...).String(), payeeBalance.String()) - - // and with a payee registered for chain B to A - _, err = chainA.SendMsgs(ibcfee.NewMsgRegisterCounterpartyPayee(ibctransfertypes.PortID, path.EndpointA.ChannelID, actorChainA.String(), payee.String())) - require.NoError(t, err) - _, err = chainB.SendMsgs(ibcfee.NewMsgRegisterPayee(ibctransfertypes.PortID, path.EndpointB.ChannelID, actorChainB.String(), payee.String())) - require.NoError(t, err) - - // and transfer from B to A - ibcPayloadMsg = ibctransfertypes.NewMsgTransfer(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID, transferCoin, actorChainB.String(), receiver.String(), clienttypes.Height{}, uint64(time.Now().Add(time.Minute).UnixNano()), "more testing") - ibcPackageFee = ibcfee.NewFee(oneToken, oneToken, sdk.Coins{}) - feeMsg = ibcfee.NewMsgPayPacketFee(ibcPackageFee, ibctransfertypes.PortID, path.EndpointB.ChannelID, actorChainB.String(), nil) - _, err = chainB.SendMsgs(feeMsg, ibcPayloadMsg) - require.NoError(t, err) - pendingIncentivisedPackages = chainB.App.IBCFeeKeeper.GetIdentifiedPacketFeesForChannel(chainB.GetContext(), ibctransfertypes.PortID, path.EndpointB.ChannelID) - assert.Len(t, pendingIncentivisedPackages, 1) - - // when packages relayed - require.NoError(t, coord.RelayAndAckPendingPackets(path)) - - // then - expBalance = ibctransfertypes.GetTransferCoin(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID, transferCoin.Denom, transferCoin.Amount) - gotBalance = chainA.Balance(receiver, expBalance.Denom) - assert.Equal(t, expBalance.String(), gotBalance.String()) - payeeBalance = chainB.AllBalances(payee) - assert.Equal(t, sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(2)).String(), payeeBalance.String()) -} - -func TestIBCFeesWasm(t *testing.T) { - // scenario: - // given 2 chains with cw20-ibc on chain A and native ics20 module on B - // and an ibc channel established - // when an ics-29 fee is attached to an ibc package - // then the relayer's payee is receiving the fee(s) on success - marshaler := app.MakeEncodingConfig().Marshaler - coord := wasmibctesting.NewCoordinator(t, 2) - chainA := coord.GetChain(wasmibctesting.GetChainID(1)) - chainB := coord.GetChain(ibctesting.GetChainID(2)) - actorChainA := sdk.AccAddress(chainA.SenderPrivKey.PubKey().Address()) - actorChainB := sdk.AccAddress(chainB.SenderPrivKey.PubKey().Address()) - - // setup chain A - codeID := chainA.StoreCodeFile("./testdata/cw20_base.wasm.gz").CodeID - - initMsg := []byte(fmt.Sprintf(`{"decimals": 6, "name": "test", "symbol":"ALX", "initial_balances": [{"address": %q,"amount":"100000000"}] }`, actorChainA.String())) - cw20ContractAddr := chainA.InstantiateContract(codeID, initMsg) - - initMsg = []byte(fmt.Sprintf(`{"default_timeout": 360, "gov_contract": %q, "allowlist":[{"contract":%q}]}`, actorChainA.String(), cw20ContractAddr.String())) - codeID = chainA.StoreCodeFile("./testdata/cw20_ics20.wasm.gz").CodeID - ibcContractAddr := chainA.InstantiateContract(codeID, initMsg) - ibcContractPortID := chainA.ContractInfo(ibcContractAddr).IBCPortID - - payee := sdk.AccAddress(bytes.Repeat([]byte{2}, address.Len)) - oneToken := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))) - - path := wasmibctesting.NewPath(chainA, chainB) - path.EndpointA.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: ibcContractPortID, - Version: string(marshaler.MustMarshalJSON(&ibcfee.Metadata{FeeVersion: ibcfee.Version, AppVersion: ibctransfertypes.Version})), - Order: channeltypes.UNORDERED, - } - path.EndpointB.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: ibctransfertypes.PortID, - Version: string(marshaler.MustMarshalJSON(&ibcfee.Metadata{FeeVersion: ibcfee.Version, AppVersion: ibctransfertypes.Version})), - Order: channeltypes.UNORDERED, - } - // with an ics-29 fee enabled channel setup between both chains - coord.Setup(path) - require.True(t, chainA.App.IBCFeeKeeper.IsFeeEnabled(chainA.GetContext(), ibcContractPortID, path.EndpointA.ChannelID)) - require.True(t, chainB.App.IBCFeeKeeper.IsFeeEnabled(chainB.GetContext(), ibctransfertypes.PortID, path.EndpointB.ChannelID)) - // and with a payee registered for A -> B - _, err := chainA.SendMsgs(ibcfee.NewMsgRegisterPayee(ibcContractPortID, path.EndpointA.ChannelID, actorChainA.String(), payee.String())) - require.NoError(t, err) - _, err = chainB.SendMsgs(ibcfee.NewMsgRegisterCounterpartyPayee(ibctransfertypes.PortID, path.EndpointB.ChannelID, actorChainB.String(), payee.String())) - require.NoError(t, err) - - // when a transfer package is sent from ics20 contract on A to B - transfer := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf(`{"channel": %q, "remote_address": %q}`, path.EndpointA.ChannelID, actorChainB.String()))) - exec := []byte(fmt.Sprintf(`{"send":{"contract": %q, "amount": "100", "msg": %q}}`, ibcContractAddr.String(), transfer)) - execMsg := wasmtypes.MsgExecuteContract{ - Sender: actorChainA.String(), - Contract: cw20ContractAddr.String(), - Msg: exec, - } - ibcPackageFee := ibcfee.NewFee(oneToken, oneToken, sdk.Coins{}) - feeMsg := ibcfee.NewMsgPayPacketFee(ibcPackageFee, ibcContractPortID, path.EndpointA.ChannelID, actorChainA.String(), nil) - _, err = chainA.SendMsgs(feeMsg, &execMsg) - require.NoError(t, err) - pendingIncentivisedPackages := chainA.App.IBCFeeKeeper.GetIdentifiedPacketFeesForChannel(chainA.GetContext(), ibcContractPortID, path.EndpointA.ChannelID) - assert.Len(t, pendingIncentivisedPackages, 1) - - // and packages relayed - require.NoError(t, coord.RelayAndAckPendingPackets(path)) - - // then - // on chain A - gotCW20Balance, err := chainA.App.WasmKeeper.QuerySmart(chainA.GetContext(), cw20ContractAddr, []byte(fmt.Sprintf(`{"balance":{"address": %q}}`, actorChainA.String()))) - require.NoError(t, err) - assert.JSONEq(t, `{"balance":"99999900"}`, string(gotCW20Balance)) - payeeBalance := chainA.AllBalances(payee) - assert.Equal(t, sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(2)).String(), payeeBalance.String()) - // and on chain B - pendingIncentivisedPackages = chainA.App.IBCFeeKeeper.GetIdentifiedPacketFeesForChannel(chainA.GetContext(), ibcContractPortID, path.EndpointA.ChannelID) - assert.Len(t, pendingIncentivisedPackages, 0) - expBalance := ibctransfertypes.GetTransferCoin(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID, "cw20:"+cw20ContractAddr.String(), sdk.NewInt(100)) - gotBalance := chainB.Balance(actorChainB, expBalance.Denom) - assert.Equal(t, expBalance.String(), gotBalance.String(), chainB.AllBalances(actorChainB)) - - // and with a payee registered for chain B to A - _, err = chainA.SendMsgs(ibcfee.NewMsgRegisterCounterpartyPayee(ibcContractPortID, path.EndpointA.ChannelID, actorChainA.String(), payee.String())) - require.NoError(t, err) - _, err = chainB.SendMsgs(ibcfee.NewMsgRegisterPayee(ibctransfertypes.PortID, path.EndpointB.ChannelID, actorChainB.String(), payee.String())) - require.NoError(t, err) - - // and when sent back from chain B to A - ibcPayloadMsg := ibctransfertypes.NewMsgTransfer(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID, gotBalance, actorChainB.String(), actorChainA.String(), clienttypes.Height{}, uint64(time.Now().Add(time.Minute).UnixNano()), "even more tests") - ibcPackageFee = ibcfee.NewFee(oneToken, oneToken, sdk.Coins{}) - feeMsg = ibcfee.NewMsgPayPacketFee(ibcPackageFee, ibctransfertypes.PortID, path.EndpointB.ChannelID, actorChainB.String(), nil) - _, err = chainB.SendMsgs(feeMsg, ibcPayloadMsg) - require.NoError(t, err) - pendingIncentivisedPackages = chainB.App.IBCFeeKeeper.GetIdentifiedPacketFeesForChannel(chainB.GetContext(), ibctransfertypes.PortID, path.EndpointB.ChannelID) - assert.Len(t, pendingIncentivisedPackages, 1) - - // when packages relayed - require.NoError(t, coord.RelayAndAckPendingPackets(path)) - - // then - // on chain A - gotCW20Balance, err = chainA.App.WasmKeeper.QuerySmart(chainA.GetContext(), cw20ContractAddr, []byte(fmt.Sprintf(`{"balance":{"address": %q}}`, actorChainA.String()))) - require.NoError(t, err) - assert.JSONEq(t, `{"balance":"100000000"}`, string(gotCW20Balance)) - // and on chain B - payeeBalance = chainB.AllBalances(payee) - assert.Equal(t, sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(2)).String(), payeeBalance.String()) -} diff --git a/tests/e2e/ica_test.go b/tests/e2e/ica_test.go deleted file mode 100644 index c77605b..0000000 --- a/tests/e2e/ica_test.go +++ /dev/null @@ -1,101 +0,0 @@ -package e2e - -import ( - "bytes" - "testing" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/cosmos/gogoproto/proto" - icacontrollertypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/controller/types" - hosttypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/host/types" - icatypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - ibctesting "github.com/cosmos/ibc-go/v7/testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - wasmibctesting "github.com/terpnetwork/terp-core/x/wasm/ibctesting" -) - -func TestICA(t *testing.T) { - // scenario: - // given a host and controller chain - // when an ica is registered on the controller chain - // and the channel is established to the host chain - // then the ICA owner can submit a message via IBC - // to control their account on the host chain - coord := wasmibctesting.NewCoordinator(t, 2) - hostChain := coord.GetChain(ibctesting.GetChainID(1)) - hostParams := hosttypes.NewParams(true, []string{sdk.MsgTypeURL(&banktypes.MsgSend{})}) - hostChain.App.ICAHostKeeper.SetParams(hostChain.GetContext(), hostParams) - - controllerChain := coord.GetChain(ibctesting.GetChainID(2)) - - path := wasmibctesting.NewPath(controllerChain, hostChain) - coord.SetupConnections(path) - - ownerAddr := sdk.AccAddress(controllerChain.SenderPrivKey.PubKey().Address()) - msg := icacontrollertypes.NewMsgRegisterInterchainAccount(path.EndpointA.ConnectionID, ownerAddr.String(), "") - res, err := controllerChain.SendMsgs(msg) - require.NoError(t, err) - chanID, portID, version := parseIBCChannelEvents(t, res) - - // next open channels on both sides - path.EndpointA.ChannelID = chanID - path.EndpointA.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: portID, - Version: version, - Order: channeltypes.ORDERED, - } - path.EndpointB.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: icatypes.HostPortID, - Version: icatypes.Version, - Order: channeltypes.ORDERED, - } - coord.CreateChannels(path) - - // assert ICA exists on controller - icaRsp, err := controllerChain.App.ICAControllerKeeper.InterchainAccount(sdk.WrapSDKContext(controllerChain.GetContext()), &icacontrollertypes.QueryInterchainAccountRequest{ - Owner: ownerAddr.String(), - ConnectionId: path.EndpointA.ConnectionID, - }) - require.NoError(t, err) - icaAddr := sdk.MustAccAddressFromBech32(icaRsp.GetAddress()) - hostChain.Fund(icaAddr, sdk.NewInt(1_000)) - - // submit a tx - targetAddr := sdk.AccAddress(bytes.Repeat([]byte{1}, address.Len)) - sendCoin := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)) - payloadMsg := banktypes.NewMsgSend(icaAddr, targetAddr, sdk.NewCoins(sendCoin)) - rawPayloadData, err := icatypes.SerializeCosmosTx(controllerChain.Codec, []proto.Message{payloadMsg}) - require.NoError(t, err) - payloadPacket := icatypes.InterchainAccountPacketData{ - Type: icatypes.EXECUTE_TX, - Data: rawPayloadData, - Memo: "testing", - } - relativeTimeout := uint64(time.Minute.Nanoseconds()) // note this is in nanoseconds - msgSendTx := icacontrollertypes.NewMsgSendTx(ownerAddr.String(), path.EndpointA.ConnectionID, relativeTimeout, payloadPacket) - _, err = controllerChain.SendMsgs(msgSendTx) - require.NoError(t, err) - - assert.Equal(t, 1, len(controllerChain.PendingSendPackets)) - require.NoError(t, coord.RelayAndAckPendingPackets(path)) - - gotBalance := hostChain.Balance(targetAddr, sdk.DefaultBondDenom) - assert.Equal(t, sendCoin.String(), gotBalance.String()) -} - -func parseIBCChannelEvents(t *testing.T, res *sdk.Result) (string, string, string) { - t.Helper() - chanID, err := ibctesting.ParseChannelIDFromEvents(res.GetEvents()) - require.NoError(t, err) - portID, err := wasmibctesting.ParsePortIDFromEvents(res.GetEvents()) - require.NoError(t, err) - version, err := wasmibctesting.ParseChannelVersionFromEvents(res.GetEvents()) - require.NoError(t, err) - return chanID, portID, version -} diff --git a/tests/e2e/reflect_helper.go b/tests/e2e/reflect_helper.go deleted file mode 100644 index 1977f82..0000000 --- a/tests/e2e/reflect_helper.go +++ /dev/null @@ -1,68 +0,0 @@ -package e2e - -import ( - "encoding/json" - "testing" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/ibctesting" - "github.com/terpnetwork/terp-core/x/wasm/keeper/testdata" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// InstantiateReflectContract store and instantiate a reflect contract instance -func InstantiateReflectContract(t *testing.T, chain *ibctesting.TestChain) sdk.AccAddress { - codeID := chain.StoreCodeFile("../../x/wasm/keeper/testdata/reflect_1_1.wasm").CodeID - contractAddr := chain.InstantiateContract(codeID, []byte(`{}`)) - require.NotEmpty(t, contractAddr) - return contractAddr -} - -// MustExecViaReflectContract submit execute message to send payload to reflect contract -func MustExecViaReflectContract(t *testing.T, chain *ibctesting.TestChain, contractAddr sdk.AccAddress, msgs ...wasmvmtypes.CosmosMsg) *sdk.Result { - rsp, err := ExecViaReflectContract(t, chain, contractAddr, msgs) - require.NoError(t, err) - return rsp -} - -type sdkMessageType interface { - codec.ProtoMarshaler - sdk.Msg -} - -func MustExecViaStargateReflectContract[T sdkMessageType](t *testing.T, chain *ibctesting.TestChain, contractAddr sdk.AccAddress, msgs ...T) *sdk.Result { - vmMsgs := make([]wasmvmtypes.CosmosMsg, len(msgs)) - for i, m := range msgs { - bz, err := chain.Codec.Marshal(m) - require.NoError(t, err) - vmMsgs[i] = wasmvmtypes.CosmosMsg{ - Stargate: &wasmvmtypes.StargateMsg{ - TypeURL: sdk.MsgTypeURL(m), - Value: bz, - }, - } - } - rsp, err := ExecViaReflectContract(t, chain, contractAddr, vmMsgs) - require.NoError(t, err) - return rsp -} - -// ExecViaReflectContract submit execute message to send payload to reflect contract -func ExecViaReflectContract(t *testing.T, chain *ibctesting.TestChain, contractAddr sdk.AccAddress, msgs []wasmvmtypes.CosmosMsg) (*sdk.Result, error) { - require.NotEmpty(t, msgs) - reflectSend := testdata.ReflectHandleMsg{ - Reflect: &testdata.ReflectPayload{Msgs: msgs}, - } - reflectSendBz, err := json.Marshal(reflectSend) - require.NoError(t, err) - execMsg := &types.MsgExecuteContract{ - Sender: chain.SenderAccount.GetAddress().String(), - Contract: contractAddr.String(), - Msg: reflectSendBz, - } - return chain.SendMsgs(execMsg) -} diff --git a/tests/e2e/testdata/cw20_base.wasm.gz b/tests/e2e/testdata/cw20_base.wasm.gz deleted file mode 100644 index 7745e80..0000000 Binary files a/tests/e2e/testdata/cw20_base.wasm.gz and /dev/null differ diff --git a/tests/e2e/testdata/cw20_ics20.wasm.gz b/tests/e2e/testdata/cw20_ics20.wasm.gz deleted file mode 100644 index 07517a2..0000000 Binary files a/tests/e2e/testdata/cw20_ics20.wasm.gz and /dev/null differ diff --git a/x/ibchooks/.cargo/config b/x/ibchooks/.cargo/config new file mode 100644 index 0000000..946af0f --- /dev/null +++ b/x/ibchooks/.cargo/config @@ -0,0 +1,2 @@ +[alias] +wasm = "build --release --lib --target wasm32-unknown-unknown" diff --git a/x/ibchooks/README.md b/x/ibchooks/README.md new file mode 100644 index 0000000..1955c92 --- /dev/null +++ b/x/ibchooks/README.md @@ -0,0 +1,185 @@ +# IBC-hooks + +## Wasm Hooks + +The wasm hook is an IBC middleware which is used to allow ICS-20 token transfers to initiate contract calls. +This allows cross-chain contract calls, that involve token movement. +This is useful for a variety of usecases. +One of primary importance is cross-chain swaps, which is an extremely powerful primitive. + +The mechanism enabling this is a `memo` field on every ICS20 transfer packet as of [IBC v3.4.0](https://medium.com/the-interchain-foundation/moving-beyond-simple-token-transfers-d42b2b1dc29b). +Wasm hooks is an IBC middleware that parses an ICS20 transfer, and if the `memo` field is of a particular form, executes a wasm contract call. We now detail the `memo` format for `wasm` contract calls, and the execution guarantees provided. + +### Cosmwasm Contract Execution Format + +Before we dive into the IBC metadata format, we show the cosmwasm execute message format, so the reader has a sense of what are the fields we need to be setting in. +The cosmwasm `MsgExecuteContract` is defined [here](https://github.com/CosmWasm/wasmd/blob/4fe2fbc8f322efdaf187e2e5c99ce32fd1df06f0/x/wasm/types/tx.pb.go#L340-L349 +) as the following type: + +```go +type MsgExecuteContract struct { + // Sender is the that actor that signed the messages + Sender string + // Contract is the address of the smart contract + Contract string + // Msg json encoded message to be passed to the contract + Msg RawContractMessage + // Funds coins that are transferred to the contract on execution + Funds sdk.Coins +} +``` + +So we detail where we want to get each of these fields from: + +* Sender: We cannot trust the sender of an IBC packet, the counterparty chain has full ability to lie about it. +We cannot risk this sender being confused for a particular user or module address on Osmosis. +So we replace the sender with an account to represent the sender prefixed by the channel and a wasm module prefix. +This is done by setting the sender to `Bech32(Hash("ibc-wasm-hook-intermediary" || channelID || sender))`, where the channelId is the channel id on the local chain. +* Contract: This field should be directly obtained from the ICS-20 packet metadata +* Msg: This field should be directly obtained from the ICS-20 packet metadata. +* Funds: This field is set to the amount of funds being sent over in the ICS 20 packet. One detail is that the denom in the packet is the counterparty chains representation of the denom, so we have to translate it to Osmosis' representation. + +So our constructed cosmwasm message that we execute will look like: + +```go +msg := MsgExecuteContract{ + // Sender is the that actor that signed the messages + Sender: "osmo1-hash-of-channel-and-sender", + // Contract is the address of the smart contract + Contract: packet.data.memo["wasm"]["ContractAddress"], + // Msg json encoded message to be passed to the contract + Msg: packet.data.memo["wasm"]["Msg"], + // Funds coins that are transferred to the contract on execution + Funds: sdk.NewCoin{Denom: ibc.ConvertSenderDenomToLocalDenom(packet.data.Denom), Amount: packet.data.Amount} +``` + +### ICS20 packet structure + +So given the details above, we propogate the implied ICS20 packet data structure. +ICS20 is JSON native, so we use JSON for the memo format. + +```json +{ + //... other ibc fields that we don't care about + "data":{ + "denom": "denom on counterparty chain (e.g. uatom)", // will be transformed to the local denom (ibc/...) + "amount": "1000", + "sender": "addr on counterparty chain", // will be transformed + "receiver": "contract addr or blank", + "memo": { + "wasm": { + "contract": "osmo1contractAddr", + "msg": { + "raw_message_fields": "raw_message_data", + } + } + } + } +} +``` + +An ICS20 packet is formatted correctly for wasmhooks iff the following all hold: + +* `memo` is not blank +* `memo` is valid JSON +* `memo` has at least one key, with value `"wasm"` +* `memo["wasm"]` has exactly two entries, `"contract"` and `"msg"` +* `memo["wasm"]["msg"]` is a valid JSON object +* `receiver == "" || receiver == memo["wasm"]["contract"]` + +We consider an ICS20 packet as directed towards wasmhooks iff all of the following hold: + +* `memo` is not blank +* `memo` is valid JSON +* `memo` has at least one key, with name `"wasm"` + +If an ICS20 packet is not directed towards wasmhooks, wasmhooks doesn't do anything. +If an ICS20 packet is directed towards wasmhooks, and is formated incorrectly, then wasmhooks returns an error. + +### Execution flow + +Pre wasm hooks: + +* Ensure the incoming IBC packet is cryptogaphically valid +* Ensure the incoming IBC packet is not timed out. + +In Wasm hooks, pre packet execution: + +* Ensure the packet is correctly formatted (as defined above) +* Edit the receiver to be the hardcoded IBC module account + +In wasm hooks, post packet execution: + +* Construct wasm message as defined before +* Execute wasm message +* if wasm message has error, return ErrAck +* otherwise continue through middleware + +## Ack callbacks + +A contract that sends an IBC transfer, may need to listen for the ACK from that packet. To allow +contracts to listen on the ack of specific packets, we provide Ack callbacks. + +### Design + +The sender of an IBC transfer packet may specify a callback for when the ack of that packet is received in the memo +field of the transfer packet. + +Crucially, _only_ the IBC packet sender can set the callback. + +### Use case + +The crosschain swaps implementation sends an IBC transfer. If the transfer were to fail, we want to allow the sender +to be able to retrieve their funds (which would otherwise be stuck in the contract). To do this, we allow users to +retrieve the funds after the timeout has passed, but without the ack information, we cannot guarantee that the send +hasn't failed (i.e.: returned an error ack notifying that the receiving change didn't accept it) + +### Implementation + +#### Callback information in memo + +For the callback to be processed, the transfer packet's memo should contain the following in its JSON: + +`{"ibc_callback": "osmo1contractAddr"}` + +The wasm hooks will keep the mapping from the packet's channel and sequence to the contract in storage. When an ack is +received, it will notify the specified contract via a sudo message. + +#### Interface for receiving the Acks and Timeouts + +The contract that awaits the callback should implement the following interface for a sudo message: + +```rust +#[cw_serde] +pub enum IBCLifecycleComplete { + #[serde(rename = "ibc_ack")] + IBCAck { + /// The source channel (osmosis side) of the IBC packet + channel: String, + /// The sequence number that the packet was sent with + sequence: u64, + /// String encoded version of the ack as seen by OnAcknowledgementPacket(..) + ack: String, + /// Weather an ack is a success of failure according to the transfer spec + success: bool, + }, + #[serde(rename = "ibc_timeout")] + IBCTimeout { + /// The source channel (osmosis side) of the IBC packet + channel: String, + /// The sequence number that the packet was sent with + sequence: u64, + }, +} + +/// Message type for `sudo` entry_point +#[cw_serde] +pub enum SudoMsg { + #[serde(rename = "ibc_lifecycle_complete")] + IBCLifecycleComplete(IBCLifecycleComplete), +} +``` + +# Testing strategy + +See go tests. \ No newline at end of file diff --git a/x/ibchooks/client/cli/query.go b/x/ibchooks/client/cli/query.go new file mode 100644 index 0000000..4c5ec97 --- /dev/null +++ b/x/ibchooks/client/cli/query.go @@ -0,0 +1,76 @@ +package cli + +import ( + "fmt" + "strings" + + "github.com/spf13/cobra" + + "github.com/cosmos/cosmos-sdk/client/flags" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/version" + + "github.com/terpnetwork/terp-core/v2/x/ibchooks/keeper" + "github.com/terpnetwork/terp-core/v2/x/ibchooks/types" +) + +func indexRunCmd(cmd *cobra.Command, _ []string) error { + usageTemplate := `Usage:{{if .HasAvailableSubCommands}} + {{.CommandPath}} [command]{{end}} + +{{if .HasAvailableSubCommands}}Available Commands:{{range .Commands}}{{if .IsAvailableCommand}} + {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}} + +Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}} +` + cmd.SetUsageTemplate(usageTemplate) + return cmd.Help() +} + +// GetQueryCmd returns the cli query commands for this module. +func GetQueryCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: types.ModuleName, + Short: fmt.Sprintf("Querying commands for the %s module", types.ModuleName), + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: indexRunCmd, + } + + cmd.AddCommand( + GetCmdWasmSender(), + ) + return cmd +} + +// GetCmdPoolParams return pool params. +func GetCmdWasmSender() *cobra.Command { + cmd := &cobra.Command{ + Use: "wasm-sender ", + Short: "Generate the local address for a wasm hooks sender", + Long: strings.TrimSpace( + fmt.Sprintf(`Generate the local address for a wasm hooks sender. +Example: +$ %s query ibc-hooks wasm-hooks-sender channel-42 terp12smx2wdlyttvyzvzg54y2vnqwq2qjatencyhtn +`, + version.AppName, + ), + ), + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + channelID := args[0] + originalSender := args[1] + prefix := sdk.GetConfig().GetBech32AccountAddrPrefix() + senderBech32, err := keeper.DeriveIntermediateSender(channelID, originalSender, prefix) + if err != nil { + return err + } + fmt.Println(senderBech32) + return nil + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} diff --git a/x/ibchooks/hooks.go b/x/ibchooks/hooks.go new file mode 100644 index 0000000..b9f76de --- /dev/null +++ b/x/ibchooks/hooks.go @@ -0,0 +1,145 @@ +package ibchooks + +import ( + // ibc-go + clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" + channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" + ibcexported "github.com/cosmos/ibc-go/v7/modules/core/exported" + + // external libraries + sdk "github.com/cosmos/cosmos-sdk/types" + capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" +) + +type Hooks interface{} + +type OnChanOpenInitOverrideHooks interface { + OnChanOpenInitOverride(im IBCMiddleware, ctx sdk.Context, order channeltypes.Order, connectionHops []string, portID string, channelID string, channelCap *capabilitytypes.Capability, counterparty channeltypes.Counterparty, version string) (string, error) +} +type OnChanOpenInitBeforeHooks interface { + OnChanOpenInitBeforeHook(ctx sdk.Context, order channeltypes.Order, connectionHops []string, portID string, channelID string, channelCap *capabilitytypes.Capability, counterparty channeltypes.Counterparty, version string) +} +type OnChanOpenInitAfterHooks interface { + OnChanOpenInitAfterHook(ctx sdk.Context, order channeltypes.Order, connectionHops []string, portID string, channelID string, channelCap *capabilitytypes.Capability, counterparty channeltypes.Counterparty, version string, finalVersion string, err error) +} + +// OnChanOpenTry Hooks +type OnChanOpenTryOverrideHooks interface { + OnChanOpenTryOverride(im IBCMiddleware, ctx sdk.Context, order channeltypes.Order, connectionHops []string, portID, channelID string, channelCap *capabilitytypes.Capability, counterparty channeltypes.Counterparty, counterpartyVersion string) (string, error) +} +type OnChanOpenTryBeforeHooks interface { + OnChanOpenTryBeforeHook(ctx sdk.Context, order channeltypes.Order, connectionHops []string, portID, channelID string, channelCap *capabilitytypes.Capability, counterparty channeltypes.Counterparty, counterpartyVersion string) +} +type OnChanOpenTryAfterHooks interface { + OnChanOpenTryAfterHook(ctx sdk.Context, order channeltypes.Order, connectionHops []string, portID, channelID string, channelCap *capabilitytypes.Capability, counterparty channeltypes.Counterparty, counterpartyVersion string, version string, err error) +} + +// OnChanOpenAck Hooks +type OnChanOpenAckOverrideHooks interface { + OnChanOpenAckOverride(im IBCMiddleware, ctx sdk.Context, portID, channelID string, counterpartyChannelID string, counterpartyVersion string) error +} +type OnChanOpenAckBeforeHooks interface { + OnChanOpenAckBeforeHook(ctx sdk.Context, portID, channelID string, counterpartyChannelID string, counterpartyVersion string) +} +type OnChanOpenAckAfterHooks interface { + OnChanOpenAckAfterHook(ctx sdk.Context, portID, channelID string, counterpartyChannelID string, counterpartyVersion string, err error) +} + +// OnChanOpenConfirm Hooks +type OnChanOpenConfirmOverrideHooks interface { + OnChanOpenConfirmOverride(im IBCMiddleware, ctx sdk.Context, portID, channelID string) error +} +type OnChanOpenConfirmBeforeHooks interface { + OnChanOpenConfirmBeforeHook(ctx sdk.Context, portID, channelID string) +} +type OnChanOpenConfirmAfterHooks interface { + OnChanOpenConfirmAfterHook(ctx sdk.Context, portID, channelID string, err error) +} + +// OnChanCloseInit Hooks +type OnChanCloseInitOverrideHooks interface { + OnChanCloseInitOverride(im IBCMiddleware, ctx sdk.Context, portID, channelID string) error +} +type OnChanCloseInitBeforeHooks interface { + OnChanCloseInitBeforeHook(ctx sdk.Context, portID, channelID string) +} +type OnChanCloseInitAfterHooks interface { + OnChanCloseInitAfterHook(ctx sdk.Context, portID, channelID string, err error) +} + +// OnChanCloseConfirm Hooks +type OnChanCloseConfirmOverrideHooks interface { + OnChanCloseConfirmOverride(im IBCMiddleware, ctx sdk.Context, portID, channelID string) error +} +type OnChanCloseConfirmBeforeHooks interface { + OnChanCloseConfirmBeforeHook(ctx sdk.Context, portID, channelID string) +} +type OnChanCloseConfirmAfterHooks interface { + OnChanCloseConfirmAfterHook(ctx sdk.Context, portID, channelID string, err error) +} + +// OnRecvPacket Hooks +type OnRecvPacketOverrideHooks interface { + OnRecvPacketOverride(im IBCMiddleware, ctx sdk.Context, packet channeltypes.Packet, relayer sdk.AccAddress) ibcexported.Acknowledgement +} +type OnRecvPacketBeforeHooks interface { + OnRecvPacketBeforeHook(ctx sdk.Context, packet channeltypes.Packet, relayer sdk.AccAddress) +} +type OnRecvPacketAfterHooks interface { + OnRecvPacketAfterHook(ctx sdk.Context, packet channeltypes.Packet, relayer sdk.AccAddress, ack ibcexported.Acknowledgement) +} + +// OnAcknowledgementPacket Hooks +type OnAcknowledgementPacketOverrideHooks interface { + OnAcknowledgementPacketOverride(im IBCMiddleware, ctx sdk.Context, packet channeltypes.Packet, acknowledgement []byte, relayer sdk.AccAddress) error +} +type OnAcknowledgementPacketBeforeHooks interface { + OnAcknowledgementPacketBeforeHook(ctx sdk.Context, packet channeltypes.Packet, acknowledgement []byte, relayer sdk.AccAddress) +} +type OnAcknowledgementPacketAfterHooks interface { + OnAcknowledgementPacketAfterHook(ctx sdk.Context, packet channeltypes.Packet, acknowledgement []byte, relayer sdk.AccAddress, err error) +} + +// OnTimeoutPacket Hooks +type OnTimeoutPacketOverrideHooks interface { + OnTimeoutPacketOverride(im IBCMiddleware, ctx sdk.Context, packet channeltypes.Packet, relayer sdk.AccAddress) error +} +type OnTimeoutPacketBeforeHooks interface { + OnTimeoutPacketBeforeHook(ctx sdk.Context, packet channeltypes.Packet, relayer sdk.AccAddress) +} +type OnTimeoutPacketAfterHooks interface { + OnTimeoutPacketAfterHook(ctx sdk.Context, packet channeltypes.Packet, relayer sdk.AccAddress, err error) +} + +// SendPacket Hooks +type SendPacketOverrideHooks interface { + SendPacketOverride(i ICS4Middleware, ctx sdk.Context, chanCap *capabilitytypes.Capability, sourcePort string, sourceChannel string, timeoutHeight clienttypes.Height, timeoutTimestamp uint64, data []byte) (uint64, error) +} +type SendPacketBeforeHooks interface { + SendPacketBeforeHook(ctx sdk.Context, chanCap *capabilitytypes.Capability, sourcePort string, sourceChannel string, timeoutHeight clienttypes.Height, timeoutTimestamp uint64, data []byte) +} +type SendPacketAfterHooks interface { + SendPacketAfterHook(ctx sdk.Context, chanCap *capabilitytypes.Capability, sourcePort string, sourceChannel string, timeoutHeight clienttypes.Height, timeoutTimestamp uint64, data []byte, err error) +} + +// WriteAcknowledgement Hooks +type WriteAcknowledgementOverrideHooks interface { + WriteAcknowledgementOverride(i ICS4Middleware, ctx sdk.Context, chanCap *capabilitytypes.Capability, packet ibcexported.PacketI, ack ibcexported.Acknowledgement) error +} +type WriteAcknowledgementBeforeHooks interface { + WriteAcknowledgementBeforeHook(ctx sdk.Context, chanCap *capabilitytypes.Capability, packet ibcexported.PacketI, ack ibcexported.Acknowledgement) +} +type WriteAcknowledgementAfterHooks interface { + WriteAcknowledgementAfterHook(ctx sdk.Context, chanCap *capabilitytypes.Capability, packet ibcexported.PacketI, ack ibcexported.Acknowledgement, err error) +} + +// GetAppVersion Hooks +type GetAppVersionOverrideHooks interface { + GetAppVersionOverride(i ICS4Middleware, ctx sdk.Context, portID, channelID string) (string, bool) +} +type GetAppVersionBeforeHooks interface { + GetAppVersionBeforeHook(ctx sdk.Context, portID, channelID string) +} +type GetAppVersionAfterHooks interface { + GetAppVersionAfterHook(ctx sdk.Context, portID, channelID string, result string, success bool) +} diff --git a/x/ibchooks/ibc_module.go b/x/ibchooks/ibc_module.go new file mode 100644 index 0000000..1ba3ba2 --- /dev/null +++ b/x/ibchooks/ibc_module.go @@ -0,0 +1,262 @@ +package ibchooks + +import ( + // ibc-go + clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" + channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" + porttypes "github.com/cosmos/ibc-go/v7/modules/core/05-port/types" + ibcexported "github.com/cosmos/ibc-go/v7/modules/core/exported" + + // external libraries + sdk "github.com/cosmos/cosmos-sdk/types" + capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" +) + +var _ porttypes.Middleware = &IBCMiddleware{} + +type IBCMiddleware struct { + App porttypes.IBCModule + ICS4Middleware *ICS4Middleware +} + +func NewIBCMiddleware(app porttypes.IBCModule, ics4 *ICS4Middleware) IBCMiddleware { + return IBCMiddleware{ + App: app, + ICS4Middleware: ics4, + } +} + +// OnChanOpenInit implements the IBCMiddleware interface +func (im IBCMiddleware) OnChanOpenInit( + ctx sdk.Context, + order channeltypes.Order, + connectionHops []string, + portID string, + channelID string, + channelCap *capabilitytypes.Capability, + counterparty channeltypes.Counterparty, + version string, +) (string, error) { + if hook, ok := im.ICS4Middleware.Hooks.(OnChanOpenInitOverrideHooks); ok { + return hook.OnChanOpenInitOverride(im, ctx, order, connectionHops, portID, channelID, channelCap, counterparty, version) + } + + if hook, ok := im.ICS4Middleware.Hooks.(OnChanOpenInitBeforeHooks); ok { + hook.OnChanOpenInitBeforeHook(ctx, order, connectionHops, portID, channelID, channelCap, counterparty, version) + } + + finalVersion, err := im.App.OnChanOpenInit(ctx, order, connectionHops, portID, channelID, channelCap, counterparty, version) + + if hook, ok := im.ICS4Middleware.Hooks.(OnChanOpenInitAfterHooks); ok { + hook.OnChanOpenInitAfterHook(ctx, order, connectionHops, portID, channelID, channelCap, counterparty, version, finalVersion, err) + } + return version, err +} + +// OnChanOpenTry implements the IBCMiddleware interface +func (im IBCMiddleware) OnChanOpenTry( + ctx sdk.Context, + order channeltypes.Order, + connectionHops []string, + portID, + channelID string, + channelCap *capabilitytypes.Capability, + counterparty channeltypes.Counterparty, + counterpartyVersion string, +) (string, error) { + if hook, ok := im.ICS4Middleware.Hooks.(OnChanOpenTryOverrideHooks); ok { + return hook.OnChanOpenTryOverride(im, ctx, order, connectionHops, portID, channelID, channelCap, counterparty, counterpartyVersion) + } + + if hook, ok := im.ICS4Middleware.Hooks.(OnChanOpenTryBeforeHooks); ok { + hook.OnChanOpenTryBeforeHook(ctx, order, connectionHops, portID, channelID, channelCap, counterparty, counterpartyVersion) + } + + version, err := im.App.OnChanOpenTry(ctx, order, connectionHops, portID, channelID, channelCap, counterparty, counterpartyVersion) + + if hook, ok := im.ICS4Middleware.Hooks.(OnChanOpenTryAfterHooks); ok { + hook.OnChanOpenTryAfterHook(ctx, order, connectionHops, portID, channelID, channelCap, counterparty, counterpartyVersion, version, err) + } + return version, err +} + +// OnChanOpenAck implements the IBCMiddleware interface +func (im IBCMiddleware) OnChanOpenAck( + ctx sdk.Context, + portID, + channelID string, + counterpartyChannelID string, + counterpartyVersion string, +) error { + if hook, ok := im.ICS4Middleware.Hooks.(OnChanOpenAckOverrideHooks); ok { + return hook.OnChanOpenAckOverride(im, ctx, portID, channelID, counterpartyChannelID, counterpartyVersion) + } + + if hook, ok := im.ICS4Middleware.Hooks.(OnChanOpenAckBeforeHooks); ok { + hook.OnChanOpenAckBeforeHook(ctx, portID, channelID, counterpartyChannelID, counterpartyVersion) + } + err := im.App.OnChanOpenAck(ctx, portID, channelID, counterpartyChannelID, counterpartyVersion) + if hook, ok := im.ICS4Middleware.Hooks.(OnChanOpenAckAfterHooks); ok { + hook.OnChanOpenAckAfterHook(ctx, portID, channelID, counterpartyChannelID, counterpartyVersion, err) + } + + return err +} + +// OnChanOpenConfirm implements the IBCMiddleware interface +func (im IBCMiddleware) OnChanOpenConfirm( + ctx sdk.Context, + portID, + channelID string, +) error { + if hook, ok := im.ICS4Middleware.Hooks.(OnChanOpenConfirmOverrideHooks); ok { + return hook.OnChanOpenConfirmOverride(im, ctx, portID, channelID) + } + + if hook, ok := im.ICS4Middleware.Hooks.(OnChanOpenConfirmBeforeHooks); ok { + hook.OnChanOpenConfirmBeforeHook(ctx, portID, channelID) + } + err := im.App.OnChanOpenConfirm(ctx, portID, channelID) + if hook, ok := im.ICS4Middleware.Hooks.(OnChanOpenConfirmAfterHooks); ok { + hook.OnChanOpenConfirmAfterHook(ctx, portID, channelID, err) + } + return err +} + +// OnChanCloseInit implements the IBCMiddleware interface +func (im IBCMiddleware) OnChanCloseInit( + ctx sdk.Context, + portID, + channelID string, +) error { + // Here we can remove the limits when a new channel is closed. For now, they can remove them manually on the contract + if hook, ok := im.ICS4Middleware.Hooks.(OnChanCloseInitOverrideHooks); ok { + return hook.OnChanCloseInitOverride(im, ctx, portID, channelID) + } + + if hook, ok := im.ICS4Middleware.Hooks.(OnChanCloseInitBeforeHooks); ok { + hook.OnChanCloseInitBeforeHook(ctx, portID, channelID) + } + err := im.App.OnChanCloseInit(ctx, portID, channelID) + if hook, ok := im.ICS4Middleware.Hooks.(OnChanCloseInitAfterHooks); ok { + hook.OnChanCloseInitAfterHook(ctx, portID, channelID, err) + } + + return err +} + +// OnChanCloseConfirm implements the IBCMiddleware interface +func (im IBCMiddleware) OnChanCloseConfirm( + ctx sdk.Context, + portID, + channelID string, +) error { + // Here we can remove the limits when a new channel is closed. For now, they can remove them manually on the contract + if hook, ok := im.ICS4Middleware.Hooks.(OnChanCloseConfirmOverrideHooks); ok { + return hook.OnChanCloseConfirmOverride(im, ctx, portID, channelID) + } + + if hook, ok := im.ICS4Middleware.Hooks.(OnChanCloseConfirmBeforeHooks); ok { + hook.OnChanCloseConfirmBeforeHook(ctx, portID, channelID) + } + err := im.App.OnChanCloseConfirm(ctx, portID, channelID) + if hook, ok := im.ICS4Middleware.Hooks.(OnChanCloseConfirmAfterHooks); ok { + hook.OnChanCloseConfirmAfterHook(ctx, portID, channelID, err) + } + + return err +} + +// OnRecvPacket implements the IBCMiddleware interface +func (im IBCMiddleware) OnRecvPacket( + ctx sdk.Context, + packet channeltypes.Packet, + relayer sdk.AccAddress, +) ibcexported.Acknowledgement { + if hook, ok := im.ICS4Middleware.Hooks.(OnRecvPacketOverrideHooks); ok { + return hook.OnRecvPacketOverride(im, ctx, packet, relayer) + } + + if hook, ok := im.ICS4Middleware.Hooks.(OnRecvPacketBeforeHooks); ok { + hook.OnRecvPacketBeforeHook(ctx, packet, relayer) + } + + ack := im.App.OnRecvPacket(ctx, packet, relayer) + + if hook, ok := im.ICS4Middleware.Hooks.(OnRecvPacketAfterHooks); ok { + hook.OnRecvPacketAfterHook(ctx, packet, relayer, ack) + } + + return ack +} + +// OnAcknowledgementPacket implements the IBCMiddleware interface +func (im IBCMiddleware) OnAcknowledgementPacket( + ctx sdk.Context, + packet channeltypes.Packet, + acknowledgement []byte, + relayer sdk.AccAddress, +) error { + if hook, ok := im.ICS4Middleware.Hooks.(OnAcknowledgementPacketOverrideHooks); ok { + return hook.OnAcknowledgementPacketOverride(im, ctx, packet, acknowledgement, relayer) + } + if hook, ok := im.ICS4Middleware.Hooks.(OnAcknowledgementPacketBeforeHooks); ok { + hook.OnAcknowledgementPacketBeforeHook(ctx, packet, acknowledgement, relayer) + } + + err := im.App.OnAcknowledgementPacket(ctx, packet, acknowledgement, relayer) + + if hook, ok := im.ICS4Middleware.Hooks.(OnAcknowledgementPacketAfterHooks); ok { + hook.OnAcknowledgementPacketAfterHook(ctx, packet, acknowledgement, relayer, err) + } + + return err +} + +// OnTimeoutPacket implements the IBCMiddleware interface +func (im IBCMiddleware) OnTimeoutPacket( + ctx sdk.Context, + packet channeltypes.Packet, + relayer sdk.AccAddress, +) error { + if hook, ok := im.ICS4Middleware.Hooks.(OnTimeoutPacketOverrideHooks); ok { + return hook.OnTimeoutPacketOverride(im, ctx, packet, relayer) + } + + if hook, ok := im.ICS4Middleware.Hooks.(OnTimeoutPacketBeforeHooks); ok { + hook.OnTimeoutPacketBeforeHook(ctx, packet, relayer) + } + err := im.App.OnTimeoutPacket(ctx, packet, relayer) + if hook, ok := im.ICS4Middleware.Hooks.(OnTimeoutPacketAfterHooks); ok { + hook.OnTimeoutPacketAfterHook(ctx, packet, relayer, err) + } + + return err +} + +// SendPacket implements the ICS4 Wrapper interface +func (im IBCMiddleware) SendPacket( + ctx sdk.Context, + chanCap *capabilitytypes.Capability, + sourcePort string, + sourceChannel string, + timeoutHeight clienttypes.Height, + timeoutTimestamp uint64, + data []byte, +) (uint64, error) { + return im.ICS4Middleware.SendPacket(ctx, chanCap, sourcePort, sourceChannel, timeoutHeight, timeoutTimestamp, data) +} + +// WriteAcknowledgement implements the ICS4 Wrapper interface +func (im IBCMiddleware) WriteAcknowledgement( + ctx sdk.Context, + chanCap *capabilitytypes.Capability, + packet ibcexported.PacketI, + ack ibcexported.Acknowledgement, +) error { + return im.ICS4Middleware.WriteAcknowledgement(ctx, chanCap, packet, ack) +} + +func (im IBCMiddleware) GetAppVersion(ctx sdk.Context, portID, channelID string) (string, bool) { + return im.ICS4Middleware.GetAppVersion(ctx, portID, channelID) +} diff --git a/x/ibchooks/ics4_middleware.go b/x/ibchooks/ics4_middleware.go new file mode 100644 index 0000000..ce60c21 --- /dev/null +++ b/x/ibchooks/ics4_middleware.go @@ -0,0 +1,78 @@ +package ibchooks + +import ( + // ibc-go + clienttypes "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" + + // external libraries + sdk "github.com/cosmos/cosmos-sdk/types" + capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" +) + +var _ porttypes.ICS4Wrapper = &ICS4Middleware{} + +type ICS4Middleware struct { + channel porttypes.ICS4Wrapper + + // Hooks + Hooks Hooks +} + +func NewICS4Middleware(channel porttypes.ICS4Wrapper, hooks Hooks) ICS4Middleware { + return ICS4Middleware{ + channel: channel, + Hooks: hooks, + } +} + +func (i ICS4Middleware) SendPacket(ctx sdk.Context, channelCap *capabilitytypes.Capability, _ string, sourceChannel string, timeoutHeight clienttypes.Height, timeoutTimestamp uint64, data []byte) (sequence uint64, err error) { + if hook, ok := i.Hooks.(SendPacketOverrideHooks); ok { + return hook.SendPacketOverride(i, ctx, channelCap, sourceChannel, sourceChannel, timeoutHeight, timeoutTimestamp, data) + } + + if hook, ok := i.Hooks.(SendPacketBeforeHooks); ok { + hook.SendPacketBeforeHook(ctx, channelCap, sourceChannel, sourceChannel, timeoutHeight, timeoutTimestamp, data) + } + + seq, err := i.channel.SendPacket(ctx, channelCap, sourceChannel, sourceChannel, timeoutHeight, timeoutTimestamp, data) + + if hook, ok := i.Hooks.(SendPacketAfterHooks); ok { + hook.SendPacketAfterHook(ctx, channelCap, sourceChannel, sourceChannel, timeoutHeight, timeoutTimestamp, data, err) + } + + return seq, err +} + +func (i ICS4Middleware) WriteAcknowledgement(ctx sdk.Context, chanCap *capabilitytypes.Capability, packet ibcexported.PacketI, ack ibcexported.Acknowledgement) error { + if hook, ok := i.Hooks.(WriteAcknowledgementOverrideHooks); ok { + return hook.WriteAcknowledgementOverride(i, ctx, chanCap, packet, ack) + } + + if hook, ok := i.Hooks.(WriteAcknowledgementBeforeHooks); ok { + hook.WriteAcknowledgementBeforeHook(ctx, chanCap, packet, ack) + } + err := i.channel.WriteAcknowledgement(ctx, chanCap, packet, ack) + if hook, ok := i.Hooks.(WriteAcknowledgementAfterHooks); ok { + hook.WriteAcknowledgementAfterHook(ctx, chanCap, packet, ack, err) + } + + return err +} + +func (i ICS4Middleware) GetAppVersion(ctx sdk.Context, portID, channelID string) (string, bool) { + if hook, ok := i.Hooks.(GetAppVersionOverrideHooks); ok { + return hook.GetAppVersionOverride(i, ctx, portID, channelID) + } + + if hook, ok := i.Hooks.(GetAppVersionBeforeHooks); ok { + hook.GetAppVersionBeforeHook(ctx, portID, channelID) + } + version, err := i.channel.GetAppVersion(ctx, portID, channelID) + if hook, ok := i.Hooks.(GetAppVersionAfterHooks); ok { + hook.GetAppVersionAfterHook(ctx, portID, channelID, version, err) + } + + return version, err +} diff --git a/x/ibchooks/keeper/keeper.go b/x/ibchooks/keeper/keeper.go new file mode 100644 index 0000000..0609f4b --- /dev/null +++ b/x/ibchooks/keeper/keeper.go @@ -0,0 +1,62 @@ +package keeper + +import ( + "fmt" + + "github.com/cometbft/cometbft/libs/log" + + storetypes "github.com/cosmos/cosmos-sdk/store/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/address" + + "github.com/terpnetwork/terp-core/v2/x/ibchooks/types" +) + +type ( + Keeper struct { + storeKey storetypes.StoreKey + } +) + +// NewKeeper returns a new instance of the x/ibchooks keeper +func NewKeeper( + storeKey storetypes.StoreKey, +) Keeper { + return Keeper{ + storeKey: storeKey, + } +} + +// 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)) +} + +func GetPacketKey(channel string, packetSequence uint64) []byte { + return []byte(fmt.Sprintf("%s::%d", channel, packetSequence)) +} + +// StorePacketCallback stores which contract will be listening for the ack or timeout of a packet +func (k Keeper) StorePacketCallback(ctx sdk.Context, channel string, packetSequence uint64, contract string) { + store := ctx.KVStore(k.storeKey) + store.Set(GetPacketKey(channel, packetSequence), []byte(contract)) +} + +// GetPacketCallback returns the bech32 addr of the contract that is expecting a callback from a packet +func (k Keeper) GetPacketCallback(ctx sdk.Context, channel string, packetSequence uint64) string { + store := ctx.KVStore(k.storeKey) + return string(store.Get(GetPacketKey(channel, packetSequence))) +} + +// DeletePacketCallback deletes the callback from storage once it has been processed +func (k Keeper) DeletePacketCallback(ctx sdk.Context, channel string, packetSequence uint64) { + store := ctx.KVStore(k.storeKey) + store.Delete(GetPacketKey(channel, packetSequence)) +} + +func DeriveIntermediateSender(channel, originalSender, bech32Prefix string) (string, error) { + senderStr := fmt.Sprintf("%s/%s", channel, originalSender) + senderHash32 := address.Hash(types.SenderPrefix, []byte(senderStr)) + sender := sdk.AccAddress(senderHash32) + return sdk.Bech32ifyAddressBytes(bech32Prefix, sender) +} diff --git a/x/ibchooks/sdkmodule.go b/x/ibchooks/sdkmodule.go new file mode 100644 index 0000000..df15bee --- /dev/null +++ b/x/ibchooks/sdkmodule.go @@ -0,0 +1,126 @@ +package ibchooks + +import ( + "encoding/json" + + "github.com/gorilla/mux" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" + + abci "github.com/cometbft/cometbft/abci/types" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + cdctypes "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" + + "github.com/terpnetwork/terp-core/v2/x/ibchooks/client/cli" + "github.com/terpnetwork/terp-core/v2/x/ibchooks/types" +) + +var ( + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} +) + +// AppModuleBasic defines the basic application module used by the ibc-hooks module. +type AppModuleBasic struct{} + +var _ module.AppModuleBasic = AppModuleBasic{} + +// Name returns the ibc-hooks module's name. +func (AppModuleBasic) Name() string { + return types.ModuleName +} + +// RegisterLegacyAminoCodec registers the ibc-hooks module's types on the given LegacyAmino codec. +func (AppModuleBasic) RegisterLegacyAminoCodec(_ *codec.LegacyAmino) {} + +// RegisterInterfaces registers the module's interface types. +func (b AppModuleBasic) RegisterInterfaces(_ cdctypes.InterfaceRegistry) {} + +// DefaultGenesis returns default genesis state as raw bytes for the +// module. +func (AppModuleBasic) DefaultGenesis(_ codec.JSONCodec) json.RawMessage { + emptyString := "{}" + return []byte(emptyString) +} + +// ValidateGenesis performs genesis state validation for the ibc-hooks module. +func (AppModuleBasic) ValidateGenesis(_ codec.JSONCodec, _ client.TxEncodingConfig, _ json.RawMessage) error { + return nil +} + +// RegisterRESTRoutes registers the REST routes for the ibc-hooks module. +func (AppModuleBasic) RegisterRESTRoutes(_ client.Context, _ *mux.Router) {} + +// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the ibc-hooks module. +func (AppModuleBasic) RegisterGRPCGatewayRoutes(_ client.Context, _ *runtime.ServeMux) {} + +// GetTxCmd returns no root tx command for the ibc-hooks module. +func (AppModuleBasic) GetTxCmd() *cobra.Command { return nil } + +// GetQueryCmd returns the root query command for the ibc-hooks module. +func (AppModuleBasic) GetQueryCmd() *cobra.Command { + return cli.GetQueryCmd() +} + +// ___________________________________________________________________________ + +// AppModule implements an application module for the ibc-hooks module. +type AppModule struct { + AppModuleBasic + + authKeeper authkeeper.AccountKeeper +} + +// NewAppModule creates a new AppModule object. +func NewAppModule(ak authkeeper.AccountKeeper) AppModule { + return AppModule{ + AppModuleBasic: AppModuleBasic{}, + authKeeper: ak, + } +} + +// Name returns the ibc-hooks module's name. +func (AppModule) Name() string { + return types.ModuleName +} + +// RegisterInvariants registers the ibc-hooks module invariants. +func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} + +// QuerierRoute returns the module's querier route name. +func (AppModule) QuerierRoute() string { + return "" +} + +// RegisterServices registers a gRPC query service to respond to the +// module-specific gRPC queries. +func (am AppModule) RegisterServices(_ module.Configurator) { +} + +// InitGenesis performs genesis initialization for the ibc-hooks module. It returns +// no validator updates. +func (am AppModule) InitGenesis(_ sdk.Context, _ codec.JSONCodec, _ json.RawMessage) []abci.ValidatorUpdate { + return []abci.ValidatorUpdate{} +} + +func (am AppModule) ExportGenesis(_ sdk.Context, _ codec.JSONCodec) json.RawMessage { + return json.RawMessage([]byte("{}")) +} + +// BeginBlock returns the begin blocker for the ibc-hooks module. +func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) { +} + +// EndBlock returns the end blocker for the ibc-hooks module. It returns no validator +// updates. +func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { + return []abci.ValidatorUpdate{} +} + +// ConsensusVersion implements AppModule/ConsensusVersion. +func (AppModule) ConsensusVersion() uint64 { return 1 } diff --git a/x/ibchooks/types/errors.go b/x/ibchooks/types/errors.go new file mode 100644 index 0000000..6c85a36 --- /dev/null +++ b/x/ibchooks/types/errors.go @@ -0,0 +1,15 @@ +package types + +import errorsmod "cosmossdk.io/errors" + +var ( + ErrBadMetadataFormatMsg = "wasm metadata not properly formatted for: '%v'. %s" + ErrBadExecutionMsg = "cannot execute contract: %v" + + ErrMsgValidation = errorsmod.Register("wasm-hooks", 2, "error in wasmhook message validation") + ErrMarshaling = errorsmod.Register("wasm-hooks", 3, "cannot marshal the ICS20 packet") + ErrInvalidPacket = errorsmod.Register("wasm-hooks", 4, "invalid packet data") + ErrBadResponse = errorsmod.Register("wasm-hooks", 5, "cannot create response") + ErrWasmError = errorsmod.Register("wasm-hooks", 6, "wasm error") + ErrBadSender = errorsmod.Register("wasm-hooks", 7, "bad sender") +) diff --git a/x/ibchooks/types/keys.go b/x/ibchooks/types/keys.go new file mode 100644 index 0000000..9a3e7de --- /dev/null +++ b/x/ibchooks/types/keys.go @@ -0,0 +1,8 @@ +package types + +const ( + ModuleName = "ibchooks" + StoreKey = "hooks-for-ibc" // not using the module name because of collisions with key "ibc" + IBCCallbackKey = "ibc_callback" + SenderPrefix = "ibc-wasm-hook-intermediary" +) diff --git a/x/ibchooks/wasm_hook.go b/x/ibchooks/wasm_hook.go new file mode 100644 index 0000000..9db9716 --- /dev/null +++ b/x/ibchooks/wasm_hook.go @@ -0,0 +1,421 @@ +package ibchooks + +import ( + "encoding/json" + "fmt" + + wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" + wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" + + transfertypes "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" + ibcexported "github.com/cosmos/ibc-go/v7/modules/core/exported" + + errorsmod "cosmossdk.io/errors" + + sdk "github.com/cosmos/cosmos-sdk/types" + capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" + + "github.com/terpnetwork/terp-core/v2/osmoutils" + "github.com/terpnetwork/terp-core/v2/x/ibchooks/keeper" + "github.com/terpnetwork/terp-core/v2/x/ibchooks/types" +) + +type ContractAck struct { + ContractResult []byte `json:"contract_result"` + IbcAck []byte `json:"ibc_ack"` +} + +type WasmHooks struct { + WasmKeeper *wasmkeeper.Keeper + ContractKeeper *wasmkeeper.PermissionedKeeper + ibcHooksKeeper *keeper.Keeper + bech32PrefixAccAddr string +} + +func NewWasmHooks(ibcHooksKeeper *keeper.Keeper, contractKeeper *wasmkeeper.PermissionedKeeper, wasmKeeper *wasmkeeper.Keeper, bech32PrefixAccAddr string) WasmHooks { + return WasmHooks{ + WasmKeeper: wasmKeeper, + ContractKeeper: contractKeeper, + ibcHooksKeeper: ibcHooksKeeper, + bech32PrefixAccAddr: bech32PrefixAccAddr, + } +} + +func (h WasmHooks) ProperlyConfigured() bool { + return h.ContractKeeper != nil && h.ibcHooksKeeper != nil +} + +func (h WasmHooks) OnRecvPacketOverride(im IBCMiddleware, ctx sdk.Context, packet channeltypes.Packet, relayer sdk.AccAddress) ibcexported.Acknowledgement { + if !h.ProperlyConfigured() { + // Not configured + return im.App.OnRecvPacket(ctx, packet, relayer) + } + isIcs20, data := isIcs20Packet(packet) + if !isIcs20 { + return im.App.OnRecvPacket(ctx, packet, relayer) + } + + // Validate the memo + isWasmRouted, contractAddr, msgBytes, err := ValidateAndParseMemo(data.GetMemo(), data.Receiver) + if !isWasmRouted { + return im.App.OnRecvPacket(ctx, packet, relayer) + } + if err != nil { + return osmoutils.NewEmitErrorAcknowledgement(ctx, types.ErrMsgValidation, err.Error()) + } + if msgBytes == nil || contractAddr == nil { // This should never happen + return osmoutils.NewEmitErrorAcknowledgement(ctx, types.ErrMsgValidation) + } + + // Calculate the receiver / contract caller based on the packet's channel and sender + channel := packet.GetDestChannel() + sender := data.GetSender() + senderBech32, err := keeper.DeriveIntermediateSender(channel, sender, h.bech32PrefixAccAddr) + if err != nil { + return osmoutils.NewEmitErrorAcknowledgement(ctx, types.ErrBadSender, fmt.Sprintf("cannot convert sender address %s/%s to bech32: %s", channel, sender, err.Error())) + } + + // The funds sent on this packet need to be transferred to the intermediary account for the sender. + // For this, we override the ICS20 packet's Receiver (essentially hijacking the funds to this new address) + // and execute the underlying OnRecvPacket() call (which should eventually land on the transfer app's + // relay.go and send the sunds to the intermediary account. + // + // If that succeeds, we make the contract call + data.Receiver = senderBech32 + bz, err := json.Marshal(data) + if err != nil { + return osmoutils.NewEmitErrorAcknowledgement(ctx, types.ErrMarshaling, err.Error()) + } + packet.Data = bz + + // Execute the receive + ack := im.App.OnRecvPacket(ctx, packet, relayer) + if !ack.Success() { + return ack + } + + amount, ok := sdk.NewIntFromString(data.GetAmount()) + if !ok { + // This should never happen, as it should've been caught in the underlaying call to OnRecvPacket, + // but returning here for completeness + return osmoutils.NewEmitErrorAcknowledgement(ctx, types.ErrInvalidPacket, "Amount is not an int") + } + + // The packet's denom is the denom in the sender chain. This needs to be converted to the local denom. + denom := osmoutils.MustExtractDenomFromPacketOnRecv(packet) + funds := sdk.NewCoins(sdk.NewCoin(denom, amount)) + + // Execute the contract + execMsg := wasmtypes.MsgExecuteContract{ + Sender: senderBech32, + Contract: contractAddr.String(), + Msg: msgBytes, + Funds: funds, + } + response, err := h.execWasmMsg(ctx, &execMsg) + if err != nil { + return osmoutils.NewEmitErrorAcknowledgement(ctx, types.ErrWasmError, err.Error()) + } + + fullAck := ContractAck{ContractResult: response.Data, IbcAck: ack.Acknowledgement()} + bz, err = json.Marshal(fullAck) + if err != nil { + return osmoutils.NewEmitErrorAcknowledgement(ctx, types.ErrBadResponse, err.Error()) + } + + return channeltypes.NewResultAcknowledgement(bz) +} + +func (h WasmHooks) execWasmMsg(ctx sdk.Context, execMsg *wasmtypes.MsgExecuteContract) (*wasmtypes.MsgExecuteContractResponse, error) { + if err := execMsg.ValidateBasic(); err != nil { + return nil, fmt.Errorf(types.ErrBadExecutionMsg, err.Error()) + } + wasmMsgServer := wasmkeeper.NewMsgServerImpl(h.WasmKeeper) + return wasmMsgServer.ExecuteContract(sdk.WrapSDKContext(ctx), execMsg) +} + +func isIcs20Packet(packet channeltypes.Packet) (isIcs20 bool, ics20data transfertypes.FungibleTokenPacketData) { + var data transfertypes.FungibleTokenPacketData + if err := json.Unmarshal(packet.GetData(), &data); err != nil { + return false, data + } + return true, data +} + +// jsonStringHasKey parses the memo as a json object and checks if it contains the key. +func jsonStringHasKey(memo, key string) (found bool, jsonObject map[string]interface{}) { + jsonObject = make(map[string]interface{}) + + // If there is no memo, the packet was either sent with an earlier version of IBC, or the memo was + // intentionally left blank. Nothing to do here. Ignore the packet and pass it down the stack. + if len(memo) == 0 { + return false, jsonObject + } + + // the jsonObject must be a valid JSON object + err := json.Unmarshal([]byte(memo), &jsonObject) + if err != nil { + return false, jsonObject + } + + // If the key doesn't exist, there's nothing to do on this hook. Continue by passing the packet + // down the stack + _, ok := jsonObject[key] + if !ok { + return false, jsonObject + } + + return true, jsonObject +} + +func ValidateAndParseMemo(memo string, receiver string) (isWasmRouted bool, contractAddr sdk.AccAddress, msgBytes []byte, err error) { + isWasmRouted, metadata := jsonStringHasKey(memo, "wasm") + if !isWasmRouted { + return isWasmRouted, sdk.AccAddress{}, nil, nil + } + + wasmRaw := metadata["wasm"] + + // Make sure the wasm key is a map. If it isn't, ignore this packet + wasm, ok := wasmRaw.(map[string]interface{}) + if !ok { + return isWasmRouted, sdk.AccAddress{}, nil, + fmt.Errorf(types.ErrBadMetadataFormatMsg, memo, "wasm metadata is not a valid JSON map object") + } + + // Get the contract + contract, ok := wasm["contract"].(string) + if !ok { + // The tokens will be returned + return isWasmRouted, sdk.AccAddress{}, nil, + fmt.Errorf(types.ErrBadMetadataFormatMsg, memo, `Could not find key wasm["contract"]`) + } + + contractAddr, err = sdk.AccAddressFromBech32(contract) + if err != nil { + return isWasmRouted, sdk.AccAddress{}, nil, + fmt.Errorf(types.ErrBadMetadataFormatMsg, memo, `wasm["contract"] is not a valid bech32 address`) + } + + // The contract and the receiver should be the same for the packet to be valid + if contract != receiver { + return isWasmRouted, sdk.AccAddress{}, nil, + fmt.Errorf(types.ErrBadMetadataFormatMsg, memo, `wasm["contract"] should be the same as the receiver of the packet`) + } + + // Ensure the message key is provided + if wasm["msg"] == nil { + return isWasmRouted, sdk.AccAddress{}, nil, + fmt.Errorf(types.ErrBadMetadataFormatMsg, memo, `Could not find key wasm["msg"]`) + } + + // Make sure the msg key is a map. If it isn't, return an error + _, ok = wasm["msg"].(map[string]interface{}) + if !ok { + return isWasmRouted, sdk.AccAddress{}, nil, + fmt.Errorf(types.ErrBadMetadataFormatMsg, memo, `wasm["msg"] is not a map object`) + } + + // Get the message string by serializing the map + msgBytes, err = json.Marshal(wasm["msg"]) + if err != nil { + // The tokens will be returned + return isWasmRouted, sdk.AccAddress{}, nil, + fmt.Errorf(types.ErrBadMetadataFormatMsg, memo, err.Error()) + } + + return isWasmRouted, contractAddr, msgBytes, nil +} + +func (h WasmHooks) SendPacketOverride(i ICS4Middleware, ctx sdk.Context, chanCap *capabilitytypes.Capability, packet ibcexported.PacketI) error { + height := clienttypes.Height{ + RevisionNumber: packet.GetTimeoutHeight().GetRevisionHeight(), + RevisionHeight: packet.GetTimeoutHeight().GetRevisionHeight(), + } + + concretePacket, ok := packet.(channeltypes.Packet) + if !ok { + if _, err := i.channel.SendPacket(ctx, chanCap, + packet.GetSourcePort(), + packet.GetSourceChannel(), + height, + packet.GetTimeoutTimestamp(), + packet.GetData()); err != nil { + return err + } + } + + isIcs20, data := isIcs20Packet(concretePacket) + if !isIcs20 { + if _, err := i.channel.SendPacket(ctx, chanCap, + packet.GetSourcePort(), + packet.GetSourceChannel(), + height, + packet.GetTimeoutTimestamp(), + packet.GetData()); err != nil { + return err + } + } + + isCallbackRouted, metadata := jsonStringHasKey(data.GetMemo(), types.IBCCallbackKey) + if !isCallbackRouted { + if _, err := i.channel.SendPacket(ctx, chanCap, + packet.GetSourcePort(), + packet.GetSourceChannel(), + height, + packet.GetTimeoutTimestamp(), + packet.GetData()); err != nil { + return err + } + } + + // We remove the callback metadata from the memo as it has already been processed. + + // If the only available key in the memo is the callback, we should remove the memo + // from the data completely so the packet is sent without it. + // This way receiver chains that are on old versions of IBC will be able to process the packet + + callbackRaw := metadata[types.IBCCallbackKey] // This will be used later. + delete(metadata, types.IBCCallbackKey) + bzMetadata, err := json.Marshal(metadata) + if err != nil { + return errorsmod.Wrap(err, "Send packet with callback error") + } + stringMetadata := string(bzMetadata) + if stringMetadata == "{}" { + data.Memo = "" + } else { + data.Memo = stringMetadata + } + dataBytes, err := json.Marshal(data) + if err != nil { + return errorsmod.Wrap(err, "Send packet with callback error") + } + + packetWithoutCallbackMemo := channeltypes.Packet{ + Sequence: concretePacket.Sequence, + SourcePort: concretePacket.SourcePort, + SourceChannel: concretePacket.SourceChannel, + DestinationPort: concretePacket.DestinationPort, + DestinationChannel: concretePacket.DestinationChannel, + Data: dataBytes, + TimeoutTimestamp: concretePacket.TimeoutTimestamp, + TimeoutHeight: concretePacket.TimeoutHeight, + } + + _, err = i.channel.SendPacket(ctx, chanCap, + packetWithoutCallbackMemo.GetSourcePort(), + packetWithoutCallbackMemo.GetSourceChannel(), + height, + packetWithoutCallbackMemo.GetTimeoutTimestamp(), + packetWithoutCallbackMemo.GetData(), + ) + if err != nil { + return err + } + + // Make sure the callback contract is a string and a valid bech32 addr. If it isn't, ignore this packet + contract, ok := callbackRaw.(string) + if !ok { + return nil + } + _, err = sdk.AccAddressFromBech32(contract) + if err != nil { + return nil + } + + h.ibcHooksKeeper.StorePacketCallback(ctx, packet.GetSourceChannel(), packet.GetSequence(), contract) + return nil +} + +func (h WasmHooks) OnAcknowledgementPacketOverride(im IBCMiddleware, ctx sdk.Context, packet channeltypes.Packet, acknowledgement []byte, relayer sdk.AccAddress) error { + err := im.App.OnAcknowledgementPacket(ctx, packet, acknowledgement, relayer) + if err != nil { + return err + } + + if !h.ProperlyConfigured() { + // Not configured. Return from the underlying implementation + return nil + } + + contract := h.ibcHooksKeeper.GetPacketCallback(ctx, packet.GetSourceChannel(), packet.GetSequence()) + if contract == "" { + // No callback configured + return nil + } + + contractAddr, err := sdk.AccAddressFromBech32(contract) + if err != nil { + return errorsmod.Wrap(err, "Ack callback error") // The callback configured is not a bech32. Error out + } + + success := "false" + if !osmoutils.IsAckError(acknowledgement) { + success = "true" + } + + // Notify the sender that the ack has been received + ackAsJSON, err := json.Marshal(acknowledgement) + if err != nil { + // If the ack is not a json object, error + return err + } + + sudoMsg := []byte(fmt.Sprintf( + `{"ibc_lifecycle_complete": {"ibc_ack": {"channel": "%s", "sequence": %d, "ack": %s, "success": %s}}}`, + packet.SourceChannel, packet.Sequence, ackAsJSON, success)) + _, err = h.ContractKeeper.Sudo(ctx, contractAddr, sudoMsg) + if err != nil { + // error processing the callback + // ToDo: Open Question: Should we also delete the callback here? + return errorsmod.Wrap(err, "Ack callback error") + } + h.ibcHooksKeeper.DeletePacketCallback(ctx, packet.GetSourceChannel(), packet.GetSequence()) + return nil +} + +func (h WasmHooks) OnTimeoutPacketOverride(im IBCMiddleware, ctx sdk.Context, packet channeltypes.Packet, relayer sdk.AccAddress) error { + err := im.App.OnTimeoutPacket(ctx, packet, relayer) + if err != nil { + return err + } + + if !h.ProperlyConfigured() { + // Not configured. Return from the underlying implementation + return nil + } + + contract := h.ibcHooksKeeper.GetPacketCallback(ctx, packet.GetSourceChannel(), packet.GetSequence()) + if contract == "" { + // No callback configured + return nil + } + + contractAddr, err := sdk.AccAddressFromBech32(contract) + if err != nil { + return errorsmod.Wrap(err, "Timeout callback error") // The callback configured is not a bech32. Error out + } + + sudoMsg := []byte(fmt.Sprintf( + `{"ibc_lifecycle_complete": {"ibc_timeout": {"channel": "%s", "sequence": %d}}}`, + packet.SourceChannel, packet.Sequence)) + _, err = h.ContractKeeper.Sudo(ctx, contractAddr, sudoMsg) + if err != nil { + // error processing the callback. This could be because the contract doesn't implement the message type to + // process the callback. Retrying this will not help, so we can delete the callback from storage. + // Since the packet has timed out, we don't expect any other responses that may trigger the callback. + ctx.EventManager().EmitEvents(sdk.Events{ + sdk.NewEvent( + "ibc-timeout-callback-error", + sdk.NewAttribute("contract", contractAddr.String()), + sdk.NewAttribute("message", string(sudoMsg)), + sdk.NewAttribute("error", err.Error()), + ), + }) + } + h.ibcHooksKeeper.DeletePacketCallback(ctx, packet.GetSourceChannel(), packet.GetSequence()) + return nil +} diff --git a/x/tokenfactory/README.md b/x/tokenfactory/README.md deleted file mode 100644 index 7d6644e..0000000 --- a/x/tokenfactory/README.md +++ /dev/null @@ -1,155 +0,0 @@ -# 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 deleted file mode 100644 index a21bc45..0000000 --- a/x/tokenfactory/bindings/custom_msg_test.go +++ /dev/null @@ -1,277 +0,0 @@ -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 { //nolint:unparam // funds currently always receives nil, but it may receive something else in the future - 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 deleted file mode 100644 index 67e3491..0000000 --- a/x/tokenfactory/bindings/custom_query_test.go +++ /dev/null @@ -1,75 +0,0 @@ -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 deleted file mode 100644 index 6857249..0000000 --- a/x/tokenfactory/bindings/helpers_test.go +++ /dev/null @@ -1,108 +0,0 @@ -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 deleted file mode 100644 index 0e67ca2..0000000 --- a/x/tokenfactory/bindings/message_plugin.go +++ /dev/null @@ -1,321 +0,0 @@ -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 deleted file mode 100644 index 15dd308..0000000 --- a/x/tokenfactory/bindings/queries.go +++ /dev/null @@ -1,57 +0,0 @@ -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 deleted file mode 100644 index 0dfbfeb..0000000 --- a/x/tokenfactory/bindings/query_plugin.go +++ /dev/null @@ -1,123 +0,0 @@ -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 deleted file mode 100755 index 161a33f..0000000 --- a/x/tokenfactory/bindings/testdata/download_releases.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/bash -set -o errexit -o nounset -o pipefail -command -v shellcheck > /dev/null && shellcheck "$0" - -if [ $# -ne 1 ]; then - echo "Usage: ./download_releases.sh RELEASE_TAG" - exit 1 -fi - -tag="$1" -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 deleted file mode 100644 index 0d742e1..0000000 Binary files a/x/tokenfactory/bindings/testdata/token_reflect.wasm and /dev/null differ diff --git a/x/tokenfactory/bindings/testdata/version.txt b/x/tokenfactory/bindings/testdata/version.txt deleted file mode 100644 index b19b521..0000000 --- a/x/tokenfactory/bindings/testdata/version.txt +++ /dev/null @@ -1 +0,0 @@ -v0.8.0 diff --git a/x/tokenfactory/bindings/types/msg.go b/x/tokenfactory/bindings/types/msg.go deleted file mode 100644 index 3c6cfa2..0000000 --- a/x/tokenfactory/bindings/types/msg.go +++ /dev/null @@ -1,60 +0,0 @@ -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 deleted file mode 100644 index f2dab49..0000000 --- a/x/tokenfactory/bindings/types/query.go +++ /dev/null @@ -1,59 +0,0 @@ -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 deleted file mode 100644 index 2c75fee..0000000 --- a/x/tokenfactory/bindings/types/types.go +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index e0a88ce..0000000 --- a/x/tokenfactory/bindings/validate_msg_test.go +++ /dev/null @@ -1,429 +0,0 @@ -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 deleted file mode 100644 index c800103..0000000 --- a/x/tokenfactory/bindings/validate_queries_test.go +++ /dev/null @@ -1,115 +0,0 @@ -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 deleted file mode 100644 index 33ea401..0000000 --- a/x/tokenfactory/bindings/wasm.go +++ /dev/null @@ -1,30 +0,0 @@ -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 deleted file mode 100644 index b23a7e2..0000000 --- a/x/tokenfactory/client/cli/query.go +++ /dev/null @@ -1,122 +0,0 @@ -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 deleted file mode 100644 index 9b0aeff..0000000 --- a/x/tokenfactory/client/cli/tx.go +++ /dev/null @@ -1,200 +0,0 @@ -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 deleted file mode 100644 index 665895b..0000000 --- a/x/tokenfactory/keeper/admins.go +++ /dev/null @@ -1,49 +0,0 @@ -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 deleted file mode 100644 index 335320f..0000000 --- a/x/tokenfactory/keeper/admins_test.go +++ /dev/null @@ -1,404 +0,0 @@ -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 deleted file mode 100644 index 803c4c3..0000000 --- a/x/tokenfactory/keeper/bankactions.go +++ /dev/null @@ -1,73 +0,0 @@ -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 deleted file mode 100644 index 4c5fe3e..0000000 --- a/x/tokenfactory/keeper/createdenom.go +++ /dev/null @@ -1,86 +0,0 @@ -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 deleted file mode 100644 index 1900bbf..0000000 --- a/x/tokenfactory/keeper/createdenom_test.go +++ /dev/null @@ -1,163 +0,0 @@ -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 deleted file mode 100644 index 570d54b..0000000 --- a/x/tokenfactory/keeper/creators.go +++ /dev/null @@ -1,27 +0,0 @@ -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 deleted file mode 100644 index 52577e8..0000000 --- a/x/tokenfactory/keeper/genesis.go +++ /dev/null @@ -1,58 +0,0 @@ -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 deleted file mode 100644 index a04ef9b..0000000 --- a/x/tokenfactory/keeper/genesis_test.go +++ /dev/null @@ -1,59 +0,0 @@ -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 deleted file mode 100644 index 2ee7191..0000000 --- a/x/tokenfactory/keeper/grpc_query.go +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index 2ce23cd..0000000 --- a/x/tokenfactory/keeper/keeper.go +++ /dev/null @@ -1,82 +0,0 @@ -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 deleted file mode 100644 index 75581e3..0000000 --- a/x/tokenfactory/keeper/keeper_test.go +++ /dev/null @@ -1,64 +0,0 @@ -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 deleted file mode 100644 index 9bd98ed..0000000 --- a/x/tokenfactory/keeper/msg_server.go +++ /dev/null @@ -1,191 +0,0 @@ -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 deleted file mode 100644 index 83f99a5..0000000 --- a/x/tokenfactory/keeper/msg_server_test.go +++ /dev/null @@ -1,247 +0,0 @@ -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 deleted file mode 100644 index 9c9caf4..0000000 --- a/x/tokenfactory/keeper/params.go +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index fdac9f1..0000000 --- a/x/tokenfactory/module.go +++ /dev/null @@ -1,220 +0,0 @@ -/* -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 deleted file mode 100644 index f3e091b..0000000 --- a/x/tokenfactory/simulation/genesis.go +++ /dev/null @@ -1,26 +0,0 @@ -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 deleted file mode 100644 index 46f9a16..0000000 --- a/x/tokenfactory/simulation/operations.go +++ /dev/null @@ -1,404 +0,0 @@ -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 deleted file mode 100644 index 886bf06..0000000 --- a/x/tokenfactory/simulation/params.go +++ /dev/null @@ -1,24 +0,0 @@ -package simulation - -import ( - "fmt" - "math/rand" - - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/simulation" - - "github.com/terpnetwork/terp-core/x/tokenfactory/types" -) - -func ParamChanges(r *rand.Rand) []simtypes.LegacyParamChange { - return []simtypes.LegacyParamChange{ - simulation.NewSimLegacyParamChange( - types.ModuleName, - string(types.KeyDenomCreationFee), - func(r *rand.Rand) string { - amount := RandDenomCreationFeeParam(r) - return fmt.Sprintf("[{\"denom\":\"%v\",\"amount\":\"%v\"}]", amount[0].Denom, amount[0].Amount) - }, - ), - } -} diff --git a/x/tokenfactory/testhelpers/consts.go b/x/tokenfactory/testhelpers/consts.go deleted file mode 100644 index d7804a3..0000000 --- a/x/tokenfactory/testhelpers/consts.go +++ /dev/null @@ -1,8 +0,0 @@ -package testhelpers - -import sdk "github.com/cosmos/cosmos-sdk/types" - -var ( - SecondaryDenom = "uion" - SecondaryAmount = sdk.NewInt(100000000) -) diff --git a/x/tokenfactory/testhelpers/suite.go b/x/tokenfactory/testhelpers/suite.go deleted file mode 100644 index b509a52..0000000 --- a/x/tokenfactory/testhelpers/suite.go +++ /dev/null @@ -1,66 +0,0 @@ -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 deleted file mode 100644 index b45bffc..0000000 --- a/x/tokenfactory/types/authorityMetadata.go +++ /dev/null @@ -1,15 +0,0 @@ -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/authority_metadata.pb.go b/x/tokenfactory/types/authority_metadata.pb.go deleted file mode 100644 index 7e07827..0000000 --- a/x/tokenfactory/types/authority_metadata.pb.go +++ /dev/null @@ -1,365 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmwasm/tokenfactory/v1beta1/authority_metadata.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_5e9c086b3b345014, []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), "osmosis.tokenfactory.v1beta1.DenomAuthorityMetadata") -} - -func init() { - proto.RegisterFile("cosmwasm/tokenfactory/v1beta1/authority_metadata.proto", fileDescriptor_5e9c086b3b345014) -} - -var fileDescriptor_5e9c086b3b345014 = []byte{ - // 253 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0x4b, 0xce, 0x2f, 0xce, - 0x2d, 0x4f, 0x2c, 0xce, 0xd5, 0x2f, 0xc9, 0xcf, 0x4e, 0xcd, 0x4b, 0x4b, 0x4c, 0x2e, 0xc9, 0x2f, - 0xaa, 0xd4, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4, 0x4f, 0x2c, 0x2d, 0xc9, 0xc8, 0x2f, - 0xca, 0x2c, 0xa9, 0x8c, 0xcf, 0x4d, 0x2d, 0x49, 0x4c, 0x49, 0x2c, 0x49, 0xd4, 0x2b, 0x28, 0xca, - 0x2f, 0xc9, 0x17, 0x92, 0xc9, 0x2f, 0xce, 0xcd, 0x2f, 0xce, 0x2c, 0xd6, 0x43, 0xd6, 0xa6, 0x07, - 0xd5, 0x26, 0x25, 0x97, 0x0c, 0x96, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0x85, 0x9b, 0x95, 0x9c, 0x9f, - 0x99, 0x07, 0xd1, 0x2d, 0x25, 0x92, 0x9e, 0x9f, 0x9e, 0x0f, 0x66, 0xea, 0x83, 0x58, 0x10, 0x51, - 0x25, 0x37, 0x2e, 0x31, 0x97, 0xd4, 0xbc, 0xfc, 0x5c, 0x47, 0x98, 0xa5, 0xbe, 0x50, 0x3b, 0x85, - 0xd4, 0xb8, 0x58, 0x13, 0x53, 0x72, 0x33, 0xf3, 0x24, 0x18, 0x15, 0x18, 0x35, 0x38, 0x9d, 0x04, - 0x3e, 0xdd, 0x93, 0xe7, 0xa9, 0x4c, 0xcc, 0xcd, 0xb1, 0x52, 0x02, 0x0b, 0x2b, 0x05, 0x41, 0xa4, - 0xad, 0x58, 0x5e, 0x2c, 0x90, 0x67, 0x74, 0xf2, 0x3f, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, - 0xc6, 0x07, 0x8f, 0xe4, 0x18, 0x27, 0x3c, 0x96, 0x63, 0xb8, 0xf0, 0x58, 0x8e, 0xe1, 0xc6, 0x63, - 0x39, 0x86, 0x28, 0xd3, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, 0xfd, 0x92, - 0xd4, 0xa2, 0x82, 0xbc, 0xd4, 0x92, 0xf2, 0xfc, 0xa2, 0x6c, 0x30, 0x5b, 0x37, 0x39, 0xbf, 0x28, - 0x55, 0xbf, 0x02, 0x35, 0x1c, 0x4a, 0x2a, 0x0b, 0x52, 0x8b, 0x93, 0xd8, 0xc0, 0xee, 0x33, 0x06, - 0x04, 0x00, 0x00, 0xff, 0xff, 0x3c, 0x03, 0xdd, 0x97, 0x2d, 0x01, 0x00, 0x00, -} - -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 deleted file mode 100644 index 366e337..0000000 --- a/x/tokenfactory/types/authzcodec/codec.go +++ /dev/null @@ -1,24 +0,0 @@ -package authzcodec - -// Note: this file is a copy from authz/codec in 0.46 so we can be compatible with 0.45 - -import ( - "github.com/cosmos/cosmos-sdk/codec" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -var ( - Amino = codec.NewLegacyAmino() - ModuleCdc = codec.NewAminoCodec(Amino) -) - -func init() { - // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be - // used to properly serialize MsgGrant and MsgExec instances - sdk.RegisterLegacyAminoCodec(Amino) - cryptocodec.RegisterCrypto(Amino) - codec.RegisterEvidences(Amino) - - Amino.Seal() -} diff --git a/x/tokenfactory/types/codec.go b/x/tokenfactory/types/codec.go deleted file mode 100644 index b086a51..0000000 --- a/x/tokenfactory/types/codec.go +++ /dev/null @@ -1,46 +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" - 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 deleted file mode 100644 index 6583998..0000000 --- a/x/tokenfactory/types/denoms.go +++ /dev/null @@ -1,68 +0,0 @@ -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 deleted file mode 100644 index 12f4637..0000000 --- a/x/tokenfactory/types/denoms_test.go +++ /dev/null @@ -1,132 +0,0 @@ -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 deleted file mode 100644 index 7742014..0000000 --- a/x/tokenfactory/types/errors.go +++ /dev/null @@ -1,22 +0,0 @@ -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 deleted file mode 100644 index 48038e0..0000000 --- a/x/tokenfactory/types/events.go +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 15f377e..0000000 --- a/x/tokenfactory/types/expected_keepers.go +++ /dev/null @@ -1,36 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -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 deleted file mode 100644 index aef9370..0000000 --- a/x/tokenfactory/types/genesis.go +++ /dev/null @@ -1,51 +0,0 @@ -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 deleted file mode 100644 index f2c5849..0000000 --- a/x/tokenfactory/types/genesis.pb.go +++ /dev/null @@ -1,669 +0,0 @@ -// 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), "osmosis.tokenfactory.v1beta1.GenesisState") - proto.RegisterType((*GenesisDenom)(nil), "osmosis.tokenfactory.v1beta1.GenesisDenom") -} - -func init() { - proto.RegisterFile("cosmwasm/tokenfactory/v1beta1/genesis.proto", fileDescriptor_b333539769138b3e) -} - -var fileDescriptor_b333539769138b3e = []byte{ - // 374 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xd2, 0x4e, 0xce, 0x2f, 0xce, - 0x2d, 0x4f, 0x2c, 0xce, 0xd5, 0x2f, 0xc9, 0xcf, 0x4e, 0xcd, 0x4b, 0x4b, 0x4c, 0x2e, 0xc9, 0x2f, - 0xaa, 0xd4, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4, 0x4f, 0x4f, 0xcd, 0x4b, 0x2d, 0xce, - 0x2c, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x92, 0xc9, 0x2f, 0xce, 0xcd, 0x07, 0x71, 0x91, - 0xd5, 0xea, 0x41, 0xd5, 0x4a, 0x89, 0xa4, 0xe7, 0xa7, 0xe7, 0x83, 0x15, 0xea, 0x83, 0x58, 0x10, - 0x3d, 0x52, 0x66, 0xf8, 0x2d, 0x48, 0x2c, 0x2d, 0xc9, 0xc8, 0x2f, 0xca, 0x2c, 0xa9, 0x8c, 0xcf, - 0x4d, 0x2d, 0x49, 0x4c, 0x49, 0x2c, 0x49, 0x84, 0xea, 0xd3, 0xc2, 0xaf, 0xaf, 0x20, 0xb1, 0x28, - 0x31, 0x17, 0xea, 0x2e, 0xa5, 0x23, 0x8c, 0x5c, 0x3c, 0xee, 0x10, 0x97, 0x06, 0x97, 0x24, 0x96, - 0xa4, 0x0a, 0x39, 0x71, 0xb1, 0x41, 0x14, 0x48, 0x30, 0x2a, 0x30, 0x6a, 0x70, 0x1b, 0xa9, 0xe8, - 0xe1, 0x73, 0xb9, 0x5e, 0x00, 0x58, 0xad, 0x13, 0xcb, 0x89, 0x7b, 0xf2, 0x0c, 0x41, 0x50, 0x9d, - 0x42, 0x05, 0x5c, 0x7c, 0x50, 0x75, 0xf1, 0x29, 0xa9, 0x79, 0xf9, 0xb9, 0xc5, 0x12, 0x4c, 0x0a, - 0xcc, 0x1a, 0xdc, 0x46, 0x5a, 0xf8, 0xcd, 0x82, 0xba, 0xc3, 0x05, 0xa4, 0xc5, 0x49, 0x16, 0x64, - 0xe2, 0xa7, 0x7b, 0xf2, 0xa2, 0x95, 0x89, 0xb9, 0x39, 0x56, 0x4a, 0xa8, 0xe6, 0x29, 0x05, 0xf1, - 0x42, 0x05, 0x5c, 0x20, 0xfc, 0xa3, 0x08, 0x6f, 0x80, 0x45, 0x84, 0xd4, 0xb8, 0x58, 0xc1, 0x4a, - 0xc1, 0xbe, 0xe0, 0x74, 0x12, 0xf8, 0x74, 0x4f, 0x9e, 0x07, 0x62, 0x12, 0x58, 0x58, 0x29, 0x08, - 0x22, 0x2d, 0xd4, 0xc6, 0xc8, 0x25, 0x84, 0x19, 0x90, 0x12, 0x4c, 0x60, 0xbf, 0x9b, 0xe0, 0x77, - 0x2f, 0xd8, 0x26, 0x47, 0x98, 0x66, 0x5f, 0xa8, 0x5e, 0x27, 0x45, 0xa8, 0xcb, 0x25, 0x21, 0xf6, - 0x61, 0x9a, 0xae, 0x14, 0x24, 0x98, 0x88, 0xae, 0xcb, 0x8a, 0xe5, 0xc5, 0x02, 0x79, 0x46, 0x27, - 0xff, 0x13, 0x8f, 0xe4, 0x18, 0x2f, 0x3c, 0x92, 0x63, 0x7c, 0xf0, 0x48, 0x8e, 0x71, 0xc2, 0x63, - 0x39, 0x86, 0x0b, 0x8f, 0xe5, 0x18, 0x6e, 0x3c, 0x96, 0x63, 0x88, 0x32, 0x4d, 0xcf, 0x2c, 0xc9, - 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x2f, 0x49, 0x2d, 0x2a, 0xc8, 0x4b, 0x2d, 0x29, 0xcf, - 0x2f, 0xca, 0x06, 0xb3, 0x75, 0x93, 0xf3, 0x8b, 0x52, 0xf5, 0x2b, 0x50, 0xa3, 0xbb, 0xa4, 0xb2, - 0x20, 0xb5, 0x38, 0x89, 0x0d, 0x1c, 0xcd, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0xe4, 0x72, - 0x8b, 0x18, 0xad, 0x02, 0x00, 0x00, -} - -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 deleted file mode 100644 index c93adb4..0000000 --- a/x/tokenfactory/types/genesis_test.go +++ /dev/null @@ -1,139 +0,0 @@ -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 deleted file mode 100644 index fac4a6e..0000000 --- a/x/tokenfactory/types/keys.go +++ /dev/null @@ -1,49 +0,0 @@ -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 deleted file mode 100644 index e9fb237..0000000 --- a/x/tokenfactory/types/msgs.go +++ /dev/null @@ -1,247 +0,0 @@ -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 deleted file mode 100644 index 2b71ce1..0000000 --- a/x/tokenfactory/types/msgs_test.go +++ /dev/null @@ -1,451 +0,0 @@ -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 deleted file mode 100644 index a483078..0000000 --- a/x/tokenfactory/types/params.go +++ /dev/null @@ -1,62 +0,0 @@ -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/tokenfactory/types/params.pb.go b/x/tokenfactory/types/params.pb.go deleted file mode 100644 index 73973e6..0000000 --- a/x/tokenfactory/types/params.pb.go +++ /dev/null @@ -1,354 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmwasm/tokenfactory/v1beta1/params.proto - -package types - -import ( - fmt "fmt" - io "io" - math "math" - math_bits "math/bits" - - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" -) - -// 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 - -// 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 (m *Params) String() string { return proto.CompactTextString(m) } -func (*Params) ProtoMessage() {} -func (*Params) Descriptor() ([]byte, []int) { - return fileDescriptor_c2e403a2e90cdef7, []int{0} -} - -func (m *Params) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *Params) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Params.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *Params) XXX_Merge(src proto.Message) { - xxx_messageInfo_Params.Merge(m, src) -} - -func (m *Params) XXX_Size() int { - return m.Size() -} - -func (m *Params) XXX_DiscardUnknown() { - xxx_messageInfo_Params.DiscardUnknown(m) -} - -var xxx_messageInfo_Params proto.InternalMessageInfo - -func (m *Params) GetDenomCreationFee() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.DenomCreationFee - } - return nil -} - -func init() { - proto.RegisterType((*Params)(nil), "osmosis.tokenfactory.v1beta1.Params") -} - -func init() { - proto.RegisterFile("cosmwasm/tokenfactory/v1beta1/params.proto", fileDescriptor_c2e403a2e90cdef7) -} - -var fileDescriptor_c2e403a2e90cdef7 = []byte{ - // 314 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x90, 0xb1, 0x4a, 0x03, 0x41, - 0x10, 0x86, 0xef, 0x10, 0x52, 0xc4, 0x46, 0x82, 0x85, 0x09, 0xb2, 0x91, 0x54, 0x41, 0xc8, 0x2d, - 0x51, 0xb4, 0xb0, 0x4c, 0xc0, 0x4e, 0x14, 0x4b, 0x9b, 0x63, 0x6e, 0x33, 0x49, 0x8e, 0xb8, 0x37, - 0xc7, 0xee, 0xc4, 0x78, 0x6f, 0x61, 0x65, 0x6f, 0xeb, 0x93, 0xa4, 0x4c, 0x69, 0x15, 0x25, 0x79, - 0x03, 0x9f, 0x40, 0xb2, 0xb7, 0x4a, 0x44, 0xb0, 0xda, 0x19, 0xe6, 0xff, 0xbf, 0x99, 0x7f, 0xab, - 0xc7, 0x8a, 0xac, 0x9e, 0x81, 0xd5, 0x92, 0x69, 0x82, 0xd9, 0x10, 0x14, 0x93, 0x29, 0xe4, 0x43, - 0x37, 0x41, 0x86, 0xae, 0xcc, 0xc1, 0x80, 0xb6, 0x51, 0x6e, 0x88, 0xa9, 0x76, 0x48, 0x56, 0x93, - 0x4d, 0x6d, 0xb4, 0x2d, 0x8d, 0xbc, 0xb4, 0xb1, 0x3f, 0xa2, 0x11, 0x39, 0xa1, 0xdc, 0x54, 0xa5, - 0xa7, 0x71, 0xfe, 0x3f, 0x1f, 0xa6, 0x3c, 0x26, 0x93, 0x72, 0x11, 0x6b, 0x64, 0x18, 0x00, 0x83, - 0xf7, 0xd5, 0x95, 0x5b, 0x16, 0x97, 0xc0, 0xb2, 0xf1, 0x23, 0x51, 0x76, 0x32, 0x01, 0x8b, 0x3f, - 0x20, 0x45, 0x69, 0x56, 0xce, 0x5b, 0x2f, 0x61, 0xb5, 0x72, 0xe3, 0xee, 0xae, 0x3d, 0x87, 0xd5, - 0xda, 0x00, 0x33, 0xd2, 0xb1, 0x32, 0x08, 0x9c, 0x52, 0x16, 0x0f, 0x11, 0x0f, 0xc2, 0xa3, 0x9d, - 0xf6, 0xee, 0x49, 0x3d, 0xf2, 0xd8, 0x0d, 0xe8, 0x3b, 0x46, 0xd4, 0xa7, 0x34, 0xeb, 0x5d, 0xcd, - 0x97, 0xcd, 0xe0, 0x73, 0xd9, 0xac, 0x17, 0xa0, 0xef, 0x2f, 0x5a, 0x7f, 0x11, 0xad, 0xd7, 0xf7, - 0x66, 0x7b, 0x94, 0xf2, 0x78, 0x9a, 0x44, 0x8a, 0xb4, 0x3f, 0xd0, 0x3f, 0x1d, 0x3b, 0x98, 0x48, - 0x2e, 0x72, 0xb4, 0x8e, 0x66, 0x6f, 0xf7, 0x1c, 0xa0, 0xef, 0xfd, 0x97, 0x88, 0xbd, 0xeb, 0xf9, - 0x4a, 0x84, 0x8b, 0x95, 0x08, 0x3f, 0x56, 0x22, 0x7c, 0x5a, 0x8b, 0x60, 0xb1, 0x16, 0xc1, 0xdb, - 0x5a, 0x04, 0x77, 0x67, 0x5b, 0x54, 0x46, 0x93, 0x67, 0xc8, 0x33, 0x32, 0x13, 0x57, 0x77, 0x14, - 0x19, 0x94, 0x8f, 0xbf, 0xbf, 0xd2, 0x2d, 0x4a, 0x2a, 0x2e, 0xfb, 0xe9, 0x57, 0x00, 0x00, 0x00, - 0xff, 0xff, 0x87, 0xe5, 0x07, 0xed, 0xd0, 0x01, 0x00, 0x00, -} - -func (m *Params) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Params) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.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 -} - -func encodeVarintParams(dAtA []byte, offset int, v uint64) int { - offset -= sovParams(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} - -func (m *Params) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.DenomCreationFee) > 0 { - for _, e := range m.DenomCreationFee { - l = e.Size() - n += 1 + l + sovParams(uint64(l)) - } - } - return n -} - -func sovParams(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} - -func sozParams(x uint64) (n int) { - return sovParams(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} - -func (m *Params) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Params: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Params: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 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:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthParams - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func skipParams(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParams - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParams - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParams - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthParams - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupParams - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthParams - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthParams = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowParams = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupParams = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/tokenfactory/types/query.pb.go b/x/tokenfactory/types/query.pb.go deleted file mode 100644 index 61e82d9..0000000 --- a/x/tokenfactory/types/query.pb.go +++ /dev/null @@ -1,1377 +0,0 @@ -// 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), "osmosis.tokenfactory.v1beta1.QueryParamsRequest") - proto.RegisterType((*QueryParamsResponse)(nil), "osmosis.tokenfactory.v1beta1.QueryParamsResponse") - proto.RegisterType((*QueryDenomAuthorityMetadataRequest)(nil), "osmosis.tokenfactory.v1beta1.QueryDenomAuthorityMetadataRequest") - proto.RegisterType((*QueryDenomAuthorityMetadataResponse)(nil), "osmosis.tokenfactory.v1beta1.QueryDenomAuthorityMetadataResponse") - proto.RegisterType((*QueryDenomsFromCreatorRequest)(nil), "osmosis.tokenfactory.v1beta1.QueryDenomsFromCreatorRequest") - proto.RegisterType((*QueryDenomsFromCreatorResponse)(nil), "osmosis.tokenfactory.v1beta1.QueryDenomsFromCreatorResponse") -} - -func init() { - proto.RegisterFile("cosmwasm/tokenfactory/v1beta1/query.proto", fileDescriptor_d8606ce711f56ea6) -} - -var fileDescriptor_d8606ce711f56ea6 = []byte{ - // 582 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x54, 0x4d, 0x4f, 0x13, 0x41, - 0x18, 0xee, 0x2a, 0xd4, 0x30, 0x7e, 0x44, 0x46, 0x62, 0xb4, 0xc1, 0xad, 0x8e, 0x84, 0x80, 0xc1, - 0x1d, 0xc1, 0x8f, 0x83, 0x68, 0x94, 0xc5, 0xe8, 0x41, 0x89, 0xba, 0x37, 0xbd, 0x34, 0xd3, 0x65, - 0x58, 0x36, 0xb0, 0xfb, 0x2e, 0x33, 0x53, 0xb1, 0x21, 0x5c, 0x3c, 0x78, 0x36, 0xf1, 0xe8, 0x7f, - 0xf0, 0x77, 0x70, 0x24, 0xe1, 0xe2, 0xa9, 0x31, 0x2d, 0xf1, 0x07, 0xf4, 0x17, 0x98, 0xce, 0x4c, - 0xb5, 0xd8, 0xb2, 0xa9, 0x7a, 0xea, 0x64, 0xe6, 0x79, 0x9e, 0xf7, 0x79, 0xde, 0xf7, 0xed, 0xa2, - 0xd9, 0x10, 0x64, 0xb2, 0xcd, 0x64, 0x42, 0x15, 0x6c, 0xf0, 0x74, 0x8d, 0x85, 0x0a, 0x44, 0x9d, - 0xbe, 0x9b, 0xaf, 0x72, 0xc5, 0xe6, 0xe9, 0x56, 0x8d, 0x8b, 0xba, 0x97, 0x09, 0x50, 0x80, 0x27, - 0x41, 0x26, 0x20, 0x63, 0xe9, 0xf5, 0x22, 0x3d, 0x8b, 0x2c, 0x4d, 0x44, 0x10, 0x81, 0x06, 0xd2, - 0xce, 0xc9, 0x70, 0x4a, 0x93, 0x11, 0x40, 0xb4, 0xc9, 0x29, 0xcb, 0x62, 0xca, 0xd2, 0x14, 0x14, - 0x53, 0x31, 0xa4, 0xd2, 0xbe, 0xde, 0x08, 0xb5, 0x24, 0xad, 0x32, 0xc9, 0x4d, 0xa9, 0x5f, 0x85, - 0x33, 0x16, 0xc5, 0xa9, 0x06, 0x5b, 0xec, 0xbd, 0x7c, 0xa3, 0xac, 0xa6, 0xd6, 0x41, 0xc4, 0xaa, - 0x5e, 0x49, 0xb8, 0x62, 0xab, 0x4c, 0xb1, 0xde, 0x1a, 0xc7, 0xf3, 0x32, 0x26, 0x58, 0x62, 0xfd, - 0x90, 0x09, 0x84, 0x5f, 0x77, 0x5c, 0xbc, 0xd2, 0x97, 0x01, 0xdf, 0xaa, 0x71, 0xa9, 0xc8, 0x1b, - 0x74, 0xe1, 0xc8, 0xad, 0xcc, 0x20, 0x95, 0x1c, 0xfb, 0xa8, 0x68, 0xc8, 0x97, 0x9c, 0xab, 0xce, - 0xcc, 0xe9, 0x85, 0x29, 0x2f, 0xaf, 0x3f, 0x9e, 0x61, 0xfb, 0x23, 0x7b, 0x8d, 0x72, 0x21, 0xb0, - 0x4c, 0xf2, 0x02, 0x11, 0x2d, 0xfd, 0x84, 0xa7, 0x90, 0x2c, 0x75, 0x23, 0xac, 0xd8, 0x04, 0xd6, - 0x00, 0x9e, 0x46, 0xa3, 0xab, 0x1d, 0x80, 0x2e, 0x34, 0xe6, 0x9f, 0x6f, 0x37, 0xca, 0x67, 0xea, - 0x2c, 0xd9, 0xbc, 0x4f, 0xf4, 0x35, 0x09, 0xcc, 0x33, 0xf9, 0xea, 0xa0, 0xeb, 0xb9, 0x72, 0xd6, - 0xf9, 0x47, 0x07, 0xe1, 0xfe, 0x7e, 0xd9, 0x18, 0x77, 0xf2, 0x63, 0x0c, 0x96, 0xf6, 0xaf, 0x75, - 0x62, 0xb5, 0x1b, 0xe5, 0xcb, 0xc6, 0x57, 0xbf, 0x3a, 0x09, 0xc6, 0xd9, 0x9f, 0x2c, 0xb2, 0x82, - 0xae, 0xfc, 0xf6, 0x2b, 0x9f, 0x0a, 0x48, 0x96, 0x05, 0x67, 0x0a, 0x44, 0x37, 0xf9, 0x1c, 0x3a, - 0x15, 0x9a, 0x1b, 0x9b, 0x1d, 0xb7, 0x1b, 0xe5, 0x73, 0xa6, 0x86, 0x7d, 0x20, 0x41, 0x17, 0x42, - 0x9e, 0x23, 0xf7, 0x38, 0x39, 0x9b, 0x7c, 0x16, 0x15, 0x75, 0xab, 0x3a, 0x33, 0x3b, 0x39, 0x33, - 0xe6, 0x8f, 0xb7, 0x1b, 0xe5, 0xb3, 0x3d, 0xad, 0x94, 0x24, 0xb0, 0x80, 0x85, 0xc3, 0x11, 0x34, - 0xaa, 0xd5, 0xf0, 0x17, 0x07, 0x15, 0xcd, 0xf4, 0xf0, 0xad, 0xfc, 0xe6, 0xf4, 0x2f, 0x4f, 0x69, - 0xfe, 0x2f, 0x18, 0xc6, 0x24, 0x99, 0xfb, 0x70, 0x70, 0xf8, 0xf9, 0xc4, 0x34, 0x9e, 0xa2, 0x96, - 0x9a, 0xb7, 0xb9, 0xf8, 0x87, 0x83, 0x2e, 0x0e, 0x1e, 0x0a, 0x7e, 0x3c, 0x44, 0xed, 0xdc, 0xcd, - 0x2b, 0x2d, 0xfd, 0x87, 0x82, 0x4d, 0xf3, 0x4c, 0xa7, 0x59, 0xc2, 0x8f, 0xf2, 0xd3, 0x98, 0xae, - 0xd3, 0x1d, 0xfd, 0xbb, 0x3b, 0xe0, 0xef, 0x8c, 0x0f, 0x1c, 0x34, 0xde, 0x37, 0x59, 0xbc, 0x38, - 0xac, 0xc3, 0x01, 0xeb, 0x55, 0x7a, 0xf0, 0x6f, 0x64, 0x9b, 0x6c, 0x59, 0x27, 0x7b, 0x88, 0x17, - 0x87, 0x49, 0x56, 0x59, 0x13, 0x90, 0x54, 0xec, 0xa6, 0xd2, 0x1d, 0x7b, 0xd8, 0xf5, 0x5f, 0xee, - 0x35, 0x5d, 0x67, 0xbf, 0xe9, 0x3a, 0xdf, 0x9b, 0xae, 0xf3, 0xa9, 0xe5, 0x16, 0xf6, 0x5b, 0x6e, - 0xe1, 0x5b, 0xcb, 0x2d, 0xbc, 0xbd, 0x1b, 0xc5, 0x6a, 0xbd, 0x56, 0xf5, 0x42, 0x48, 0xa8, 0xe2, - 0x22, 0x4b, 0xb9, 0xda, 0x06, 0xb1, 0xa1, 0xcf, 0x37, 0x43, 0x10, 0x9c, 0xbe, 0x3f, 0x5a, 0x50, - 0xd5, 0x33, 0x2e, 0xab, 0x45, 0xfd, 0x29, 0xbb, 0xfd, 0x33, 0x00, 0x00, 0xff, 0xff, 0x57, 0xf9, - 0x26, 0xf2, 0xd9, 0x05, 0x00, 0x00, -} - -// 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, "/osmosis.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, "/osmosis.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, "/osmosis.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: "/osmosis.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: "/osmosis.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: "/osmosis.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: "osmosis.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 deleted file mode 100644 index af07c01..0000000 --- a/x/tokenfactory/types/query.pb.gw.go +++ /dev/null @@ -1,343 +0,0 @@ -// 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 deleted file mode 100644 index 8aafe6e..0000000 --- a/x/tokenfactory/types/tx.pb.go +++ /dev/null @@ -1,2329 +0,0 @@ -// 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{} -} - -// MsgMintResponse defines the response structure for an executed -// MsgMint message. -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{} -} - -// MsgBurnResponse defines the response structure for an executed -// MsgBurn message. -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), "osmosis.tokenfactory.v1beta1.MsgCreateDenom") - proto.RegisterType((*MsgCreateDenomResponse)(nil), "osmosis.tokenfactory.v1beta1.MsgCreateDenomResponse") - proto.RegisterType((*MsgMint)(nil), "osmosis.tokenfactory.v1beta1.MsgMint") - proto.RegisterType((*MsgMintResponse)(nil), "osmosis.tokenfactory.v1beta1.MsgMintResponse") - proto.RegisterType((*MsgBurn)(nil), "osmosis.tokenfactory.v1beta1.MsgBurn") - proto.RegisterType((*MsgBurnResponse)(nil), "osmosis.tokenfactory.v1beta1.MsgBurnResponse") - proto.RegisterType((*MsgChangeAdmin)(nil), "osmosis.tokenfactory.v1beta1.MsgChangeAdmin") - proto.RegisterType((*MsgChangeAdminResponse)(nil), "osmosis.tokenfactory.v1beta1.MsgChangeAdminResponse") - proto.RegisterType((*MsgSetDenomMetadata)(nil), "osmosis.tokenfactory.v1beta1.MsgSetDenomMetadata") - proto.RegisterType((*MsgSetDenomMetadataResponse)(nil), "osmosis.tokenfactory.v1beta1.MsgSetDenomMetadataResponse") -} - -func init() { - proto.RegisterFile("cosmwasm/tokenfactory/v1beta1/tx.proto", fileDescriptor_345508fcea0bfc02) -} - -var fileDescriptor_345508fcea0bfc02 = []byte{ - // 600 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x55, 0x41, 0x6e, 0xd3, 0x40, - 0x14, 0x8d, 0x69, 0x29, 0xe9, 0x94, 0x92, 0xd4, 0x2d, 0x25, 0x18, 0x6a, 0xa3, 0x91, 0xa8, 0x40, - 0xa2, 0xb6, 0x52, 0x60, 0x01, 0x3b, 0x5c, 0x16, 0x6c, 0x2c, 0x24, 0xc3, 0x0a, 0x55, 0xaa, 0x26, - 0xce, 0xe0, 0x5a, 0xa9, 0x67, 0x82, 0x67, 0x42, 0x9a, 0x0d, 0xe2, 0x08, 0x2c, 0x10, 0x87, 0xe0, - 0x24, 0x5d, 0x76, 0xc9, 0xca, 0x42, 0xc9, 0x0d, 0x72, 0x02, 0xe4, 0x99, 0xb1, 0xe3, 0x34, 0x88, - 0x24, 0x2b, 0x76, 0x8e, 0xff, 0x7b, 0x6f, 0xde, 0xbc, 0xff, 0x7f, 0x0c, 0xf6, 0x03, 0xca, 0xe2, - 0x3e, 0x62, 0xb1, 0xc3, 0x69, 0x07, 0x93, 0x8f, 0x28, 0xe0, 0x34, 0x19, 0x38, 0x9f, 0x9b, 0x2d, - 0xcc, 0x51, 0xd3, 0xe1, 0xe7, 0x76, 0x37, 0xa1, 0x9c, 0xea, 0xf7, 0x29, 0x8b, 0x29, 0x8b, 0x98, - 0x5d, 0x86, 0xd9, 0x0a, 0x66, 0xec, 0x84, 0x34, 0xa4, 0x02, 0xe8, 0x64, 0x4f, 0x92, 0x63, 0x98, - 0x81, 0x20, 0x39, 0x2d, 0xc4, 0x70, 0xa1, 0x18, 0xd0, 0x88, 0xcc, 0xd4, 0x49, 0xa7, 0xa8, 0x67, - 0x3f, 0x64, 0x1d, 0x9e, 0x81, 0x5b, 0x1e, 0x0b, 0x8f, 0x12, 0x8c, 0x38, 0x7e, 0x8d, 0x09, 0x8d, - 0xf5, 0xc7, 0x60, 0x8d, 0x61, 0xd2, 0xc6, 0x49, 0x43, 0x7b, 0xa0, 0x3d, 0x5a, 0x77, 0xb7, 0xc6, - 0xa9, 0xb5, 0x39, 0x40, 0xf1, 0xd9, 0x4b, 0x28, 0xdf, 0x43, 0x5f, 0x01, 0x74, 0x07, 0x54, 0x59, - 0xaf, 0xd5, 0xce, 0x68, 0x8d, 0x6b, 0x02, 0xbc, 0x3d, 0x4e, 0xad, 0x9a, 0x02, 0xab, 0x0a, 0xf4, - 0x0b, 0x10, 0x3c, 0x06, 0xbb, 0xd3, 0xa7, 0xf9, 0x98, 0x75, 0x29, 0x61, 0x58, 0x77, 0x41, 0x8d, - 0xe0, 0xfe, 0x89, 0xb8, 0xf9, 0x89, 0x54, 0x94, 0xc7, 0x1b, 0xe3, 0xd4, 0xda, 0x95, 0x8a, 0x57, - 0x00, 0xd0, 0xdf, 0x24, 0xb8, 0xff, 0x3e, 0x7b, 0x21, 0xb4, 0xe0, 0x17, 0x70, 0xc3, 0x63, 0xa1, - 0x17, 0x11, 0xbe, 0xcc, 0x25, 0xde, 0x80, 0x35, 0x14, 0xd3, 0x1e, 0xe1, 0xe2, 0x0a, 0x1b, 0x87, - 0x77, 0x6d, 0x19, 0x99, 0x9d, 0x45, 0x9a, 0xa7, 0x6f, 0x1f, 0xd1, 0x88, 0xb8, 0xb7, 0x2f, 0x52, - 0xab, 0x32, 0x51, 0x92, 0x34, 0xe8, 0x2b, 0x3e, 0xdc, 0x02, 0x35, 0x75, 0x7e, 0x7e, 0x2d, 0x65, - 0xc9, 0xed, 0x25, 0xe4, 0x7f, 0x5a, 0xca, 0xce, 0x2f, 0x2c, 0xfd, 0xd0, 0x64, 0xcb, 0x4f, 0x11, - 0x09, 0xf1, 0xab, 0x76, 0x1c, 0x2d, 0x65, 0x6d, 0x1f, 0x5c, 0x2f, 0xf7, 0xbb, 0x3e, 0x4e, 0xad, - 0x9b, 0x12, 0xa9, 0x7a, 0x22, 0xcb, 0x7a, 0x13, 0xac, 0x67, 0xed, 0x42, 0x99, 0x7e, 0x63, 0x45, - 0x60, 0x77, 0xc6, 0xa9, 0x55, 0x9f, 0x74, 0x52, 0x94, 0xa0, 0x5f, 0x25, 0xb8, 0x2f, 0x5c, 0xc0, - 0x86, 0x1c, 0x8e, 0x89, 0xaf, 0xc2, 0xf2, 0x77, 0x0d, 0x6c, 0x7b, 0x2c, 0x7c, 0x87, 0xb9, 0x68, - 0xb4, 0x87, 0x39, 0x6a, 0x23, 0x8e, 0x96, 0xf1, 0xed, 0x83, 0x6a, 0xac, 0x68, 0x2a, 0xd4, 0xbd, - 0x49, 0xa8, 0xa4, 0x53, 0x84, 0x9a, 0x6b, 0xbb, 0x77, 0x54, 0xb0, 0x6a, 0x9a, 0x73, 0x32, 0xf4, - 0x0b, 0x1d, 0xb8, 0x07, 0xee, 0xfd, 0xc5, 0x55, 0xee, 0xfa, 0xf0, 0xe7, 0x2a, 0x58, 0xf1, 0x58, - 0xa8, 0x7f, 0x02, 0x1b, 0xe5, 0xfd, 0x7a, 0x62, 0xff, 0x6b, 0xcd, 0xed, 0xe9, 0xfd, 0x30, 0x9e, - 0x2d, 0x83, 0x2e, 0xb6, 0xe9, 0x18, 0xac, 0x8a, 0x35, 0x78, 0x38, 0x97, 0x9d, 0xc1, 0x8c, 0x83, - 0x85, 0x60, 0x65, 0x75, 0x31, 0xd1, 0xf3, 0xd5, 0x33, 0xd8, 0x02, 0xea, 0xe5, 0xf9, 0x14, 0x71, - 0x95, 0x66, 0x73, 0x81, 0xb8, 0x26, 0xe8, 0x45, 0xe2, 0x9a, 0x9d, 0x2f, 0xfd, 0xab, 0x06, 0xea, - 0x33, 0xc3, 0xd5, 0x9c, 0x2b, 0x75, 0x95, 0x62, 0xbc, 0x58, 0x9a, 0x92, 0x5b, 0x70, 0xdf, 0x5e, - 0x0c, 0x4d, 0xed, 0x72, 0x68, 0x6a, 0xbf, 0x87, 0xa6, 0xf6, 0x6d, 0x64, 0x56, 0x2e, 0x47, 0x66, - 0xe5, 0xd7, 0xc8, 0xac, 0x7c, 0x78, 0x1e, 0x46, 0xfc, 0xb4, 0xd7, 0xb2, 0x03, 0x1a, 0x3b, 0x1c, - 0x27, 0x5d, 0x82, 0x79, 0x9f, 0x26, 0x1d, 0xf1, 0x7c, 0x10, 0xd0, 0x04, 0x3b, 0xe7, 0xd3, 0xdf, - 0x15, 0x3e, 0xe8, 0x62, 0xd6, 0x5a, 0x13, 0xff, 0xef, 0x4f, 0xff, 0x04, 0x00, 0x00, 0xff, 0xff, - 0x50, 0xaf, 0x99, 0xd6, 0x7d, 0x06, 0x00, 0x00, -} - -// 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 Creates a denom of factory/{creator address}/{subdenom} given - // the denom creator address and the subdenom. Subdenoms can contain - // [a-zA-Z0-9./]. - CreateDenom(ctx context.Context, in *MsgCreateDenom, opts ...grpc.CallOption) (*MsgCreateDenomResponse, error) - // Mint is message type that represents a request to mint a new denom. - Mint(ctx context.Context, in *MsgMint, opts ...grpc.CallOption) (*MsgMintResponse, error) - // Burn message type that represents a request to burn (i.e., destroy) a - // denom. - Burn(ctx context.Context, in *MsgBurn, opts ...grpc.CallOption) (*MsgBurnResponse, error) - // A message type that represents a request to change the administrator of the - // denom. - ChangeAdmin(ctx context.Context, in *MsgChangeAdmin, opts ...grpc.CallOption) (*MsgChangeAdminResponse, error) - // A message type that represents a request to set metadata for a - // denomination. - SetDenomMetadata(ctx context.Context, in *MsgSetDenomMetadata, opts ...grpc.CallOption) (*MsgSetDenomMetadataResponse, error) -} - -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, "/osmosis.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, "/osmosis.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, "/osmosis.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, "/osmosis.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, "/osmosis.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 Creates a denom of factory/{creator address}/{subdenom} given - // the denom creator address and the subdenom. Subdenoms can contain - // [a-zA-Z0-9./]. - CreateDenom(context.Context, *MsgCreateDenom) (*MsgCreateDenomResponse, error) - // Mint is message type that represents a request to mint a new denom. - Mint(context.Context, *MsgMint) (*MsgMintResponse, error) - // Burn message type that represents a request to burn (i.e., destroy) a - // denom. - Burn(context.Context, *MsgBurn) (*MsgBurnResponse, error) - // A message type that represents a request to change the administrator of the - // denom. - ChangeAdmin(context.Context, *MsgChangeAdmin) (*MsgChangeAdminResponse, error) - // A message type that represents a request to set metadata for a - // denomination. - SetDenomMetadata(context.Context, *MsgSetDenomMetadata) (*MsgSetDenomMetadataResponse, error) -} - -// 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: "/osmosis.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: "/osmosis.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: "/osmosis.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: "/osmosis.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: "/osmosis.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: "osmosis.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 deleted file mode 100644 index 8760412..0000000 --- a/x/wasm/Governance.md +++ /dev/null @@ -1,205 +0,0 @@ -# Governance - -This document gives an overview of how the various governance -proposals interact with the CosmWasm contract lifecycle. It is -a high-level, technical introduction meant to provide context before -looking into the code, or constructing proposals. - -## Proposal Types -We have added 9 new wasm specific proposal types that cover the contract's live cycle and authorization: - -* `StoreCodeProposal` - upload a wasm binary -* `InstantiateContractProposal` - instantiate a wasm contract -* `MigrateContractProposal` - migrate a wasm contract to a new code version -* `SudoContractProposal` - call into the protected `sudo` entry point of a contract -* `ExecuteContractProposal` - execute a wasm contract as an arbitrary user -* `UpdateAdminProposal` - set a new admin for a contract -* `ClearAdminProposal` - clear admin for a contract to prevent further migrations -* `PinCodes` - pin the given code ids in cache. This trades memory for reduced startup time and lowers gas cost -* `UnpinCodes` - unpin the given code ids from the cache. This frees up memory and returns to standard speed and gas cost -* `UpdateInstantiateConfigProposal` - update instantiate permissions to a list of given code ids. -* `StoreAndInstantiateContractProposal` - upload and instantiate a wasm contract. - -For details see the proposal type [implementation](https://github.com/terpnetwork/terp-core/blob/master/x/wasm/types/proposal.go) - -### Unit tests -[Proposal type validations](https://github.com/terpnetwork/terp-core/blob/master/x/wasm/types/proposal_test.go) - -## Proposal Handler -The [wasmd proposal_handler](https://github.com/terpnetwork/terp-core/blob/master/x/wasm/keeper/proposal_handler.go) implements the `gov.Handler` function -and executes the wasmd proposal types after a successful tally. - -The proposal handler uses a [`GovAuthorizationPolicy`](https://github.com/terpnetwork/terp-core/blob/master/x/wasm/keeper/authz_policy.go#L29) to bypass the existing contract's authorization policy. - -### Tests -* [Integration: Submit and execute proposal](https://github.com/terpnetwork/terp-core/blob/master/x/wasm/keeper/proposal_integration_test.go) - -## Gov Integration -The wasmd proposal handler can be added to the gov router in the [abci app](https://github.com/terpnetwork/terp-core/blob/master/app/app.go#L306) -to receive proposal execution calls. -```go -govRouter.AddRoute(wasm.RouterKey, wasm.NewWasmProposalHandler(app.wasmKeeper, enabledProposals)) -``` - -## Wasmd Authorization Settings - -Settings via sdk `params` module: -- `code_upload_access` - who can upload a wasm binary: `Nobody`, `Everybody`, `OnlyAddress` -- `instantiate_default_permission` - platform default, who can instantiate a wasm binary when the code owner has not set it - -See [params.go](https://github.com/terpnetwork/terp-core/blob/master/x/wasm/types/params.go) - -### Init Params Via Genesis - -```json - "wasm": { - "params": { - "code_upload_access": { - "permission": "Everybody" - }, - "instantiate_default_permission": "Everybody" - } - }, -``` - -The values can be updated via gov proposal implemented in the `params` module. - -### Update Params Via [ParamChangeProposal](https://github.com/cosmos/cosmos-sdk/blob/v0.45.3/proto/cosmos/params/v1beta1/params.proto#L10) -Example to submit a parameter change gov proposal: -```sh -wasmd tx gov submit-proposal param-change --from validator --chain-id=testing -b block -``` -#### Content examples -* Disable wasm code uploads -```json -{ - "title": "Foo", - "description": "Bar", - "changes": [ - { - "subspace": "wasm", - "key": "uploadAccess", - "value": { - "permission": "Nobody" - } - } - ], - "deposit": "" -} -``` -* Allow wasm code uploads for everybody -```json -{ - "title": "Foo", - "description": "Bar", - "changes": [ - { - "subspace": "wasm", - "key": "uploadAccess", - "value": { - "permission": "Everybody" - } - } - ], - "deposit": "" -} -``` - -* Restrict code uploads to a single address -```json -{ - "title": "Foo", - "description": "Bar", - "changes": [ - { - "subspace": "wasm", - "key": "uploadAccess", - "value": { - "permission": "OnlyAddress", - "address": "cosmos1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq0fr2sh" - } - } - ], - "deposit": "" -} -``` -* Set chain **default** instantiation settings to nobody -```json -{ - "title": "Foo", - "description": "Bar", - "changes": [ - { - "subspace": "wasm", - "key": "instantiateAccess", - "value": "Nobody" - } - ], - "deposit": "" -} -``` -* Set chain **default** instantiation settings to everybody -```json -{ - "title": "Foo", - "description": "Bar", - "changes": [ - { - "subspace": "wasm", - "key": "instantiateAccess", - "value": "Everybody" - } - ], - "deposit": "" -} -``` - -### Enable gov proposals at **compile time**. -As gov proposals bypass the existing authorization policy they are disabled and require to be enabled at compile time. -``` --X github.com/terpnetwork/terp-core/app.ProposalsEnabled=true - enable all x/wasm governance proposals (default false) --X github.com/terpnetwork/terp-core/app.EnableSpecificProposals=MigrateContract,UpdateAdmin,ClearAdmin - enable a subset of the x/wasm governance proposal types (overrides ProposalsEnabled) -``` - -The `ParamChangeProposal` is always enabled. - -### Tests -* [params validation unit tests](https://github.com/terpnetwork/terp-core/blob/master/x/wasm/types/params_test.go) -* [genesis validation tests](https://github.com/terpnetwork/terp-core/blob/master/x/wasm/types/genesis_test.go) -* [policy integration tests](https://github.com/terpnetwork/terp-core/blob/master/x/wasm/keeper/keeper_test.go) - -## CLI - -```shell script - wasmd tx gov submit-proposal [command] - -Available Commands: - wasm-store Submit a wasm binary proposal - instantiate-contract Submit an instantiate wasm contract proposal - migrate-contract Submit a migrate wasm contract to a new code version proposal - set-contract-admin Submit a new admin for a contract proposal - clear-contract-admin Submit a clear admin for a contract to prevent further migrations proposal -... -``` -## Rest -New [`ProposalHandlers`](https://github.com/terpnetwork/terp-core/blob/master/x/wasm/client/proposal_handler.go) - -* Integration -```shell script -gov.NewAppModuleBasic(append(wasmclient.ProposalHandlers, paramsclient.ProposalHandler, distr.ProposalHandler, upgradeclient.ProposalHandler)...), -``` -In [abci app](https://github.com/terpnetwork/terp-core/blob/master/app/app.go#L109) - -### Tests -* [Rest Unit tests](https://github.com/terpnetwork/terp-core/blob/master/x/wasm/client/proposal_handler_test.go) -* [Rest smoke LCD test](https://github.com/terpnetwork/terp-core/blob/master/lcd_test/wasm_test.go) - - - -## Pull requests -* https://github.com/terpnetwork/terp-core/pull/190 -* https://github.com/terpnetwork/terp-core/pull/186 -* https://github.com/terpnetwork/terp-core/pull/183 -* https://github.com/terpnetwork/terp-core/pull/180 -* https://github.com/terpnetwork/terp-core/pull/179 -* https://github.com/terpnetwork/terp-core/pull/173 diff --git a/x/wasm/IBC.md b/x/wasm/IBC.md deleted file mode 100644 index c3cd0a0..0000000 --- a/x/wasm/IBC.md +++ /dev/null @@ -1,137 +0,0 @@ -# IBC specification - -This documents how CosmWasm contracts are expected to interact with IBC. - -## General Concepts - -**IBC Enabled** - when instantiating a contract, we detect if it supports IBC messages. - We require "feature flags" in the contract/vm handshake to ensure compatibility - for features like staking or chain-specific extensions. IBC functionality will require - another "feature flag", and the list of "enabled features" can be returned to the `x/wasm` - module to control conditional IBC behavior. - - If this feature is enabled, it is considered "IBC Enabled", and that info will - be stored in the ContractInfo. (For mock, we assume all contracts are IBC enabled) - -Also, please read the [IBC Docs](https://docs.cosmos.network/master/ibc/overview.html) -for detailed descriptions of the terms *Port*, *Client*, *Connection*, -and *Channel* - -## Overview - -We use "One Port per Contract", which is the most straight-forward mapping, treating each contract -like a module. It does lead to very long portIDs however. Pay special attention to both the Channel establishment -(which should be compatible with standard ICS20 modules without changes on their part), as well -as how contracts can properly identify their counterparty. - -(We considered on port for the `x/wasm` module and multiplexing on it, but [dismissed that idea](#rejected-ideas)) - -* Upon `Instantiate`, if a contract is *IBC Enabled*, we dynamically - bind a port for this contract. The port name is `wasm.`, - eg. `wasm.cosmos1hmdudppzceg27qsuq707tjg8rkgj7g5hnvnw29` -* If a *Channel* is being established with a registered `wasm.xyz` port, - the `x/wasm.Keeper` will handle this and call into the appropriate - contract to determine supported protocol versions during the - [`ChanOpenTry` and `ChanOpenAck` phases](https://docs.cosmos.network/master/ibc/overview.html#channels). - (See [Channel Handshake Version Negotiation](https://docs.cosmos.network/master/ibc/custom.html#channel-handshake-version-negotiation)) -* Both the *Port* and the *Channel* are fully owned by one contract. -* `x/wasm` will allow both *ORDERED* and *UNORDERED* channels and pass that mode - down to the contract in `OnChanOpenTry`, so the contract can decide if it accepts - the mode. We will recommend the contract developers stick with *ORDERED* channels - for custom protocols unless they can reason about async packet timing. -* When sending a packet, the CosmWasm contract must specify the local *ChannelID*. - As there is a unique *PortID* per contract, that is filled in by `x/wasm` - to produce the globally unique `(PortID, ChannelID)` -* When receiving a Packet (or Ack or Timeout), the contracts receives the local - *ChannelID* it came from, as well as the packet that was sent by the counterparty. -* When receiving an Ack or Timeout packet, the contract also receives the - original packet that it sent earlier. -* We do not support multihop packets in this model (they are rejected by `x/wasm`). - They are currently not fully specified nor implemented in IBC 1.0, so let us - simplify our model until this is well established - -## Workflow - -Establishing *Clients* and *Connections* is out of the scope of this -module and must be created by the same means as for `ibc-transfer` -(via the [go cli](https://github.com/cosmos/relayer) or better [ts-relayer](https://github.com/confio/ts-relayer)). -`x/wasm` will bind a unique *Port* for each "IBC Enabled" contract. - -For mocks, all the Packet Handling and Channel Lifecycle Hooks are routed -to some Golang stub handler, but containing the contract address, so we -can perform contract-specific actions for each packet. In a real setting, -we route to the contract that owns the port/channel and call one of it's various -entry points. - -Please refer to the CosmWasm repo for all -[details on the IBC API from the point of view of a CosmWasm contract](https://github.com/CosmWasm/cosmwasm/blob/main/IBC.md). - -## Future Ideas - -Here are some ideas we may add in the future - -### Dynamic Ports and Channels - -* multiple ports per contract -* elastic ports that can be assigned to different contracts -* transfer of channels to another contract - -This is inspired by the Agoric design, but also adds considerable complexity to both the `x/wasm` -implementation as well as the correctness reasoning of any given contract. This will not be -available in the first version of our "IBC Enabled contracts", but we can consider it for later, -if there are concrete user cases that would significantly benefit from this added complexity. - -### Add multihop support - -Once the ICS and IBC specs fully establish how multihop packets work, we should add support for that. -Both on setting up the routes with OpenChannel, as well as acting as an intermediate relayer (if that is possible) - -## Rejected Ideas - -### One Port per Module - -We decided on "one port per contract", especially after the IBC team raised -the max length on port names to allow `wasm-` to be a valid port. -Here are the arguments for "one port for x/wasm" vs "one port per contract". Here -was an alternate proposal: - -In this approach, the `x/wasm` module just binds one port to handle all -modules. This can be well defined name like `wasm`. Since we always -have `(ChannelID, PortID)` for routing messages, we can reuse one port -for all contracts as long as we have a clear way to map the `ChannelID` -to a specific contract when it is being established. - - -* On genesis we bind the port `wasm` for all communication with the `x/wasm` - module. -* The *Port* is fully owned by `x/wasm` -* Each *Channel* is fully owned by one contract. -* `x/wasm` only accepts *ORDERED Channels* for simplicity of contract - correctness. - -To clarify: - -* When a *Channel* is being established with port `wasm`, the - `x/wasm.Keeper` must be able to identify for which contract this - is destined. **how to do so**?? - * One idea: the channel name must be the contract address. This means - (`wasm`, `cosmos13d...`) will map to the given contract in the wasm module. - The problem with this is that if two contracts from chainA want to - connect to the same contracts on chainB, they will want to claim the - same *ChannelID* and *PortID*. Not sure how to differentiate multiple - parties in this way. - * Other ideas: have a special field we send on `OnChanOpenInit` that - specifies the destination contract, and allow any *ChannelID*. - However, looking at [`OnChanOpenInit` function signature](https://docs.cosmos.network/master/ibc/custom.html#implement-ibcmodule-interface-and-callbacks), - I don't see a place to put this extra info, without abusing the version field, - which is a [specified field](https://docs.cosmos.network/master/ibc/custom.html#channel-handshake-version-negotiation): - ``` - Versions must be strings but can implement any versioning structure. - If your application plans to have linear releases then semantic versioning is recommended. - ... - Valid version selection includes selecting a compatible version identifier with a subset - of features supported by your application for that version. - ... - ICS20 currently implements basic string matching with a - single supported version. - ``` \ No newline at end of file diff --git a/x/wasm/README.md b/x/wasm/README.md deleted file mode 100644 index cba9c5c..0000000 --- a/x/wasm/README.md +++ /dev/null @@ -1,219 +0,0 @@ -# Wasm Module - -This should be a brief overview of the functionality - -## Configuration - -You can add the following section to `config/app.toml`: - -```toml -[wasm] -# This is the maximum sdk gas (wasm and storage) that we allow for any x/wasm "smart" queries -query_gas_limit = 300000 -# This defines the memory size for Wasm modules that we can keep cached to speed-up instantiation -# The value is in MiB not bytes -memory_cache_size = 300 -``` - -The values can also be set via CLI flags on with the `start` command: -```shell script ---wasm.memory_cache_size uint32 Sets the size in MiB (NOT bytes) of an in-memory cache for wasm modules. Set to 0 to disable. (default 100) ---wasm.query_gas_limit uint Set the max gas that can be spent on executing a query with a Wasm contract (default 3000000) -``` - -## Events - -A number of events are returned to allow good indexing of the transactions from smart contracts. - -Every call to Instantiate or Execute will be tagged with the info on the contract that was executed and who executed it. -It should look something like this (with different addresses). The module is always `wasm`, and `code_id` is only present -when Instantiating a contract, so you can subscribe to new instances, it is omitted on Execute. There is also an `action` tag -which is auto-added by the Cosmos SDK and has a value of either `store-code`, `instantiate` or `execute` depending on which message -was sent: - -```json -{ - "Type": "message", - "Attr": [ - { - "key": "module", - "value": "wasm" - }, - { - "key": "action", - "value": "instantiate" - }, - { - "key": "signer", - "value": "cosmos1vx8knpllrj7n963p9ttd80w47kpacrhuts497x" - }, - { - "key": "code_id", - "value": "1" - }, - { - "key": "_contract_address", - "value": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr" - } - ] -} -``` - -If any funds were transferred to the contract as part of the message, or if the contract released funds as part of it's executions, -it will receive the typical events associated with sending tokens from bank. In this case, we instantiate the contract and -provide a initial balance in the same `MsgInstantiateContract`. We see the following events in addition to the above one: - -```json -[ - { - "Type": "transfer", - "Attr": [ - { - "key": "recipient", - "value": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr" - }, - { - "key": "sender", - "value": "cosmos1ffnqn02ft2psvyv4dyr56nnv6plllf9pm2kpmv" - }, - { - "key": "amount", - "value": "100000denom" - } - ] - } -] -``` - -Finally, the contract itself can emit a "custom event" on Execute only (not on Init). -There is one event per contract, so if one contract calls a second contract, you may receive -one event for the original contract and one for the re-invoked contract. All attributes from the contract are passed through verbatim, -and we add a `_contract_address` attribute that contains the actual contract that emitted that event. -Here is an example from the escrow contract successfully releasing funds to the destination address: - -```json -{ - "Type": "wasm", - "Attr": [ - { - "key": "_contract_address", - "value": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr" - }, - { - "key": "action", - "value": "release" - }, - { - "key": "destination", - "value": "cosmos14k7v7ms4jxkk2etmg9gljxjm4ru3qjdugfsflq" - } - ] -} -``` - -### Pulling this all together - -We will invoke an escrow contract to release to the designated beneficiary. -The escrow was previously loaded with `100000denom` (from the above example). -In this transaction, we send `5000denom` along with the `MsgExecuteContract` -and the contract releases the entire funds (`105000denom`) to the beneficiary. - -We will see all the following events, where you should be able to reconstruct the actions -(remember there are two events for each transfer). We see (1) the initial transfer of funds -to the contract, (2) the contract custom event that it released funds (3) the transfer of funds -from the contract to the beneficiary and (4) the generic x/wasm event stating that the contract -was executed (which always appears, while 2 is optional and has information as reliable as the contract): - -```json -[ - { - "Type": "transfer", - "Attr": [ - { - "key": "recipient", - "value": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr" - }, - { - "key": "sender", - "value": "cosmos1zm074khx32hqy20hlshlsd423n07pwlu9cpt37" - }, - { - "key": "amount", - "value": "5000denom" - } - ] - }, - { - "Type": "wasm", - "Attr": [ - { - "key": "_contract_address", - "value": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr" - }, - { - "key": "action", - "value": "release" - }, - { - "key": "destination", - "value": "cosmos14k7v7ms4jxkk2etmg9gljxjm4ru3qjdugfsflq" - } - ] - }, - { - "Type": "transfer", - "Attr": [ - { - "key": "recipient", - "value": "cosmos14k7v7ms4jxkk2etmg9gljxjm4ru3qjdugfsflq" - }, - { - "key": "sender", - "value": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr" - }, - { - "key": "amount", - "value": "105000denom" - } - ] - }, - { - "Type": "message", - "Attr": [ - { - "key": "module", - "value": "wasm" - }, - { - "key": "action", - "value": "execute" - }, - { - "key": "signer", - "value": "cosmos1zm074khx32hqy20hlshlsd423n07pwlu9cpt37" - }, - { - "key": "_contract_address", - "value": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr" - } - ] - } -] -``` - -A note on this format. This is what we return from our module. However, it seems to me that many events with the same `Type` -get merged together somewhere along the stack, so in this case, you *may* end up with one "transfer" event with the info for -both transfers. Double check when evaluating the event logs, I will document better with more experience, especially when I -find out the entire path for the events. - -## Messages - -TODO - -## CLI - -TODO - working, but not the nicest interface (json + bash = bleh). Use to upload, but I suggest to focus on frontend / js tooling - -## Rest - -TODO - main supported interface, under rapid change diff --git a/x/wasm/alias.go b/x/wasm/alias.go deleted file mode 100644 index 8f952e2..0000000 --- a/x/wasm/alias.go +++ /dev/null @@ -1,124 +0,0 @@ -// autogenerated code using github.com/rigelrozanski/multitool -// aliases generated for the following subdirectories: -// ALIASGEN: github.com/Cosmwasm/wasmd/x/wasm/types -// ALIASGEN: github.com/terpnetwork/terp-core/x/wasm/keeper -package wasm - -import ( - "github.com/terpnetwork/terp-core/x/wasm/keeper" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -const ( - firstCodeID = 1 - ModuleName = types.ModuleName - StoreKey = types.StoreKey - TStoreKey = types.TStoreKey - QuerierRoute = types.QuerierRoute - RouterKey = types.RouterKey - WasmModuleEventType = types.WasmModuleEventType - AttributeKeyContractAddr = types.AttributeKeyContractAddr - ProposalTypeStoreCode = types.ProposalTypeStoreCode - ProposalTypeInstantiateContract = types.ProposalTypeInstantiateContract - ProposalTypeMigrateContract = types.ProposalTypeMigrateContract - ProposalTypeUpdateAdmin = types.ProposalTypeUpdateAdmin - ProposalTypeClearAdmin = types.ProposalTypeClearAdmin -) - -var ( - // functions aliases - RegisterCodec = types.RegisterLegacyAminoCodec - RegisterInterfaces = types.RegisterInterfaces - ValidateGenesis = types.ValidateGenesis - ConvertToProposals = types.ConvertToProposals - GetCodeKey = types.GetCodeKey - GetContractAddressKey = types.GetContractAddressKey - GetContractStorePrefixKey = types.GetContractStorePrefix - NewCodeInfo = types.NewCodeInfo - NewAbsoluteTxPosition = types.NewAbsoluteTxPosition - NewContractInfo = types.NewContractInfo - NewEnv = types.NewEnv - NewWasmCoins = types.NewWasmCoins - DefaultWasmConfig = types.DefaultWasmConfig - DefaultParams = types.DefaultParams - InitGenesis = keeper.InitGenesis - ExportGenesis = keeper.ExportGenesis - NewMessageHandler = keeper.NewDefaultMessageHandler - DefaultEncoders = keeper.DefaultEncoders - EncodeBankMsg = keeper.EncodeBankMsg - NoCustomMsg = keeper.NoCustomMsg - EncodeStakingMsg = keeper.EncodeStakingMsg - EncodeWasmMsg = keeper.EncodeWasmMsg - NewKeeper = keeper.NewKeeper - DefaultQueryPlugins = keeper.DefaultQueryPlugins - BankQuerier = keeper.BankQuerier - NoCustomQuerier = keeper.NoCustomQuerier - StakingQuerier = keeper.StakingQuerier - WasmQuerier = keeper.WasmQuerier - CreateTestInput = keeper.CreateTestInput - TestHandler = keeper.TestHandler - NewWasmProposalHandler = keeper.NewWasmProposalHandler //nolint:staticcheck - NewQuerier = keeper.Querier - ContractFromPortID = keeper.ContractFromPortID - WithWasmEngine = keeper.WithWasmEngine - NewCountTXDecorator = keeper.NewCountTXDecorator - - // variable aliases - ModuleCdc = types.ModuleCdc - DefaultCodespace = types.DefaultCodespace - ErrCreateFailed = types.ErrCreateFailed - ErrAccountExists = types.ErrAccountExists - ErrInstantiateFailed = types.ErrInstantiateFailed - ErrExecuteFailed = types.ErrExecuteFailed - ErrGasLimit = types.ErrGasLimit - ErrInvalidGenesis = types.ErrInvalidGenesis - ErrNotFound = types.ErrNotFound - ErrQueryFailed = types.ErrQueryFailed - ErrInvalidMsg = types.ErrInvalidMsg - KeyLastCodeID = types.KeyLastCodeID - KeyLastInstanceID = types.KeyLastInstanceID - CodeKeyPrefix = types.CodeKeyPrefix - ContractKeyPrefix = types.ContractKeyPrefix - ContractStorePrefix = types.ContractStorePrefix - EnableAllProposals = types.EnableAllProposals - DisableAllProposals = types.DisableAllProposals -) - -type ( - ProposalType = types.ProposalType - GenesisState = types.GenesisState - Code = types.Code - Contract = types.Contract - MsgStoreCode = types.MsgStoreCode - MsgStoreCodeResponse = types.MsgStoreCodeResponse - MsgInstantiateContract = types.MsgInstantiateContract - MsgInstantiateContract2 = types.MsgInstantiateContract2 - MsgInstantiateContractResponse = types.MsgInstantiateContractResponse - MsgExecuteContract = types.MsgExecuteContract - MsgExecuteContractResponse = types.MsgExecuteContractResponse - MsgMigrateContract = types.MsgMigrateContract - MsgMigrateContractResponse = types.MsgMigrateContractResponse - MsgUpdateAdmin = types.MsgUpdateAdmin - MsgUpdateAdminResponse = types.MsgUpdateAdminResponse - MsgClearAdmin = types.MsgClearAdmin - MsgWasmIBCCall = types.MsgIBCSend - MsgClearAdminResponse = types.MsgClearAdminResponse - MsgServer = types.MsgServer - Model = types.Model - CodeInfo = types.CodeInfo - ContractInfo = types.ContractInfo - CreatedAt = types.AbsoluteTxPosition - Config = types.WasmConfig - CodeInfoResponse = types.CodeInfoResponse - MessageHandler = keeper.SDKMessageHandler - BankEncoder = keeper.BankEncoder - CustomEncoder = keeper.CustomEncoder - StakingEncoder = keeper.StakingEncoder - WasmEncoder = keeper.WasmEncoder - MessageEncoders = keeper.MessageEncoders - Keeper = keeper.Keeper - QueryHandler = keeper.QueryHandler - CustomQuerier = keeper.CustomQuerier - QueryPlugins = keeper.QueryPlugins - Option = keeper.Option -) diff --git a/x/wasm/client/cli/new_tx.go b/x/wasm/client/cli/new_tx.go deleted file mode 100644 index 8ce605a..0000000 --- a/x/wasm/client/cli/new_tx.go +++ /dev/null @@ -1,160 +0,0 @@ -package cli - -import ( - "strconv" - - errorsmod "cosmossdk.io/errors" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/tx" - "github.com/spf13/cobra" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// MigrateContractCmd will migrate a contract to a new code version -func MigrateContractCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "migrate [contract_addr_bech32] [new_code_id_int64] [json_encoded_migration_args]", - Short: "Migrate a wasm contract to a new code version", - Aliases: []string{"update", "mig", "m"}, - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - msg, err := parseMigrateContractArgs(args, clientCtx.GetFromAddress().String()) - if err != nil { - return err - } - if err := msg.ValidateBasic(); err != nil { - return nil - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - SilenceUsage: true, - } - flags.AddTxFlagsToCmd(cmd) - return cmd -} - -func parseMigrateContractArgs(args []string, sender string) (types.MsgMigrateContract, error) { - // get the id of the code to instantiate - codeID, err := strconv.ParseUint(args[1], 10, 64) - if err != nil { - return types.MsgMigrateContract{}, errorsmod.Wrap(err, "code id") - } - - migrateMsg := args[2] - - msg := types.MsgMigrateContract{ - Sender: sender, - Contract: args[0], - CodeID: codeID, - Msg: []byte(migrateMsg), - } - return msg, nil -} - -// UpdateContractAdminCmd sets an new admin for a contract -func UpdateContractAdminCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "set-contract-admin [contract_addr_bech32] [new_admin_addr_bech32]", - Short: "Set new admin for a contract", - Aliases: []string{"new-admin", "admin", "set-adm", "sa"}, - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - msg := parseUpdateContractAdminArgs(args, clientCtx.GetFromAddress().String()) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - SilenceUsage: true, - } - flags.AddTxFlagsToCmd(cmd) - return cmd -} - -func parseUpdateContractAdminArgs(args []string, sender string) types.MsgUpdateAdmin { - msg := types.MsgUpdateAdmin{ - Sender: sender, - Contract: args[0], - NewAdmin: args[1], - } - return msg -} - -// ClearContractAdminCmd clears an admin for a contract -func ClearContractAdminCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "clear-contract-admin [contract_addr_bech32]", - Short: "Clears admin for a contract to prevent further migrations", - Aliases: []string{"clear-admin", "clr-adm"}, - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - msg := types.MsgClearAdmin{ - Sender: clientCtx.GetFromAddress().String(), - Contract: args[0], - } - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - SilenceUsage: true, - } - flags.AddTxFlagsToCmd(cmd) - return cmd -} - -// UpdateInstantiateConfigCmd updates instantiate config for a smart contract. -func UpdateInstantiateConfigCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "update-instantiate-config [code_id_int64]", - Short: "Update instantiate config for a codeID", - Aliases: []string{"update-instantiate-config"}, - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - codeID, err := strconv.ParseUint(args[0], 10, 64) - if err != nil { - return err - } - perm, err := parseAccessConfigFlags(cmd.Flags()) - if err != nil { - return err - } - - msg := types.MsgUpdateInstantiateConfig{ - Sender: string(clientCtx.GetFromAddress()), - CodeID: codeID, - NewInstantiatePermission: perm, - } - if err = msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - SilenceUsage: true, - } - - addInstantiatePermissionFlags(cmd) - flags.AddTxFlagsToCmd(cmd) - return cmd -} diff --git a/x/wasm/client/cli/query.go b/x/wasm/client/cli/query.go deleted file mode 100644 index 2971e1e..0000000 --- a/x/wasm/client/cli/query.go +++ /dev/null @@ -1,675 +0,0 @@ -package cli - -import ( - "context" - "encoding/base64" - "encoding/hex" - "encoding/json" - "errors" - "fmt" - "os" - "strconv" - - wasmvm "github.com/CosmWasm/wasmvm" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/spf13/cobra" - flag "github.com/spf13/pflag" - - "github.com/terpnetwork/terp-core/x/wasm/keeper" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func GetQueryCmd() *cobra.Command { - queryCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Querying commands for the wasm module", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - SilenceUsage: true, - } - queryCmd.AddCommand( - GetCmdListCode(), - GetCmdListContractByCode(), - GetCmdQueryCode(), - GetCmdQueryCodeInfo(), - GetCmdGetContractInfo(), - GetCmdGetContractHistory(), - GetCmdGetContractState(), - GetCmdListPinnedCode(), - GetCmdLibVersion(), - GetCmdQueryParams(), - GetCmdBuildAddress(), - GetCmdListContractsByCreator(), - ) - return queryCmd -} - -// GetCmdLibVersion gets current libwasmvm version. -func GetCmdLibVersion() *cobra.Command { - cmd := &cobra.Command{ - Use: "libwasmvm-version", - Short: "Get libwasmvm version", - Long: "Get libwasmvm version", - Aliases: []string{"lib-version"}, - Args: cobra.ExactArgs(0), - RunE: func(cmd *cobra.Command, args []string) error { - version, err := wasmvm.LibwasmvmVersion() - if err != nil { - return fmt.Errorf("error retrieving libwasmvm version: %w", err) - } - fmt.Println(version) - return nil - }, - SilenceUsage: true, - } - return cmd -} - -// GetCmdBuildAddress build a contract address -func GetCmdBuildAddress() *cobra.Command { - decoder := newArgDecoder(hex.DecodeString) - cmd := &cobra.Command{ - Use: "build-address [code-hash] [creator-address] [salt-hex-encoded] [json_encoded_init_args (required when set as fixed)]", - Short: "build contract address", - Aliases: []string{"address"}, - Args: cobra.RangeArgs(3, 4), - RunE: func(cmd *cobra.Command, args []string) error { - codeHash, err := hex.DecodeString(args[0]) - if err != nil { - return fmt.Errorf("code-hash: %s", err) - } - creator, err := sdk.AccAddressFromBech32(args[1]) - if err != nil { - return fmt.Errorf("creator: %s", err) - } - salt, err := hex.DecodeString(args[2]) - switch { - case err != nil: - return fmt.Errorf("salt: %s", err) - case len(salt) == 0: - return errors.New("empty salt") - } - - if len(args) == 3 { - cmd.Println(keeper.BuildContractAddressPredictable(codeHash, creator, salt, []byte{}).String()) - return nil - } - msg := types.RawContractMessage(args[3]) - if err := msg.ValidateBasic(); err != nil { - return fmt.Errorf("init message: %s", err) - } - cmd.Println(keeper.BuildContractAddressPredictable(codeHash, creator, salt, msg).String()) - return nil - }, - SilenceUsage: true, - } - decoder.RegisterFlags(cmd.PersistentFlags(), "salt") - return cmd -} - -// GetCmdListCode lists all wasm code uploaded -func GetCmdListCode() *cobra.Command { - cmd := &cobra.Command{ - Use: "list-code", - Short: "List all wasm bytecode on the chain", - Long: "List all wasm bytecode on the chain", - Aliases: []string{"list-codes", "codes", "lco"}, - Args: cobra.ExactArgs(0), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - pageReq, err := client.ReadPageRequest(withPageKeyDecoded(cmd.Flags())) - if err != nil { - return err - } - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.Codes( - context.Background(), - &types.QueryCodesRequest{ - Pagination: pageReq, - }, - ) - if err != nil { - return err - } - return clientCtx.PrintProto(res) - }, - SilenceUsage: true, - } - flags.AddQueryFlagsToCmd(cmd) - flags.AddPaginationFlagsToCmd(cmd, "list codes") - return cmd -} - -// GetCmdListContractByCode lists all wasm code uploaded for given code id -func GetCmdListContractByCode() *cobra.Command { - cmd := &cobra.Command{ - Use: "list-contract-by-code [code_id]", - Short: "List wasm all bytecode on the chain for given code id", - Long: "List wasm all bytecode on the chain for given code id", - Aliases: []string{"list-contracts-by-code", "list-contracts", "contracts", "lca"}, - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - codeID, err := strconv.ParseUint(args[0], 10, 64) - if err != nil { - return err - } - if codeID == 0 { - return errors.New("empty code id") - } - - pageReq, err := client.ReadPageRequest(withPageKeyDecoded(cmd.Flags())) - if err != nil { - return err - } - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.ContractsByCode( - context.Background(), - &types.QueryContractsByCodeRequest{ - CodeId: codeID, - Pagination: pageReq, - }, - ) - if err != nil { - return err - } - return clientCtx.PrintProto(res) - }, - SilenceUsage: true, - } - flags.AddQueryFlagsToCmd(cmd) - flags.AddPaginationFlagsToCmd(cmd, "list contracts by code") - return cmd -} - -// GetCmdQueryCode returns the bytecode for a given contract -func GetCmdQueryCode() *cobra.Command { - cmd := &cobra.Command{ - Use: "code [code_id] [output filename]", - Short: "Downloads wasm bytecode for given code id", - Long: "Downloads wasm bytecode for given code id", - Aliases: []string{"source-code", "source"}, - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - codeID, err := strconv.ParseUint(args[0], 10, 64) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.Code( - context.Background(), - &types.QueryCodeRequest{ - CodeId: codeID, - }, - ) - if err != nil { - return err - } - if len(res.Data) == 0 { - return fmt.Errorf("contract not found") - } - - fmt.Printf("Downloading wasm code to %s\n", args[1]) - return os.WriteFile(args[1], res.Data, 0o600) - }, - SilenceUsage: true, - } - flags.AddQueryFlagsToCmd(cmd) - return cmd -} - -// GetCmdQueryCodeInfo returns the code info for a given code id -func GetCmdQueryCodeInfo() *cobra.Command { - cmd := &cobra.Command{ - Use: "code-info [code_id]", - Short: "Prints out metadata of a code id", - Long: "Prints out metadata of a code id", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - codeID, err := strconv.ParseUint(args[0], 10, 64) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.Code( - context.Background(), - &types.QueryCodeRequest{ - CodeId: codeID, - }, - ) - if err != nil { - return err - } - if res.CodeInfoResponse == nil { - return fmt.Errorf("contract not found") - } - - return clientCtx.PrintProto(res.CodeInfoResponse) - }, - SilenceUsage: true, - } - flags.AddQueryFlagsToCmd(cmd) - return cmd -} - -// GetCmdGetContractInfo gets details about a given contract -func GetCmdGetContractInfo() *cobra.Command { - cmd := &cobra.Command{ - Use: "contract [bech32_address]", - Short: "Prints out metadata of a contract given its address", - Long: "Prints out metadata of a contract given its address", - Aliases: []string{"meta", "c"}, - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - _, err = sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.ContractInfo( - context.Background(), - &types.QueryContractInfoRequest{ - Address: args[0], - }, - ) - if err != nil { - return err - } - return clientCtx.PrintProto(res) - }, - SilenceUsage: true, - } - flags.AddQueryFlagsToCmd(cmd) - return cmd -} - -// GetCmdGetContractState dumps full internal state of a given contract -func GetCmdGetContractState() *cobra.Command { - cmd := &cobra.Command{ - Use: "contract-state", - Short: "Querying commands for the wasm module", - Aliases: []string{"state", "cs", "s"}, - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - SilenceUsage: true, - } - cmd.AddCommand( - GetCmdGetContractStateAll(), - GetCmdGetContractStateRaw(), - GetCmdGetContractStateSmart(), - ) - return cmd -} - -func GetCmdGetContractStateAll() *cobra.Command { - cmd := &cobra.Command{ - Use: "all [bech32_address]", - Short: "Prints out all internal state of a contract given its address", - Long: "Prints out all internal state of a contract given its address", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - _, err = sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - - pageReq, err := client.ReadPageRequest(withPageKeyDecoded(cmd.Flags())) - if err != nil { - return err - } - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.AllContractState( - context.Background(), - &types.QueryAllContractStateRequest{ - Address: args[0], - Pagination: pageReq, - }, - ) - if err != nil { - return err - } - return clientCtx.PrintProto(res) - }, - SilenceUsage: true, - } - flags.AddQueryFlagsToCmd(cmd) - flags.AddPaginationFlagsToCmd(cmd, "contract state") - return cmd -} - -func GetCmdGetContractStateRaw() *cobra.Command { - decoder := newArgDecoder(hex.DecodeString) - cmd := &cobra.Command{ - Use: "raw [bech32_address] [key]", - Short: "Prints out internal state for key of a contract given its address", - Long: "Prints out internal state for of a contract given its address", - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - _, err = sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - queryData, err := decoder.DecodeString(args[1]) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.RawContractState( - context.Background(), - &types.QueryRawContractStateRequest{ - Address: args[0], - QueryData: queryData, - }, - ) - if err != nil { - return err - } - return clientCtx.PrintProto(res) - }, - SilenceUsage: true, - } - decoder.RegisterFlags(cmd.PersistentFlags(), "key argument") - flags.AddQueryFlagsToCmd(cmd) - return cmd -} - -func GetCmdGetContractStateSmart() *cobra.Command { - decoder := newArgDecoder(asciiDecodeString) - cmd := &cobra.Command{ - Use: "smart [bech32_address] [query]", - Short: "Calls contract with given address with query data and prints the returned result", - Long: "Calls contract with given address with query data and prints the returned result", - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - _, err = sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - if args[1] == "" { - return errors.New("query data must not be empty") - } - - queryData, err := decoder.DecodeString(args[1]) - if err != nil { - return fmt.Errorf("decode query: %s", err) - } - if !json.Valid(queryData) { - return errors.New("query data must be json") - } - - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.SmartContractState( - context.Background(), - &types.QuerySmartContractStateRequest{ - Address: args[0], - QueryData: queryData, - }, - ) - if err != nil { - return err - } - return clientCtx.PrintProto(res) - }, - SilenceUsage: true, - } - decoder.RegisterFlags(cmd.PersistentFlags(), "query argument") - flags.AddQueryFlagsToCmd(cmd) - return cmd -} - -// GetCmdGetContractHistory prints the code history for a given contract -func GetCmdGetContractHistory() *cobra.Command { - cmd := &cobra.Command{ - Use: "contract-history [bech32_address]", - Short: "Prints out the code history for a contract given its address", - Long: "Prints out the code history for a contract given its address", - Aliases: []string{"history", "hist", "ch"}, - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - _, err = sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - - pageReq, err := client.ReadPageRequest(withPageKeyDecoded(cmd.Flags())) - if err != nil { - return err - } - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.ContractHistory( - context.Background(), - &types.QueryContractHistoryRequest{ - Address: args[0], - Pagination: pageReq, - }, - ) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - SilenceUsage: true, - } - - flags.AddQueryFlagsToCmd(cmd) - flags.AddPaginationFlagsToCmd(cmd, "contract history") - return cmd -} - -// GetCmdListPinnedCode lists all wasm code ids that are pinned -func GetCmdListPinnedCode() *cobra.Command { - cmd := &cobra.Command{ - Use: "pinned", - Short: "List all pinned code ids", - Long: "List all pinned code ids", - Args: cobra.ExactArgs(0), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - pageReq, err := client.ReadPageRequest(withPageKeyDecoded(cmd.Flags())) - if err != nil { - return err - } - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.PinnedCodes( - context.Background(), - &types.QueryPinnedCodesRequest{ - Pagination: pageReq, - }, - ) - if err != nil { - return err - } - return clientCtx.PrintProto(res) - }, - SilenceUsage: true, - } - flags.AddQueryFlagsToCmd(cmd) - flags.AddPaginationFlagsToCmd(cmd, "list codes") - return cmd -} - -// GetCmdListContractsByCreator lists all contracts by creator -func GetCmdListContractsByCreator() *cobra.Command { - cmd := &cobra.Command{ - Use: "list-contracts-by-creator [creator]", - Short: "List all contracts by creator", - Long: "List all contracts by creator", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - _, err = sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - pageReq, err := client.ReadPageRequest(withPageKeyDecoded(cmd.Flags())) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.ContractsByCreator( - context.Background(), - &types.QueryContractsByCreatorRequest{ - CreatorAddress: args[0], - Pagination: pageReq, - }, - ) - if err != nil { - return err - } - return clientCtx.PrintProto(res) - }, - SilenceUsage: true, - } - flags.AddQueryFlagsToCmd(cmd) - flags.AddPaginationFlagsToCmd(cmd, "list contracts by creator") - return cmd -} - -type argumentDecoder struct { - // dec is the default decoder - dec func(string) ([]byte, error) - asciiF, hexF, b64F bool -} - -func newArgDecoder(def func(string) ([]byte, error)) *argumentDecoder { - return &argumentDecoder{dec: def} -} - -func (a *argumentDecoder) RegisterFlags(f *flag.FlagSet, argName string) { - f.BoolVar(&a.asciiF, "ascii", false, "ascii encoded "+argName) - f.BoolVar(&a.hexF, "hex", false, "hex encoded "+argName) - f.BoolVar(&a.b64F, "b64", false, "base64 encoded "+argName) -} - -func (a *argumentDecoder) DecodeString(s string) ([]byte, error) { - found := -1 - for i, v := range []*bool{&a.asciiF, &a.hexF, &a.b64F} { - if !*v { - continue - } - if found != -1 { - return nil, errors.New("multiple decoding flags used") - } - found = i - } - switch found { - case 0: - return asciiDecodeString(s) - case 1: - return hex.DecodeString(s) - case 2: - return base64.StdEncoding.DecodeString(s) - default: - return a.dec(s) - } -} - -func asciiDecodeString(s string) ([]byte, error) { - return []byte(s), nil -} - -// sdk ReadPageRequest expects binary but we encoded to base64 in our marshaller -func withPageKeyDecoded(flagSet *flag.FlagSet) *flag.FlagSet { - encoded, err := flagSet.GetString(flags.FlagPageKey) - if err != nil { - panic(err.Error()) - } - raw, err := base64.StdEncoding.DecodeString(encoded) - if err != nil { - panic(err.Error()) - } - err = flagSet.Set(flags.FlagPageKey, string(raw)) - if err != nil { - panic(err.Error()) - } - return flagSet -} - -// GetCmdQueryParams implements a command to return the current wasm -// parameters. -func GetCmdQueryParams() *cobra.Command { - cmd := &cobra.Command{ - Use: "params", - Short: "Query the current wasm parameters", - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - queryClient := types.NewQueryClient(clientCtx) - - params := &types.QueryParamsRequest{} - res, err := queryClient.Params(cmd.Context(), params) - if err != nil { - return err - } - - return clientCtx.PrintProto(&res.Params) - }, - SilenceUsage: true, - } - - flags.AddQueryFlagsToCmd(cmd) - - return cmd -} diff --git a/x/wasm/client/cli/tx.go b/x/wasm/client/cli/tx.go deleted file mode 100644 index 6131620..0000000 --- a/x/wasm/client/cli/tx.go +++ /dev/null @@ -1,566 +0,0 @@ -package cli - -import ( - "encoding/hex" - "errors" - "fmt" - "os" - "strconv" - "time" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/tx" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" - "github.com/cosmos/cosmos-sdk/x/authz" - "github.com/spf13/cobra" - flag "github.com/spf13/pflag" - - "github.com/terpnetwork/terp-core/x/wasm/ioutils" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -const ( - flagAmount = "amount" - flagLabel = "label" - flagSource = "code-source-url" - flagBuilder = "builder" - flagCodeHash = "code-hash" - flagAdmin = "admin" - flagNoAdmin = "no-admin" - flagFixMsg = "fix-msg" - flagRunAs = "run-as" - flagInstantiateByEverybody = "instantiate-everybody" - flagInstantiateNobody = "instantiate-nobody" - flagInstantiateByAddress = "instantiate-only-address" - flagInstantiateByAnyOfAddress = "instantiate-anyof-addresses" - flagUnpinCode = "unpin-code" - flagAllowedMsgKeys = "allow-msg-keys" - flagAllowedRawMsgs = "allow-raw-msgs" - flagExpiration = "expiration" - flagMaxCalls = "max-calls" - flagMaxFunds = "max-funds" - flagAllowAllMsgs = "allow-all-messages" - flagNoTokenTransfer = "no-token-transfer" //nolint:gosec -) - -// GetTxCmd returns the transaction commands for this module -func GetTxCmd() *cobra.Command { - txCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Wasm transaction subcommands", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - SilenceUsage: true, - } - txCmd.AddCommand( - StoreCodeCmd(), - InstantiateContractCmd(), - InstantiateContract2Cmd(), - ExecuteContractCmd(), - MigrateContractCmd(), - UpdateContractAdminCmd(), - ClearContractAdminCmd(), - GrantAuthorizationCmd(), - UpdateInstantiateConfigCmd(), - ) - return txCmd -} - -// StoreCodeCmd will upload code to be reused. -func StoreCodeCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "store [wasm file]", - Short: "Upload a wasm binary", - Aliases: []string{"upload", "st", "s"}, - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - msg, err := parseStoreCodeArgs(args[0], clientCtx.GetFromAddress().String(), cmd.Flags()) - if err != nil { - return err - } - if err = msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - SilenceUsage: true, - } - - addInstantiatePermissionFlags(cmd) - flags.AddTxFlagsToCmd(cmd) - return cmd -} - -// Prepares MsgStoreCode object from flags with gzipped wasm byte code field -func parseStoreCodeArgs(file string, sender string, flags *flag.FlagSet) (types.MsgStoreCode, error) { - wasm, err := os.ReadFile(file) - if err != nil { - return types.MsgStoreCode{}, err - } - - // gzip the wasm file - if ioutils.IsWasm(wasm) { - wasm, err = ioutils.GzipIt(wasm) - - if err != nil { - return types.MsgStoreCode{}, err - } - } else if !ioutils.IsGzip(wasm) { - return types.MsgStoreCode{}, fmt.Errorf("invalid input file. Use wasm binary or gzip") - } - - perm, err := parseAccessConfigFlags(flags) - if err != nil { - return types.MsgStoreCode{}, err - } - - msg := types.MsgStoreCode{ - Sender: sender, - WASMByteCode: wasm, - InstantiatePermission: perm, - } - return msg, nil -} - -func parseAccessConfigFlags(flags *flag.FlagSet) (*types.AccessConfig, error) { - addrs, err := flags.GetStringSlice(flagInstantiateByAnyOfAddress) - if err != nil { - return nil, fmt.Errorf("flag any of: %s", err) - } - if len(addrs) != 0 { - acceptedAddrs := make([]sdk.AccAddress, len(addrs)) - for i, v := range addrs { - acceptedAddrs[i], err = sdk.AccAddressFromBech32(v) - if err != nil { - return nil, fmt.Errorf("parse %q: %w", v, err) - } - } - x := types.AccessTypeAnyOfAddresses.With(acceptedAddrs...) - return &x, nil - } - - onlyAddrStr, err := flags.GetString(flagInstantiateByAddress) - if err != nil { - return nil, fmt.Errorf("instantiate by address: %s", err) - } - if onlyAddrStr != "" { - return nil, fmt.Errorf("not supported anymore. Use: %s", flagInstantiateByAnyOfAddress) - } - everybodyStr, err := flags.GetString(flagInstantiateByEverybody) - if err != nil { - return nil, fmt.Errorf("instantiate by everybody: %s", err) - } - if everybodyStr != "" { - ok, err := strconv.ParseBool(everybodyStr) - if err != nil { - return nil, fmt.Errorf("boolean value expected for instantiate by everybody: %s", err) - } - if ok { - return &types.AllowEverybody, nil - } - } - - nobodyStr, err := flags.GetString(flagInstantiateNobody) - if err != nil { - return nil, fmt.Errorf("instantiate by nobody: %s", err) - } - if nobodyStr != "" { - ok, err := strconv.ParseBool(nobodyStr) - if err != nil { - return nil, fmt.Errorf("boolean value expected for instantiate by nobody: %s", err) - } - if ok { - return &types.AllowNobody, nil - } - } - return nil, nil -} - -func addInstantiatePermissionFlags(cmd *cobra.Command) { - cmd.Flags().String(flagInstantiateByEverybody, "", "Everybody can instantiate a contract from the code, optional") - cmd.Flags().String(flagInstantiateNobody, "", "Nobody except the governance process can instantiate a contract from the code, optional") - cmd.Flags().String(flagInstantiateByAddress, "", fmt.Sprintf("Removed: use %s instead", flagInstantiateByAnyOfAddress)) - cmd.Flags().StringSlice(flagInstantiateByAnyOfAddress, []string{}, "Any of the addresses can instantiate a contract from the code, optional") -} - -// InstantiateContractCmd will instantiate a contract from previously uploaded code. -func InstantiateContractCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "instantiate [code_id_int64] [json_encoded_init_args] --label [text] --admin [address,optional] --amount [coins,optional] ", - Short: "Instantiate a wasm contract", - Long: fmt.Sprintf(`Creates a new instance of an uploaded wasm code with the given 'constructor' message. -Each contract instance has a unique address assigned. -Example: -$ %s tx wasm instantiate 1 '{"foo":"bar"}' --admin="$(%s keys show mykey -a)" \ - --from mykey --amount="100ustake" --label "local0.1.0" -`, version.AppName, version.AppName), - Aliases: []string{"start", "init", "inst", "i"}, - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - msg, err := parseInstantiateArgs(args[0], args[1], clientCtx.Keyring, clientCtx.GetFromAddress().String(), cmd.Flags()) - if err != nil { - return err - } - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - SilenceUsage: true, - } - - cmd.Flags().String(flagAmount, "", "Coins to send to the contract during instantiation") - cmd.Flags().String(flagLabel, "", "A human-readable name for this contract in lists") - cmd.Flags().String(flagAdmin, "", "Address or key name of an admin") - cmd.Flags().Bool(flagNoAdmin, false, "You must set this explicitly if you don't want an admin") - flags.AddTxFlagsToCmd(cmd) - return cmd -} - -// InstantiateContract2Cmd will instantiate a contract from previously uploaded code with predicable address generated -func InstantiateContract2Cmd() *cobra.Command { - decoder := newArgDecoder(hex.DecodeString) - cmd := &cobra.Command{ - Use: "instantiate2 [code_id_int64] [json_encoded_init_args] [salt] --label [text] --admin [address,optional] --amount [coins,optional] " + - "--fix-msg [bool,optional]", - Short: "Instantiate a wasm contract with predictable address", - Long: fmt.Sprintf(`Creates a new instance of an uploaded wasm code with the given 'constructor' message. -Each contract instance has a unique address assigned. They are assigned automatically but in order to have predictable addresses -for special use cases, the given 'salt' argument and '--fix-msg' parameters can be used to generate a custom address. - -Predictable address example (also see '%s query wasm build-address -h'): -$ %s tx wasm instantiate2 1 '{"foo":"bar"}' $(echo -n "testing" | xxd -ps) --admin="$(%s keys show mykey -a)" \ - --from mykey --amount="100ustake" --label "local0.1.0" \ - --fix-msg -`, version.AppName, version.AppName, version.AppName), - Aliases: []string{"start", "init", "inst", "i"}, - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - salt, err := decoder.DecodeString(args[2]) - if err != nil { - return fmt.Errorf("salt: %w", err) - } - fixMsg, err := cmd.Flags().GetBool(flagFixMsg) - if err != nil { - return fmt.Errorf("fix msg: %w", err) - } - data, err := parseInstantiateArgs(args[0], args[1], clientCtx.Keyring, clientCtx.GetFromAddress().String(), cmd.Flags()) - if err != nil { - return err - } - msg := &types.MsgInstantiateContract2{ - Sender: data.Sender, - Admin: data.Admin, - CodeID: data.CodeID, - Label: data.Label, - Msg: data.Msg, - Funds: data.Funds, - Salt: salt, - FixMsg: fixMsg, - } - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - SilenceUsage: true, - } - - cmd.Flags().String(flagAmount, "", "Coins to send to the contract during instantiation") - cmd.Flags().String(flagLabel, "", "A human-readable name for this contract in lists") - cmd.Flags().String(flagAdmin, "", "Address or key name of an admin") - cmd.Flags().Bool(flagNoAdmin, false, "You must set this explicitly if you don't want an admin") - cmd.Flags().Bool(flagFixMsg, false, "An optional flag to include the json_encoded_init_args for the predictable address generation mode") - decoder.RegisterFlags(cmd.PersistentFlags(), "salt") - flags.AddTxFlagsToCmd(cmd) - return cmd -} - -func parseInstantiateArgs(rawCodeID, initMsg string, kr keyring.Keyring, sender string, flags *flag.FlagSet) (*types.MsgInstantiateContract, error) { - // get the id of the code to instantiate - codeID, err := strconv.ParseUint(rawCodeID, 10, 64) - if err != nil { - return nil, err - } - - amountStr, err := flags.GetString(flagAmount) - if err != nil { - return nil, fmt.Errorf("amount: %s", err) - } - amount, err := sdk.ParseCoinsNormalized(amountStr) - if err != nil { - return nil, fmt.Errorf("amount: %s", err) - } - label, err := flags.GetString(flagLabel) - if err != nil { - return nil, fmt.Errorf("label: %s", err) - } - if label == "" { - return nil, errors.New("label is required on all contracts") - } - adminStr, err := flags.GetString(flagAdmin) - if err != nil { - return nil, fmt.Errorf("admin: %s", err) - } - - noAdmin, err := flags.GetBool(flagNoAdmin) - if err != nil { - return nil, fmt.Errorf("no-admin: %s", err) - } - - // ensure sensible admin is set (or explicitly immutable) - if adminStr == "" && !noAdmin { - return nil, fmt.Errorf("you must set an admin or explicitly pass --no-admin to make it immutible (wasmd issue #719)") - } - if adminStr != "" && noAdmin { - return nil, fmt.Errorf("you set an admin and passed --no-admin, those cannot both be true") - } - - if adminStr != "" { - addr, err := sdk.AccAddressFromBech32(adminStr) - if err != nil { - info, err := kr.Key(adminStr) - if err != nil { - return nil, fmt.Errorf("admin %s", err) - } - admin, err := info.GetAddress() - if err != nil { - return nil, err - } - adminStr = admin.String() - } else { - adminStr = addr.String() - } - } - - // build and sign the transaction, then broadcast to Tendermint - msg := types.MsgInstantiateContract{ - Sender: sender, - CodeID: codeID, - Label: label, - Funds: amount, - Msg: []byte(initMsg), - Admin: adminStr, - } - return &msg, nil -} - -// ExecuteContractCmd will instantiate a contract from previously uploaded code. -func ExecuteContractCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "execute [contract_addr_bech32] [json_encoded_send_args] --amount [coins,optional]", - Short: "Execute a command on a wasm contract", - Aliases: []string{"run", "call", "exec", "ex", "e"}, - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - msg, err := parseExecuteArgs(args[0], args[1], clientCtx.GetFromAddress(), cmd.Flags()) - if err != nil { - return err - } - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - SilenceUsage: true, - } - - cmd.Flags().String(flagAmount, "", "Coins to send to the contract along with command") - flags.AddTxFlagsToCmd(cmd) - return cmd -} - -func parseExecuteArgs(contractAddr string, execMsg string, sender sdk.AccAddress, flags *flag.FlagSet) (types.MsgExecuteContract, error) { - amountStr, err := flags.GetString(flagAmount) - if err != nil { - return types.MsgExecuteContract{}, fmt.Errorf("amount: %s", err) - } - - amount, err := sdk.ParseCoinsNormalized(amountStr) - if err != nil { - return types.MsgExecuteContract{}, err - } - - return types.MsgExecuteContract{ - Sender: sender.String(), - Contract: contractAddr, - Funds: amount, - Msg: []byte(execMsg), - }, nil -} - -func GrantAuthorizationCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "grant [grantee] [message_type=\"execution\"|\"migration\"] [contract_addr_bech32] --allow-raw-msgs [msg1,msg2,...] --allow-msg-keys [key1,key2,...] --allow-all-messages", - Short: "Grant authorization to an address", - Long: fmt.Sprintf(`Grant authorization to an address. -Examples: -$ %s tx grant execution --allow-all-messages --max-calls 1 --no-token-transfer --expiration 1667979596 - -$ %s tx grant execution --allow-all-messages --max-funds 100000uwasm --expiration 1667979596 - -$ %s tx grant execution --allow-all-messages --max-calls 5 --max-funds 100000uwasm --expiration 1667979596 -`, version.AppName, version.AppName, version.AppName), - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - grantee, err := sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - - contract, err := sdk.AccAddressFromBech32(args[2]) - if err != nil { - return err - } - - msgKeys, err := cmd.Flags().GetStringSlice(flagAllowedMsgKeys) - if err != nil { - return err - } - - rawMsgs, err := cmd.Flags().GetStringSlice(flagAllowedRawMsgs) - if err != nil { - return err - } - - maxFundsStr, err := cmd.Flags().GetString(flagMaxFunds) - if err != nil { - return fmt.Errorf("max funds: %s", err) - } - - maxCalls, err := cmd.Flags().GetUint64(flagMaxCalls) - if err != nil { - return err - } - - exp, err := cmd.Flags().GetInt64(flagExpiration) - if err != nil { - return err - } - if exp == 0 { - return errors.New("expiration must be set") - } - - allowAllMsgs, err := cmd.Flags().GetBool(flagAllowAllMsgs) - if err != nil { - return err - } - - noTokenTransfer, err := cmd.Flags().GetBool(flagNoTokenTransfer) - if err != nil { - return err - } - - var limit types.ContractAuthzLimitX - switch { - case maxFundsStr != "" && maxCalls != 0 && !noTokenTransfer: - maxFunds, err := sdk.ParseCoinsNormalized(maxFundsStr) - if err != nil { - return fmt.Errorf("max funds: %s", err) - } - limit = types.NewCombinedLimit(maxCalls, maxFunds...) - case maxFundsStr != "" && maxCalls == 0 && !noTokenTransfer: - maxFunds, err := sdk.ParseCoinsNormalized(maxFundsStr) - if err != nil { - return fmt.Errorf("max funds: %s", err) - } - limit = types.NewMaxFundsLimit(maxFunds...) - case maxCalls != 0 && noTokenTransfer && maxFundsStr == "": - limit = types.NewMaxCallsLimit(maxCalls) - default: - return errors.New("invalid limit setup") - } - - var filter types.ContractAuthzFilterX - switch { - case allowAllMsgs && len(msgKeys) != 0 || allowAllMsgs && len(rawMsgs) != 0 || len(msgKeys) != 0 && len(rawMsgs) != 0: - return errors.New("cannot set more than one filter within one grant") - case allowAllMsgs: - filter = types.NewAllowAllMessagesFilter() - case len(msgKeys) != 0: - filter = types.NewAcceptedMessageKeysFilter(msgKeys...) - case len(rawMsgs) != 0: - msgs := make([]types.RawContractMessage, len(rawMsgs)) - for i, msg := range rawMsgs { - msgs[i] = types.RawContractMessage(msg) - } - filter = types.NewAcceptedMessagesFilter(msgs...) - default: - return errors.New("invalid filter setup") - } - - grant, err := types.NewContractGrant(contract, limit, filter) - if err != nil { - return err - } - - var authorization authz.Authorization - switch args[1] { - case "execution": - authorization = types.NewContractExecutionAuthorization(*grant) - case "migration": - authorization = types.NewContractMigrationAuthorization(*grant) - default: - return fmt.Errorf("%s authorization type not supported", args[1]) - } - - expire, err := getExpireTime(cmd) - if err != nil { - return err - } - - grantMsg, err := authz.NewMsgGrant(clientCtx.GetFromAddress(), grantee, authorization, expire) - if err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), grantMsg) - }, - } - flags.AddTxFlagsToCmd(cmd) - cmd.Flags().StringSlice(flagAllowedMsgKeys, []string{}, "Allowed msg keys") - cmd.Flags().StringSlice(flagAllowedRawMsgs, []string{}, "Allowed raw msgs") - cmd.Flags().Uint64(flagMaxCalls, 0, "Maximal number of calls to the contract") - cmd.Flags().String(flagMaxFunds, "", "Maximal amount of tokens transferable to the contract.") - cmd.Flags().Int64(flagExpiration, 0, "The Unix timestamp.") - cmd.Flags().Bool(flagAllowAllMsgs, false, "Allow all messages") - cmd.Flags().Bool(flagNoTokenTransfer, false, "Don't allow token transfer") - return cmd -} - -func getExpireTime(cmd *cobra.Command) (*time.Time, error) { - exp, err := cmd.Flags().GetInt64(flagExpiration) - if err != nil { - return nil, err - } - if exp == 0 { - return nil, nil - } - e := time.Unix(exp, 0) - return &e, nil -} diff --git a/x/wasm/client/cli/tx_test.go b/x/wasm/client/cli/tx_test.go deleted file mode 100644 index 0521f5e..0000000 --- a/x/wasm/client/cli/tx_test.go +++ /dev/null @@ -1,59 +0,0 @@ -package cli - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestParseAccessConfigFlags(t *testing.T) { - specs := map[string]struct { - args []string - expCfg *types.AccessConfig - expErr bool - }{ - "nobody": { - args: []string{"--instantiate-nobody=true"}, - expCfg: &types.AccessConfig{Permission: types.AccessTypeNobody}, - }, - "everybody": { - args: []string{"--instantiate-everybody=true"}, - expCfg: &types.AccessConfig{Permission: types.AccessTypeEverybody}, - }, - "only address": { - args: []string{"--instantiate-only-address=cosmos1vx8knpllrj7n963p9ttd80w47kpacrhuts497x"}, - expErr: true, - }, - "only address - invalid": { - args: []string{"--instantiate-only-address=foo"}, - expErr: true, - }, - "any of address": { - args: []string{"--instantiate-anyof-addresses=cosmos1vx8knpllrj7n963p9ttd80w47kpacrhuts497x,cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr"}, - expCfg: &types.AccessConfig{Permission: types.AccessTypeAnyOfAddresses, Addresses: []string{"cosmos1vx8knpllrj7n963p9ttd80w47kpacrhuts497x", "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr"}}, - }, - "any of address - invalid": { - args: []string{"--instantiate-anyof-addresses=cosmos1vx8knpllrj7n963p9ttd80w47kpacrhuts497x,foo"}, - expErr: true, - }, - "not set": { - args: []string{}, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - flags := StoreCodeCmd().Flags() - require.NoError(t, flags.Parse(spec.args)) - gotCfg, gotErr := parseAccessConfigFlags(flags) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - assert.Equal(t, spec.expCfg, gotCfg) - }) - } -} diff --git a/x/wasm/common_test.go b/x/wasm/common_test.go deleted file mode 100644 index 4500abe..0000000 --- a/x/wasm/common_test.go +++ /dev/null @@ -1,35 +0,0 @@ -package wasm - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" -) - -// ensure store code returns the expected response -func assertStoreCodeResponse(t *testing.T, data []byte, expected uint64) { - var pStoreResp MsgStoreCodeResponse - require.NoError(t, pStoreResp.Unmarshal(data)) - require.Equal(t, pStoreResp.CodeID, expected) -} - -// ensure execution returns the expected data -func assertExecuteResponse(t *testing.T, data []byte, expected []byte) { - var pExecResp MsgExecuteContractResponse - require.NoError(t, pExecResp.Unmarshal(data)) - require.Equal(t, pExecResp.Data, expected) -} - -// ensures this returns a valid bech32 address and returns it -func parseInitResponse(t *testing.T, data []byte) string { - t.Helper() - var pInstResp MsgInstantiateContractResponse - require.NoError(t, pInstResp.Unmarshal(data)) - require.NotEmpty(t, pInstResp.Address) - addr := pInstResp.Address - // ensure this is a valid sdk address - _, err := sdk.AccAddressFromBech32(addr) - require.NoError(t, err) - return addr -} diff --git a/x/wasm/exported/exported.go b/x/wasm/exported/exported.go deleted file mode 100644 index 000114e..0000000 --- a/x/wasm/exported/exported.go +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 83d5db2..0000000 --- a/x/wasm/genesis_test.go +++ /dev/null @@ -1,99 +0,0 @@ -package wasm - -import ( - "encoding/json" - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" -) - -func TestInitGenesis(t *testing.T) { - data := setupTest(t) - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) - creator := data.faucet.NewFundedRandomAccount(data.ctx, deposit.Add(deposit...)...) - fred := data.faucet.NewFundedRandomAccount(data.ctx, topUp...) - - msg := MsgStoreCode{ - Sender: creator.String(), - WASMByteCode: testContract, - } - h := data.msgServiceRouter.Handler(&msg) - q := data.grpcQueryRouter - - err := msg.ValidateBasic() - require.NoError(t, err) - - res, err := h(data.ctx, &msg) - require.NoError(t, err) - assertStoreCodeResponse(t, res.Data, 1) - - bob := keyPubAddr() - initMsg := initMsg{ - Verifier: fred, - Beneficiary: bob, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - - instMsg := MsgInstantiateContract{ - Sender: creator.String(), - CodeID: firstCodeID, - Msg: initMsgBz, - Funds: deposit, - Label: "testing", - } - h = data.msgServiceRouter.Handler(&instMsg) - res, err = h(data.ctx, &instMsg) - require.NoError(t, err) - contractBech32Addr := parseInitResponse(t, res.Data) - - execMsg := MsgExecuteContract{ - Sender: fred.String(), - Contract: contractBech32Addr, - Msg: []byte(`{"release":{}}`), - Funds: topUp, - } - h = data.msgServiceRouter.Handler(&execMsg) - res, err = h(data.ctx, &execMsg) - require.NoError(t, err) - // from https://github.com/CosmWasm/cosmwasm/blob/master/contracts/hackatom/src/contract.rs#L167 - assertExecuteResponse(t, res.Data, []byte{0xf0, 0x0b, 0xaa}) - - // ensure all contract state is as after init - assertCodeList(t, q, data.ctx, 1, data.encConf.Marshaler) - assertCodeBytes(t, q, data.ctx, 1, testContract, data.encConf.Marshaler) - - assertContractList(t, q, data.ctx, 1, []string{contractBech32Addr}, data.encConf.Marshaler) - assertContractInfo(t, q, data.ctx, contractBech32Addr, 1, creator, data.encConf.Marshaler) - assertContractState(t, q, data.ctx, contractBech32Addr, state{ - Verifier: fred.String(), - Beneficiary: bob.String(), - Funder: creator.String(), - }, data.encConf.Marshaler) - - // export into genstate - genState := ExportGenesis(data.ctx, &data.keeper) - - // create new app to import genstate into - newData := setupTest(t) - q2 := newData.grpcQueryRouter - - // initialize new app with genstate - _, err = InitGenesis(newData.ctx, &newData.keeper, *genState) - require.NoError(t, err) - - // run same checks again on newdata, to make sure it was reinitialized correctly - assertCodeList(t, q2, newData.ctx, 1, data.encConf.Marshaler) - assertCodeBytes(t, q2, newData.ctx, 1, testContract, data.encConf.Marshaler) - - assertContractList(t, q2, newData.ctx, 1, []string{contractBech32Addr}, data.encConf.Marshaler) - assertContractInfo(t, q2, newData.ctx, contractBech32Addr, 1, creator, data.encConf.Marshaler) - assertContractState(t, q2, newData.ctx, contractBech32Addr, state{ - Verifier: fred.String(), - Beneficiary: bob.String(), - Funder: creator.String(), - }, data.encConf.Marshaler) -} diff --git a/x/wasm/ibc.go b/x/wasm/ibc.go deleted file mode 100644 index cf06e64..0000000 --- a/x/wasm/ibc.go +++ /dev/null @@ -1,357 +0,0 @@ -package wasm - -import ( - "math" - - errorsmod "cosmossdk.io/errors" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - sdk "github.com/cosmos/cosmos-sdk/types" - capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - porttypes "github.com/cosmos/ibc-go/v7/modules/core/05-port/types" - host "github.com/cosmos/ibc-go/v7/modules/core/24-host" - ibcexported "github.com/cosmos/ibc-go/v7/modules/core/exported" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -var _ porttypes.IBCModule = IBCHandler{} - -// internal interface that is implemented by ibc middleware -type appVersionGetter interface { - // GetAppVersion returns the application level version with all middleware data stripped out - GetAppVersion(ctx sdk.Context, portID, channelID string) (string, bool) -} - -type IBCHandler struct { - keeper types.IBCContractKeeper - channelKeeper types.ChannelKeeper - appVersionGetter appVersionGetter -} - -func NewIBCHandler(k types.IBCContractKeeper, ck types.ChannelKeeper, vg appVersionGetter) IBCHandler { - return IBCHandler{keeper: k, channelKeeper: ck, appVersionGetter: vg} -} - -// OnChanOpenInit implements the IBCModule interface -func (i IBCHandler) OnChanOpenInit( - ctx sdk.Context, - order channeltypes.Order, - connectionHops []string, - portID string, - channelID string, - chanCap *capabilitytypes.Capability, - counterParty channeltypes.Counterparty, - version string, -) (string, error) { - // ensure port, version, capability - if err := ValidateChannelParams(channelID); err != nil { - return "", err - } - contractAddr, err := ContractFromPortID(portID) - if err != nil { - return "", errorsmod.Wrapf(err, "contract port id") - } - - msg := wasmvmtypes.IBCChannelOpenMsg{ - OpenInit: &wasmvmtypes.IBCOpenInit{ - Channel: wasmvmtypes.IBCChannel{ - Endpoint: wasmvmtypes.IBCEndpoint{PortID: portID, ChannelID: channelID}, - CounterpartyEndpoint: wasmvmtypes.IBCEndpoint{PortID: counterParty.PortId, ChannelID: counterParty.ChannelId}, - Order: order.String(), - // DESIGN V3: this may be "" ?? - Version: version, - ConnectionID: connectionHops[0], // At the moment this list must be of length 1. In the future multi-hop channels may be supported. - }, - }, - } - - // Allow contracts to return a version (or default to proposed version if unset) - acceptedVersion, err := i.keeper.OnOpenChannel(ctx, contractAddr, msg) - if err != nil { - return "", err - } - if acceptedVersion == "" { // accept incoming version when nothing returned by contract - acceptedVersion = version - } - - // Claim channel capability passed back by IBC module - if err := i.keeper.ClaimCapability(ctx, chanCap, host.ChannelCapabilityPath(portID, channelID)); err != nil { - return "", errorsmod.Wrap(err, "claim capability") - } - return acceptedVersion, nil -} - -// OnChanOpenTry implements the IBCModule interface -func (i IBCHandler) OnChanOpenTry( - ctx sdk.Context, - order channeltypes.Order, - connectionHops []string, - portID, channelID string, - chanCap *capabilitytypes.Capability, - counterParty channeltypes.Counterparty, - counterpartyVersion string, -) (string, error) { - // ensure port, version, capability - if err := ValidateChannelParams(channelID); err != nil { - return "", err - } - - contractAddr, err := ContractFromPortID(portID) - if err != nil { - return "", errorsmod.Wrapf(err, "contract port id") - } - - msg := wasmvmtypes.IBCChannelOpenMsg{ - OpenTry: &wasmvmtypes.IBCOpenTry{ - Channel: wasmvmtypes.IBCChannel{ - Endpoint: wasmvmtypes.IBCEndpoint{PortID: portID, ChannelID: channelID}, - CounterpartyEndpoint: wasmvmtypes.IBCEndpoint{PortID: counterParty.PortId, ChannelID: counterParty.ChannelId}, - Order: order.String(), - Version: counterpartyVersion, - ConnectionID: connectionHops[0], // At the moment this list must be of length 1. In the future multi-hop channels may be supported. - }, - CounterpartyVersion: counterpartyVersion, - }, - } - - // Allow contracts to return a version (or default to counterpartyVersion if unset) - version, err := i.keeper.OnOpenChannel(ctx, contractAddr, msg) - if err != nil { - return "", err - } - if version == "" { - version = counterpartyVersion - } - - // Module may have already claimed capability in OnChanOpenInit in the case of crossing hellos - // (ie chainA and chainB both call ChanOpenInit before one of them calls ChanOpenTry) - // If module can already authenticate the capability then module already owns it, so we don't need to claim - // Otherwise, module does not have channel capability, and we must claim it from IBC - if !i.keeper.AuthenticateCapability(ctx, chanCap, host.ChannelCapabilityPath(portID, channelID)) { - // Only claim channel capability passed back by IBC module if we do not already own it - if err := i.keeper.ClaimCapability(ctx, chanCap, host.ChannelCapabilityPath(portID, channelID)); err != nil { - return "", errorsmod.Wrap(err, "claim capability") - } - } - - return version, nil -} - -// OnChanOpenAck implements the IBCModule interface -func (i IBCHandler) OnChanOpenAck( - ctx sdk.Context, - portID, channelID string, - counterpartyChannelID string, - counterpartyVersion string, -) error { - contractAddr, err := ContractFromPortID(portID) - if err != nil { - return errorsmod.Wrapf(err, "contract port id") - } - channelInfo, ok := i.channelKeeper.GetChannel(ctx, portID, channelID) - if !ok { - return errorsmod.Wrapf(channeltypes.ErrChannelNotFound, "port ID (%s) channel ID (%s)", portID, channelID) - } - channelInfo.Counterparty.ChannelId = counterpartyChannelID - - appVersion, ok := i.appVersionGetter.GetAppVersion(ctx, portID, channelID) - if !ok { - return errorsmod.Wrapf(channeltypes.ErrInvalidChannelVersion, "port ID (%s) channel ID (%s)", portID, channelID) - } - - msg := wasmvmtypes.IBCChannelConnectMsg{ - OpenAck: &wasmvmtypes.IBCOpenAck{ - Channel: toWasmVMChannel(portID, channelID, channelInfo, appVersion), - CounterpartyVersion: counterpartyVersion, - }, - } - return i.keeper.OnConnectChannel(ctx, contractAddr, msg) -} - -// OnChanOpenConfirm implements the IBCModule interface -func (i IBCHandler) OnChanOpenConfirm(ctx sdk.Context, portID, channelID string) error { - contractAddr, err := ContractFromPortID(portID) - if err != nil { - return errorsmod.Wrapf(err, "contract port id") - } - channelInfo, ok := i.channelKeeper.GetChannel(ctx, portID, channelID) - if !ok { - return errorsmod.Wrapf(channeltypes.ErrChannelNotFound, "port ID (%s) channel ID (%s)", portID, channelID) - } - appVersion, ok := i.appVersionGetter.GetAppVersion(ctx, portID, channelID) - if !ok { - return errorsmod.Wrapf(channeltypes.ErrInvalidChannelVersion, "port ID (%s) channel ID (%s)", portID, channelID) - } - msg := wasmvmtypes.IBCChannelConnectMsg{ - OpenConfirm: &wasmvmtypes.IBCOpenConfirm{ - Channel: toWasmVMChannel(portID, channelID, channelInfo, appVersion), - }, - } - return i.keeper.OnConnectChannel(ctx, contractAddr, msg) -} - -// OnChanCloseInit implements the IBCModule interface -func (i IBCHandler) OnChanCloseInit(ctx sdk.Context, portID, channelID string) error { - contractAddr, err := ContractFromPortID(portID) - if err != nil { - return errorsmod.Wrapf(err, "contract port id") - } - channelInfo, ok := i.channelKeeper.GetChannel(ctx, portID, channelID) - if !ok { - return errorsmod.Wrapf(channeltypes.ErrChannelNotFound, "port ID (%s) channel ID (%s)", portID, channelID) - } - appVersion, ok := i.appVersionGetter.GetAppVersion(ctx, portID, channelID) - if !ok { - return errorsmod.Wrapf(channeltypes.ErrInvalidChannelVersion, "port ID (%s) channel ID (%s)", portID, channelID) - } - - msg := wasmvmtypes.IBCChannelCloseMsg{ - CloseInit: &wasmvmtypes.IBCCloseInit{Channel: toWasmVMChannel(portID, channelID, channelInfo, appVersion)}, - } - err = i.keeper.OnCloseChannel(ctx, contractAddr, msg) - if err != nil { - return err - } - // emit events? - - return err -} - -// OnChanCloseConfirm implements the IBCModule interface -func (i IBCHandler) OnChanCloseConfirm(ctx sdk.Context, portID, channelID string) error { - // counterparty has closed the channel - contractAddr, err := ContractFromPortID(portID) - if err != nil { - return errorsmod.Wrapf(err, "contract port id") - } - channelInfo, ok := i.channelKeeper.GetChannel(ctx, portID, channelID) - if !ok { - return errorsmod.Wrapf(channeltypes.ErrChannelNotFound, "port ID (%s) channel ID (%s)", portID, channelID) - } - appVersion, ok := i.appVersionGetter.GetAppVersion(ctx, portID, channelID) - if !ok { - return errorsmod.Wrapf(channeltypes.ErrInvalidChannelVersion, "port ID (%s) channel ID (%s)", portID, channelID) - } - - msg := wasmvmtypes.IBCChannelCloseMsg{ - CloseConfirm: &wasmvmtypes.IBCCloseConfirm{Channel: toWasmVMChannel(portID, channelID, channelInfo, appVersion)}, - } - err = i.keeper.OnCloseChannel(ctx, contractAddr, msg) - if err != nil { - return err - } - // emit events? - - return err -} - -func toWasmVMChannel(portID, channelID string, channelInfo channeltypes.Channel, appVersion string) wasmvmtypes.IBCChannel { - return wasmvmtypes.IBCChannel{ - Endpoint: wasmvmtypes.IBCEndpoint{PortID: portID, ChannelID: channelID}, - CounterpartyEndpoint: wasmvmtypes.IBCEndpoint{PortID: channelInfo.Counterparty.PortId, ChannelID: channelInfo.Counterparty.ChannelId}, - Order: channelInfo.Ordering.String(), - Version: appVersion, - ConnectionID: channelInfo.ConnectionHops[0], // At the moment this list must be of length 1. In the future multi-hop channels may be supported. - } -} - -// OnRecvPacket implements the IBCModule interface -func (i IBCHandler) OnRecvPacket( - ctx sdk.Context, - packet channeltypes.Packet, - relayer sdk.AccAddress, -) ibcexported.Acknowledgement { - contractAddr, err := ContractFromPortID(packet.DestinationPort) - if err != nil { - return channeltypes.NewErrorAcknowledgement(errorsmod.Wrapf(err, "contract port id")) - } - msg := wasmvmtypes.IBCPacketReceiveMsg{Packet: newIBCPacket(packet), Relayer: relayer.String()} - ack, err := i.keeper.OnRecvPacket(ctx, contractAddr, msg) - if err != nil { - return channeltypes.NewErrorAcknowledgement(err) - } - return ContractConfirmStateAck(ack) -} - -var _ ibcexported.Acknowledgement = ContractConfirmStateAck{} - -type ContractConfirmStateAck []byte - -func (w ContractConfirmStateAck) Success() bool { - return true // always commit state -} - -func (w ContractConfirmStateAck) Acknowledgement() []byte { - return w -} - -// OnAcknowledgementPacket implements the IBCModule interface -func (i IBCHandler) OnAcknowledgementPacket( - ctx sdk.Context, - packet channeltypes.Packet, - acknowledgement []byte, - relayer sdk.AccAddress, -) error { - contractAddr, err := ContractFromPortID(packet.SourcePort) - if err != nil { - return errorsmod.Wrapf(err, "contract port id") - } - - err = i.keeper.OnAckPacket(ctx, contractAddr, wasmvmtypes.IBCPacketAckMsg{ - Acknowledgement: wasmvmtypes.IBCAcknowledgement{Data: acknowledgement}, - OriginalPacket: newIBCPacket(packet), - Relayer: relayer.String(), - }) - if err != nil { - return errorsmod.Wrap(err, "on ack") - } - return nil -} - -// OnTimeoutPacket implements the IBCModule interface -func (i IBCHandler) OnTimeoutPacket(ctx sdk.Context, packet channeltypes.Packet, relayer sdk.AccAddress) error { - contractAddr, err := ContractFromPortID(packet.SourcePort) - if err != nil { - return errorsmod.Wrapf(err, "contract port id") - } - msg := wasmvmtypes.IBCPacketTimeoutMsg{Packet: newIBCPacket(packet), Relayer: relayer.String()} - err = i.keeper.OnTimeoutPacket(ctx, contractAddr, msg) - if err != nil { - return errorsmod.Wrap(err, "on timeout") - } - return nil -} - -func newIBCPacket(packet channeltypes.Packet) wasmvmtypes.IBCPacket { - timeout := wasmvmtypes.IBCTimeout{ - Timestamp: packet.TimeoutTimestamp, - } - if !packet.TimeoutHeight.IsZero() { - timeout.Block = &wasmvmtypes.IBCTimeoutBlock{ - Height: packet.TimeoutHeight.RevisionHeight, - Revision: packet.TimeoutHeight.RevisionNumber, - } - } - - return wasmvmtypes.IBCPacket{ - Data: packet.Data, - Src: wasmvmtypes.IBCEndpoint{ChannelID: packet.SourceChannel, PortID: packet.SourcePort}, - Dest: wasmvmtypes.IBCEndpoint{ChannelID: packet.DestinationChannel, PortID: packet.DestinationPort}, - Sequence: packet.Sequence, - Timeout: timeout, - } -} - -func ValidateChannelParams(channelID string) error { - // NOTE: for escrow address security only 2^32 channels are allowed to be created - // Issue: https://github.com/cosmos/cosmos-sdk/issues/7737 - channelSequence, err := channeltypes.ParseChannelSequence(channelID) - if err != nil { - return err - } - if channelSequence > math.MaxUint32 { - return errorsmod.Wrapf(types.ErrMaxIBCChannels, "channel sequence %d is greater than max allowed transfer channels %d", channelSequence, math.MaxUint32) - } - return nil -} diff --git a/x/wasm/ibc_integration_test.go b/x/wasm/ibc_integration_test.go deleted file mode 100644 index f348f46..0000000 --- a/x/wasm/ibc_integration_test.go +++ /dev/null @@ -1,126 +0,0 @@ -package wasm_test - -import ( - "testing" - - wasmvm "github.com/CosmWasm/wasmvm" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - ibctransfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - ibctesting "github.com/cosmos/ibc-go/v7/testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - wasmibctesting "github.com/terpnetwork/terp-core/x/wasm/ibctesting" - wasmkeeper "github.com/terpnetwork/terp-core/x/wasm/keeper" - "github.com/terpnetwork/terp-core/x/wasm/keeper/wasmtesting" -) - -func TestOnChanOpenInitVersion(t *testing.T) { - const startVersion = "v1" - specs := map[string]struct { - contractRsp *wasmvmtypes.IBC3ChannelOpenResponse - expVersion string - }{ - "different version": { - contractRsp: &wasmvmtypes.IBC3ChannelOpenResponse{Version: "v2"}, - expVersion: "v2", - }, - "no response": { - expVersion: startVersion, - }, - "empty result": { - contractRsp: &wasmvmtypes.IBC3ChannelOpenResponse{}, - expVersion: startVersion, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - myContract := &wasmtesting.MockIBCContractCallbacks{ - IBCChannelOpenFn: func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCChannelOpenMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBC3ChannelOpenResponse, uint64, error) { - return spec.contractRsp, 0, nil - }, - } - var ( - chainAOpts = []wasmkeeper.Option{ - wasmkeeper.WithWasmEngine( - wasmtesting.NewIBCContractMockWasmer(myContract)), - } - coordinator = wasmibctesting.NewCoordinator(t, 2, chainAOpts) - chainA = coordinator.GetChain(wasmibctesting.GetChainID(1)) - chainB = coordinator.GetChain(wasmibctesting.GetChainID(2)) - myContractAddr = chainA.SeedNewContractInstance() - contractInfo = chainA.App.WasmKeeper.GetContractInfo(chainA.GetContext(), myContractAddr) - ) - - path := wasmibctesting.NewPath(chainA, chainB) - coordinator.SetupConnections(path) - - path.EndpointA.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: contractInfo.IBCPortID, - Version: startVersion, - Order: channeltypes.UNORDERED, - } - require.NoError(t, path.EndpointA.ChanOpenInit()) - assert.Equal(t, spec.expVersion, path.EndpointA.ChannelConfig.Version) - }) - } -} - -func TestOnChanOpenTryVersion(t *testing.T) { - const startVersion = ibctransfertypes.Version - specs := map[string]struct { - contractRsp *wasmvmtypes.IBC3ChannelOpenResponse - expVersion string - }{ - "different version": { - contractRsp: &wasmvmtypes.IBC3ChannelOpenResponse{Version: "v2"}, - expVersion: "v2", - }, - "no response": { - expVersion: startVersion, - }, - "empty result": { - contractRsp: &wasmvmtypes.IBC3ChannelOpenResponse{}, - expVersion: startVersion, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - myContract := &wasmtesting.MockIBCContractCallbacks{ - IBCChannelOpenFn: func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCChannelOpenMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBC3ChannelOpenResponse, uint64, error) { - return spec.contractRsp, 0, nil - }, - } - var ( - chainAOpts = []wasmkeeper.Option{ - wasmkeeper.WithWasmEngine( - wasmtesting.NewIBCContractMockWasmer(myContract)), - } - coordinator = wasmibctesting.NewCoordinator(t, 2, chainAOpts) - chainA = coordinator.GetChain(wasmibctesting.GetChainID(1)) - chainB = coordinator.GetChain(wasmibctesting.GetChainID(2)) - myContractAddr = chainA.SeedNewContractInstance() - contractInfo = chainA.ContractInfo(myContractAddr) - ) - - path := wasmibctesting.NewPath(chainA, chainB) - coordinator.SetupConnections(path) - - path.EndpointA.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: contractInfo.IBCPortID, - Version: startVersion, - Order: channeltypes.UNORDERED, - } - path.EndpointB.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: ibctransfertypes.PortID, - Version: ibctransfertypes.Version, - Order: channeltypes.UNORDERED, - } - - require.NoError(t, path.EndpointB.ChanOpenInit()) - require.NoError(t, path.EndpointA.ChanOpenTry()) - assert.Equal(t, spec.expVersion, path.EndpointA.ChannelConfig.Version) - }) - } -} diff --git a/x/wasm/ibc_reflect_test.go b/x/wasm/ibc_reflect_test.go deleted file mode 100644 index 7d4e41d..0000000 --- a/x/wasm/ibc_reflect_test.go +++ /dev/null @@ -1,124 +0,0 @@ -package wasm_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - ibctesting "github.com/cosmos/ibc-go/v7/testing" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/stretchr/testify/require" - - wasmibctesting "github.com/terpnetwork/terp-core/x/wasm/ibctesting" - wasmkeeper "github.com/terpnetwork/terp-core/x/wasm/keeper" -) - -func TestIBCReflectContract(t *testing.T) { - // scenario: - // chain A: ibc_reflect_send.wasm - // chain B: reflect.wasm + ibc_reflect.wasm - // - // Chain A "ibc_reflect_send" sends a IBC packet "on channel connect" event to chain B "ibc_reflect" - // "ibc_reflect" sends a submessage to "reflect" which is returned as submessage. - - var ( - coordinator = wasmibctesting.NewCoordinator(t, 2) - chainA = coordinator.GetChain(wasmibctesting.GetChainID(1)) - chainB = coordinator.GetChain(wasmibctesting.GetChainID(2)) - ) - coordinator.CommitBlock(chainA, chainB) - - initMsg := []byte(`{}`) - codeID := chainA.StoreCodeFile("./keeper/testdata/ibc_reflect_send.wasm").CodeID - sendContractAddr := chainA.InstantiateContract(codeID, initMsg) - - reflectID := chainB.StoreCodeFile("./keeper/testdata/reflect.wasm").CodeID - initMsg = wasmkeeper.IBCReflectInitMsg{ - ReflectCodeID: reflectID, - }.GetBytes(t) - codeID = chainB.StoreCodeFile("./keeper/testdata/ibc_reflect.wasm").CodeID - - reflectContractAddr := chainB.InstantiateContract(codeID, initMsg) - var ( - sourcePortID = chainA.ContractInfo(sendContractAddr).IBCPortID - counterpartPortID = chainB.ContractInfo(reflectContractAddr).IBCPortID - ) - coordinator.CommitBlock(chainA, chainB) - coordinator.UpdateTime() - - require.Equal(t, chainA.CurrentHeader.Time, chainB.CurrentHeader.Time) - path := wasmibctesting.NewPath(chainA, chainB) - path.EndpointA.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: sourcePortID, - Version: "ibc-reflect-v1", - Order: channeltypes.ORDERED, - } - path.EndpointB.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: counterpartPortID, - Version: "ibc-reflect-v1", - Order: channeltypes.ORDERED, - } - - coordinator.SetupConnections(path) - coordinator.CreateChannels(path) - - // TODO: query both contracts directly to ensure they have registered the proper connection - // (and the chainB has created a reflect contract) - - // there should be one packet to relay back and forth (whoami) - // TODO: how do I find the packet that was previously sent by the smart contract? - // Coordinator.RecvPacket requires channeltypes.Packet as input? - // Given the source (portID, channelID), we should be able to count how many packets are pending, query the data - // and submit them to the other side (same with acks). This is what the real relayer does. I guess the test framework doesn't? - - // Update: I dug through the code, especially channel.Keeper.SendPacket, and it only writes a commitment - // only writes I see: https://github.com/cosmos/cosmos-sdk/blob/31fdee0228bd6f3e787489c8e4434aabc8facb7d/x/ibc/core/04-channel/keeper/packet.go#L115-L116 - // commitment is hashed packet: https://github.com/cosmos/cosmos-sdk/blob/31fdee0228bd6f3e787489c8e4434aabc8facb7d/x/ibc/core/04-channel/types/packet.go#L14-L34 - // how is the relayer supposed to get the original packet data?? - // eg. ibctransfer doesn't store the packet either: https://github.com/cosmos/cosmos-sdk/blob/master/x/ibc/applications/transfer/keeper/relay.go#L145-L162 - // ... or I guess the original packet data is only available in the event logs???? - // https://github.com/cosmos/cosmos-sdk/blob/31fdee0228bd6f3e787489c8e4434aabc8facb7d/x/ibc/core/04-channel/keeper/packet.go#L121-L132 - - // ensure the expected packet was prepared, and relay it - require.Equal(t, 1, len(chainA.PendingSendPackets)) - require.Equal(t, 0, len(chainB.PendingSendPackets)) - err := coordinator.RelayAndAckPendingPackets(path) - require.NoError(t, err) - require.Equal(t, 0, len(chainA.PendingSendPackets)) - require.Equal(t, 0, len(chainB.PendingSendPackets)) - - // let's query the source contract and make sure it registered an address - query := ReflectSendQueryMsg{Account: &AccountQuery{ChannelID: path.EndpointA.ChannelID}} - var account AccountResponse - err = chainA.SmartQuery(sendContractAddr.String(), query, &account) - require.NoError(t, err) - require.NotEmpty(t, account.RemoteAddr) - require.Empty(t, account.RemoteBalance) - - // close channel - coordinator.CloseChannel(path) - - // let's query the source contract and make sure it registered an address - account = AccountResponse{} - err = chainA.SmartQuery(sendContractAddr.String(), query, &account) - require.Error(t, err) - assert.Contains(t, err.Error(), "not found") -} - -type ReflectSendQueryMsg struct { - Admin *struct{} `json:"admin,omitempty"` - ListAccounts *struct{} `json:"list_accounts,omitempty"` - Account *AccountQuery `json:"account,omitempty"` -} - -type AccountQuery struct { - ChannelID string `json:"channel_id"` -} - -type AccountResponse struct { - LastUpdateTime uint64 `json:"last_update_time,string"` - RemoteAddr string `json:"remote_addr"` - RemoteBalance wasmvmtypes.Coins `json:"remote_balance"` -} diff --git a/x/wasm/ibc_test.go b/x/wasm/ibc_test.go deleted file mode 100644 index a92d451..0000000 --- a/x/wasm/ibc_test.go +++ /dev/null @@ -1,82 +0,0 @@ -package wasm - -import ( - "testing" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - "github.com/stretchr/testify/assert" -) - -func TestMapToWasmVMIBCPacket(t *testing.T) { - var myTimestamp uint64 = 1 - specs := map[string]struct { - src channeltypes.Packet - exp wasmvmtypes.IBCPacket - }{ - "with height timeout": { - src: IBCPacketFixture(), - exp: wasmvmtypes.IBCPacket{ - Data: []byte("myData"), - Src: wasmvmtypes.IBCEndpoint{PortID: "srcPort", ChannelID: "channel-1"}, - Dest: wasmvmtypes.IBCEndpoint{PortID: "destPort", ChannelID: "channel-2"}, - Sequence: 1, - Timeout: wasmvmtypes.IBCTimeout{Block: &wasmvmtypes.IBCTimeoutBlock{Height: 1, Revision: 2}}, - }, - }, - "with time timeout": { - src: IBCPacketFixture(func(p *channeltypes.Packet) { - p.TimeoutTimestamp = myTimestamp - p.TimeoutHeight = clienttypes.Height{} - }), - exp: wasmvmtypes.IBCPacket{ - Data: []byte("myData"), - Src: wasmvmtypes.IBCEndpoint{PortID: "srcPort", ChannelID: "channel-1"}, - Dest: wasmvmtypes.IBCEndpoint{PortID: "destPort", ChannelID: "channel-2"}, - Sequence: 1, - Timeout: wasmvmtypes.IBCTimeout{Timestamp: myTimestamp}, - }, - }, "with time and height timeout": { - src: IBCPacketFixture(func(p *channeltypes.Packet) { - p.TimeoutTimestamp = myTimestamp - }), - exp: wasmvmtypes.IBCPacket{ - Data: []byte("myData"), - Src: wasmvmtypes.IBCEndpoint{PortID: "srcPort", ChannelID: "channel-1"}, - Dest: wasmvmtypes.IBCEndpoint{PortID: "destPort", ChannelID: "channel-2"}, - Sequence: 1, - Timeout: wasmvmtypes.IBCTimeout{ - Block: &wasmvmtypes.IBCTimeoutBlock{Height: 1, Revision: 2}, - Timestamp: myTimestamp, - }, - }, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - got := newIBCPacket(spec.src) - assert.Equal(t, spec.exp, got) - }) - } -} - -func IBCPacketFixture(mutators ...func(p *channeltypes.Packet)) channeltypes.Packet { - r := channeltypes.Packet{ - Sequence: 1, - SourcePort: "srcPort", - SourceChannel: "channel-1", - DestinationPort: "destPort", - DestinationChannel: "channel-2", - Data: []byte("myData"), - TimeoutHeight: clienttypes.Height{ - RevisionHeight: 1, - RevisionNumber: 2, - }, - TimeoutTimestamp: 0, - } - for _, m := range mutators { - m(&r) - } - return r -} diff --git a/x/wasm/ibctesting/README.md b/x/wasm/ibctesting/README.md deleted file mode 100644 index 1c92869..0000000 --- a/x/wasm/ibctesting/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# testing package for ibc -Customized version of cosmos-sdk x/ibc/testing \ No newline at end of file diff --git a/x/wasm/ibctesting/chain.go b/x/wasm/ibctesting/chain.go deleted file mode 100644 index 844befc..0000000 --- a/x/wasm/ibctesting/chain.go +++ /dev/null @@ -1,611 +0,0 @@ -package ibctesting - -import ( - "fmt" - "testing" - "time" - - errorsmod "cosmossdk.io/errors" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" - - "github.com/terpnetwork/terp-core/app" - "github.com/terpnetwork/terp-core/x/wasm" - - // simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cometbft/cometbft/crypto/tmhash" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmprotoversion "github.com/cometbft/cometbft/proto/tendermint/version" - tmtypes "github.com/cometbft/cometbft/types" - tmversion "github.com/cometbft/cometbft/version" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - capabilitykeeper "github.com/cosmos/cosmos-sdk/x/capability/keeper" - capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" - "github.com/cosmos/cosmos-sdk/x/staking/testutil" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - commitmenttypes "github.com/cosmos/ibc-go/v7/modules/core/23-commitment/types" - host "github.com/cosmos/ibc-go/v7/modules/core/24-host" - "github.com/cosmos/ibc-go/v7/modules/core/exported" - "github.com/cosmos/ibc-go/v7/modules/core/types" - ibctm "github.com/cosmos/ibc-go/v7/modules/light-clients/07-tendermint" - ibctesting "github.com/cosmos/ibc-go/v7/testing" - "github.com/cosmos/ibc-go/v7/testing/mock" - "github.com/stretchr/testify/require" -) - -var MaxAccounts = 10 - -type SenderAccount struct { - SenderPrivKey cryptotypes.PrivKey - SenderAccount authtypes.AccountI -} - -// TestChain is a testing struct that wraps a simapp with the last TM Header, the current ABCI -// header and the validators of the TestChain. It also contains a field called ChainID. This -// is the clientID that *other* chains use to refer to this TestChain. The SenderAccount -// is used for delivering transactions through the application state. -// NOTE: the actual application uses an empty chain-id for ease of testing. -type TestChain struct { - t *testing.T - - Coordinator *Coordinator - App *app.TerpApp - ChainID string - LastHeader *ibctm.Header // header for last block height committed - CurrentHeader tmproto.Header // header for current block height - QueryServer types.QueryServer - TxConfig client.TxConfig - Codec codec.BinaryCodec - - Vals *tmtypes.ValidatorSet - NextVals *tmtypes.ValidatorSet - - // Signers is a map from validator address to the PrivValidator - // The map is converted into an array that is the same order as the validators right before signing commit - // This ensures that signers will always be in correct order even as validator powers change. - // If a test adds a new validator after chain creation, then the signer map must be updated to include - // the new PrivValidator entry. - Signers map[string]tmtypes.PrivValidator - - // autogenerated sender private key - SenderPrivKey cryptotypes.PrivKey - SenderAccount authtypes.AccountI - SenderAccounts []SenderAccount - - PendingSendPackets []channeltypes.Packet -} - -type PacketAck struct { - Packet channeltypes.Packet - Ack []byte -} - -// NewTestChain initializes a new test chain with a default of 4 validators -// Use this function if the tests do not need custom control over the validator set -func NewTestChain(t *testing.T, coord *Coordinator, chainID string, opts ...wasm.Option) *TestChain { - // generate validators private/public key - var ( - validatorsPerChain = 4 - validators = make([]*tmtypes.Validator, 0, validatorsPerChain) - signersByAddress = make(map[string]tmtypes.PrivValidator, validatorsPerChain) - ) - - for i := 0; i < validatorsPerChain; i++ { - privVal := mock.NewPV() - pubKey, err := privVal.GetPubKey() - require.NoError(t, err) - validators = append(validators, tmtypes.NewValidator(pubKey, 1)) - signersByAddress[pubKey.Address().String()] = privVal - } - - // construct validator set; - // Note that the validators are sorted by voting power - // or, if equal, by address lexical order - valSet := tmtypes.NewValidatorSet(validators) - - return NewTestChainWithValSet(t, coord, chainID, valSet, signersByAddress, opts...) -} - -// NewTestChainWithValSet initializes a new TestChain instance with the given validator set -// and signer array. It also initializes 10 Sender accounts with a balance of 10000000000000000000 coins of -// bond denom to use for tests. -// -// The first block height is committed to state in order to allow for client creations on -// counterparty chains. The TestChain will return with a block height starting at 2. -// -// Time management is handled by the Coordinator in order to ensure synchrony between chains. -// Each update of any chain increments the block header time for all chains by 5 seconds. -// -// NOTE: to use a custom sender privkey and account for testing purposes, replace and modify this -// constructor function. -// -// CONTRACT: Validator array must be provided in the order expected by Tendermint. -// i.e. sorted first by power and then lexicographically by address. -func NewTestChainWithValSet(t *testing.T, coord *Coordinator, chainID string, valSet *tmtypes.ValidatorSet, signers map[string]tmtypes.PrivValidator, opts ...wasm.Option) *TestChain { - genAccs := []authtypes.GenesisAccount{} - genBals := []banktypes.Balance{} - senderAccs := []SenderAccount{} - - // generate genesis accounts - for i := 0; i < MaxAccounts; i++ { - senderPrivKey := secp256k1.GenPrivKey() - acc := authtypes.NewBaseAccount(senderPrivKey.PubKey().Address().Bytes(), senderPrivKey.PubKey(), uint64(i), 0) - amount, ok := sdk.NewIntFromString("10000000000000000000") - require.True(t, ok) - - // add sender account - balance := banktypes.Balance{ - Address: acc.GetAddress().String(), - Coins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, amount)), - } - - genAccs = append(genAccs, acc) - genBals = append(genBals, balance) - - senderAcc := SenderAccount{ - SenderAccount: acc, - SenderPrivKey: senderPrivKey, - } - - senderAccs = append(senderAccs, senderAcc) - } - - wasmApp := app.SetupWithGenesisValSet(t, valSet, genAccs, chainID, opts, genBals...) - - // create current header and call begin block - header := tmproto.Header{ - ChainID: chainID, - Height: 1, - Time: coord.CurrentTime.UTC(), - } - - txConfig := wasmApp.TxConfig() - - // create an account to send transactions from - chain := &TestChain{ - t: t, - Coordinator: coord, - ChainID: chainID, - App: wasmApp, - CurrentHeader: header, - QueryServer: wasmApp.IBCKeeper, - TxConfig: txConfig, - Codec: wasmApp.AppCodec(), - Vals: valSet, - NextVals: valSet, - Signers: signers, - SenderPrivKey: senderAccs[0].SenderPrivKey, - SenderAccount: senderAccs[0].SenderAccount, - SenderAccounts: senderAccs, - } - - coord.CommitBlock(chain) - - return chain -} - -// GetContext returns the current context for the application. -func (chain *TestChain) GetContext() sdk.Context { - return chain.App.BaseApp.NewContext(false, chain.CurrentHeader) -} - -// QueryProof performs an abci query with the given key and returns the proto encoded merkle proof -// for the query and the height at which the proof will succeed on a tendermint verifier. -func (chain *TestChain) QueryProof(key []byte) ([]byte, clienttypes.Height) { - return chain.QueryProofAtHeight(key, chain.App.LastBlockHeight()) -} - -// QueryProofAtHeight performs an abci query with the given key and returns the proto encoded merkle proof -// for the query and the height at which the proof will succeed on a tendermint verifier. Only the IBC -// store is supported -func (chain *TestChain) QueryProofAtHeight(key []byte, height int64) ([]byte, clienttypes.Height) { - return chain.QueryProofForStore(exported.StoreKey, key, height) -} - -// QueryProofForStore performs an abci query with the given key and returns the proto encoded merkle proof -// for the query and the height at which the proof will succeed on a tendermint verifier. -func (chain *TestChain) QueryProofForStore(storeKey string, key []byte, height int64) ([]byte, clienttypes.Height) { - res := chain.App.Query(abci.RequestQuery{ - Path: fmt.Sprintf("store/%s/key", storeKey), - Height: height - 1, - Data: key, - Prove: true, - }) - - merkleProof, err := commitmenttypes.ConvertProofs(res.ProofOps) - require.NoError(chain.t, err) - - proof, err := chain.App.AppCodec().Marshal(&merkleProof) - require.NoError(chain.t, err) - - revision := clienttypes.ParseChainID(chain.ChainID) - - // proof height + 1 is returned as the proof created corresponds to the height the proof - // was created in the IAVL tree. Tendermint and subsequently the clients that rely on it - // have heights 1 above the IAVL tree. Thus we return proof height + 1 - return proof, clienttypes.NewHeight(revision, uint64(res.Height)+1) -} - -// QueryUpgradeProof performs an abci query with the given key and returns the proto encoded merkle proof -// for the query and the height at which the proof will succeed on a tendermint verifier. -func (chain *TestChain) QueryUpgradeProof(key []byte, height uint64) ([]byte, clienttypes.Height) { - res := chain.App.Query(abci.RequestQuery{ - Path: "store/upgrade/key", - Height: int64(height - 1), - Data: key, - Prove: true, - }) - - merkleProof, err := commitmenttypes.ConvertProofs(res.ProofOps) - require.NoError(chain.t, err) - - proof, err := chain.App.AppCodec().Marshal(&merkleProof) - require.NoError(chain.t, err) - - revision := clienttypes.ParseChainID(chain.ChainID) - - // proof height + 1 is returned as the proof created corresponds to the height the proof - // was created in the IAVL tree. Tendermint and subsequently the clients that rely on it - // have heights 1 above the IAVL tree. Thus we return proof height + 1 - return proof, clienttypes.NewHeight(revision, uint64(res.Height+1)) -} - -// QueryConsensusStateProof performs an abci query for a consensus state -// stored on the given clientID. The proof and consensusHeight are returned. -func (chain *TestChain) QueryConsensusStateProof(clientID string) ([]byte, clienttypes.Height) { - clientState := chain.GetClientState(clientID) - - consensusHeight := clientState.GetLatestHeight().(clienttypes.Height) - consensusKey := host.FullConsensusStateKey(clientID, consensusHeight) - proofConsensus, _ := chain.QueryProof(consensusKey) - - return proofConsensus, consensusHeight -} - -// NextBlock sets the last header to the current header and increments the current header to be -// at the next block height. It does not update the time as that is handled by the Coordinator. -// It will call Endblock and Commit and apply the validator set changes to the next validators -// of the next block being created. This follows the Tendermint protocol of applying valset changes -// returned on block `n` to the validators of block `n+2`. -// It calls BeginBlock with the new block created before returning. -func (chain *TestChain) NextBlock() { - res := chain.App.EndBlock(abci.RequestEndBlock{Height: chain.CurrentHeader.Height}) - - chain.App.Commit() - - // set the last header to the current header - // use nil trusted fields - chain.LastHeader = chain.CurrentTMClientHeader() - - // val set changes returned from previous block get applied to the next validators - // of this block. See tendermint spec for details. - chain.Vals = chain.NextVals - chain.NextVals = ibctesting.ApplyValSetChanges(chain.t, chain.Vals, res.ValidatorUpdates) - - // increment the current header - chain.CurrentHeader = tmproto.Header{ - ChainID: chain.ChainID, - Height: chain.App.LastBlockHeight() + 1, - AppHash: chain.App.LastCommitID().Hash, - // NOTE: the time is increased by the coordinator to maintain time synchrony amongst - // chains. - Time: chain.CurrentHeader.Time, - ValidatorsHash: chain.Vals.Hash(), - NextValidatorsHash: chain.NextVals.Hash(), - ProposerAddress: chain.CurrentHeader.ProposerAddress, - } - - chain.App.BeginBlock(abci.RequestBeginBlock{Header: chain.CurrentHeader}) -} - -// sendMsgs delivers a transaction through the application without returning the result. -func (chain *TestChain) sendMsgs(msgs ...sdk.Msg) error { - _, err := chain.SendMsgs(msgs...) - return err -} - -// SendMsgs delivers a transaction through the application. It updates the senders sequence -// number and updates the TestChain's headers. It returns the result and error if one -// occurred. -func (chain *TestChain) SendMsgs(msgs ...sdk.Msg) (*sdk.Result, error) { - // ensure the chain has the latest time - chain.Coordinator.UpdateTimeForChain(chain) - - _, r, err := app.SignAndDeliverWithoutCommit( - chain.t, - chain.TxConfig, - chain.App.BaseApp, - chain.GetContext().BlockHeader(), - msgs, - chain.ChainID, - []uint64{chain.SenderAccount.GetAccountNumber()}, - []uint64{chain.SenderAccount.GetSequence()}, - chain.SenderPrivKey, - ) - if err != nil { - return nil, err - } - - // NextBlock calls app.Commit() - chain.NextBlock() - - // increment sequence for successful transaction execution - err = chain.SenderAccount.SetSequence(chain.SenderAccount.GetSequence() + 1) - if err != nil { - return nil, err - } - - chain.Coordinator.IncrementTime() - - chain.CaptureIBCEvents(r) - - return r, nil -} - -func (chain *TestChain) CaptureIBCEvents(r *sdk.Result) { - toSend := getSendPackets(r.Events) - if len(toSend) > 0 { - // Keep a queue on the chain that we can relay in tests - chain.PendingSendPackets = append(chain.PendingSendPackets, toSend...) - } -} - -// GetClientState retrieves the client state for the provided clientID. The client is -// expected to exist otherwise testing will fail. -func (chain *TestChain) GetClientState(clientID string) exported.ClientState { - clientState, found := chain.App.IBCKeeper.ClientKeeper.GetClientState(chain.GetContext(), clientID) - require.True(chain.t, found) - - return clientState -} - -// GetConsensusState retrieves the consensus state for the provided clientID and height. -// It will return a success boolean depending on if consensus state exists or not. -func (chain *TestChain) GetConsensusState(clientID string, height exported.Height) (exported.ConsensusState, bool) { - return chain.App.IBCKeeper.ClientKeeper.GetClientConsensusState(chain.GetContext(), clientID, height) -} - -// GetValsAtHeight will return the validator set of the chain at a given height. It will return -// a success boolean depending on if the validator set exists or not at that height. -func (chain *TestChain) GetValsAtHeight(height int64) (*tmtypes.ValidatorSet, bool) { - histInfo, ok := chain.App.StakingKeeper.GetHistoricalInfo(chain.GetContext(), height) - if !ok { - return nil, false - } - - valSet := stakingtypes.Validators(histInfo.Valset) - - tmValidators, err := testutil.ToTmValidators(valSet, sdk.DefaultPowerReduction) - if err != nil { - panic(err) - } - return tmtypes.NewValidatorSet(tmValidators), true -} - -// GetAcknowledgement retrieves an acknowledgement for the provided packet. If the -// acknowledgement does not exist then testing will fail. -func (chain *TestChain) GetAcknowledgement(packet exported.PacketI) []byte { - ack, found := chain.App.IBCKeeper.ChannelKeeper.GetPacketAcknowledgement(chain.GetContext(), packet.GetDestPort(), packet.GetDestChannel(), packet.GetSequence()) - require.True(chain.t, found) - - return ack -} - -// GetPrefix returns the prefix for used by a chain in connection creation -func (chain *TestChain) GetPrefix() commitmenttypes.MerklePrefix { - return commitmenttypes.NewMerklePrefix(chain.App.IBCKeeper.ConnectionKeeper.GetCommitmentPrefix().Bytes()) -} - -// ConstructUpdateTMClientHeader will construct a valid 07-tendermint Header to update the -// light client on the source chain. -func (chain *TestChain) ConstructUpdateTMClientHeader(counterparty *TestChain, clientID string) (*ibctm.Header, error) { - return chain.ConstructUpdateTMClientHeaderWithTrustedHeight(counterparty, clientID, clienttypes.ZeroHeight()) -} - -// ConstructUpdateTMClientHeader will construct a valid 07-tendermint Header to update the -// light client on the source chain. -func (chain *TestChain) ConstructUpdateTMClientHeaderWithTrustedHeight(counterparty *TestChain, clientID string, trustedHeight clienttypes.Height) (*ibctm.Header, error) { - header := counterparty.LastHeader - // Relayer must query for LatestHeight on client to get TrustedHeight if the trusted height is not set - if trustedHeight.IsZero() { - trustedHeight = chain.GetClientState(clientID).GetLatestHeight().(clienttypes.Height) - } - var ( - tmTrustedVals *tmtypes.ValidatorSet - ok bool - ) - // Once we get TrustedHeight from client, we must query the validators from the counterparty chain - // If the LatestHeight == LastHeader.Height, then TrustedValidators are current validators - // If LatestHeight < LastHeader.Height, we can query the historical validator set from HistoricalInfo - if trustedHeight == counterparty.LastHeader.GetHeight() { - tmTrustedVals = counterparty.Vals - } else { - // NOTE: We need to get validators from counterparty at height: trustedHeight+1 - // since the last trusted validators for a header at height h - // is the NextValidators at h+1 committed to in header h by - // NextValidatorsHash - tmTrustedVals, ok = counterparty.GetValsAtHeight(int64(trustedHeight.RevisionHeight + 1)) - if !ok { - return nil, errorsmod.Wrapf(ibctm.ErrInvalidHeaderHeight, "could not retrieve trusted validators at trustedHeight: %d", trustedHeight) - } - } - // inject trusted fields into last header - // for now assume revision number is 0 - header.TrustedHeight = trustedHeight - - trustedVals, err := tmTrustedVals.ToProto() - if err != nil { - return nil, err - } - header.TrustedValidators = trustedVals - - return header, nil -} - -// ExpireClient fast forwards the chain's block time by the provided amount of time which will -// expire any clients with a trusting period less than or equal to this amount of time. -func (chain *TestChain) ExpireClient(amount time.Duration) { - chain.Coordinator.IncrementTimeBy(amount) -} - -// CurrentTMClientHeader creates a TM header using the current header parameters -// on the chain. The trusted fields in the header are set to nil. -func (chain *TestChain) CurrentTMClientHeader() *ibctm.Header { - return chain.CreateTMClientHeader(chain.ChainID, chain.CurrentHeader.Height, clienttypes.Height{}, chain.CurrentHeader.Time, chain.Vals, chain.NextVals, nil, chain.Signers) -} - -// CreateTMClientHeader creates a TM header to update the TM client. Args are passed in to allow -// caller flexibility to use params that differ from the chain. -func (chain *TestChain) CreateTMClientHeader(chainID string, blockHeight int64, trustedHeight clienttypes.Height, timestamp time.Time, tmValSet, nextVals, tmTrustedVals *tmtypes.ValidatorSet, signers map[string]tmtypes.PrivValidator) *ibctm.Header { - var ( - valSet *tmproto.ValidatorSet - trustedVals *tmproto.ValidatorSet - ) - require.NotNil(chain.t, tmValSet) - - vsetHash := tmValSet.Hash() - nextValHash := nextVals.Hash() - - tmHeader := tmtypes.Header{ - Version: tmprotoversion.Consensus{Block: tmversion.BlockProtocol, App: 2}, - ChainID: chainID, - Height: blockHeight, - Time: timestamp, - LastBlockID: MakeBlockID(make([]byte, tmhash.Size), 10_000, make([]byte, tmhash.Size)), - LastCommitHash: chain.App.LastCommitID().Hash, - DataHash: tmhash.Sum([]byte("data_hash")), - ValidatorsHash: vsetHash, - NextValidatorsHash: nextValHash, - ConsensusHash: tmhash.Sum([]byte("consensus_hash")), - AppHash: chain.CurrentHeader.AppHash, - LastResultsHash: tmhash.Sum([]byte("last_results_hash")), - EvidenceHash: tmhash.Sum([]byte("evidence_hash")), - ProposerAddress: tmValSet.Proposer.Address, //nolint:staticcheck // SA5011: possible nil pointer dereference - } - - hhash := tmHeader.Hash() - blockID := MakeBlockID(hhash, 3, tmhash.Sum([]byte("part_set"))) - voteSet := tmtypes.NewVoteSet(chainID, blockHeight, 1, tmproto.PrecommitType, tmValSet) - // MakeCommit expects a signer array in the same order as the validator array. - // Thus we iterate over the ordered validator set and construct a signer array - // from the signer map in the same order. - signerArr := make([]tmtypes.PrivValidator, len(tmValSet.Validators)) //nolint:staticcheck - for i, v := range tmValSet.Validators { //nolint:staticcheck - signerArr[i] = signers[v.Address.String()] - } - - commit, err := tmtypes.MakeCommit(blockID, blockHeight, 1, voteSet, signerArr, timestamp) - require.NoError(chain.t, err) - - signedHeader := &tmproto.SignedHeader{ - Header: tmHeader.ToProto(), - Commit: commit.ToProto(), - } - - if tmValSet != nil { //nolint:staticcheck - valSet, err = tmValSet.ToProto() - require.NoError(chain.t, err) - } - - if tmTrustedVals != nil { - trustedVals, err = tmTrustedVals.ToProto() - require.NoError(chain.t, err) - } - - // The trusted fields may be nil. They may be filled before relaying messages to a client. - // The relayer is responsible for querying client and injecting appropriate trusted fields. - return &ibctm.Header{ - SignedHeader: signedHeader, - ValidatorSet: valSet, - TrustedHeight: trustedHeight, - TrustedValidators: trustedVals, - } -} - -// MakeBlockID copied unimported test functions from tmtypes to use them here -func MakeBlockID(hash []byte, partSetSize uint32, partSetHash []byte) tmtypes.BlockID { - return tmtypes.BlockID{ - Hash: hash, - PartSetHeader: tmtypes.PartSetHeader{ - Total: partSetSize, - Hash: partSetHash, - }, - } -} - -// CreatePortCapability binds and claims a capability for the given portID if it does not -// already exist. This function will fail testing on any resulting error. -// NOTE: only creation of a capability for a transfer or mock port is supported -// Other applications must bind to the port in InitGenesis or modify this code. -func (chain *TestChain) CreatePortCapability(scopedKeeper capabilitykeeper.ScopedKeeper, portID string) { - // check if the portId is already binded, if not bind it - _, ok := chain.App.ScopedIBCKeeper.GetCapability(chain.GetContext(), host.PortPath(portID)) - if !ok { - // create capability using the IBC capability keeper - portCap, err := chain.App.ScopedIBCKeeper.NewCapability(chain.GetContext(), host.PortPath(portID)) - require.NoError(chain.t, err) - - // claim capability using the scopedKeeper - err = scopedKeeper.ClaimCapability(chain.GetContext(), portCap, host.PortPath(portID)) - require.NoError(chain.t, err) - } - - chain.NextBlock() -} - -// GetPortCapability returns the port capability for the given portID. The capability must -// exist, otherwise testing will fail. -func (chain *TestChain) GetPortCapability(portID string) *capabilitytypes.Capability { - portCap, ok := chain.App.ScopedIBCKeeper.GetCapability(chain.GetContext(), host.PortPath(portID)) - require.True(chain.t, ok) - - return portCap -} - -// CreateChannelCapability binds and claims a capability for the given portID and channelID -// if it does not already exist. This function will fail testing on any resulting error. The -// scoped keeper passed in will claim the new capability. -func (chain *TestChain) CreateChannelCapability(scopedKeeper capabilitykeeper.ScopedKeeper, portID, channelID string) { - capName := host.ChannelCapabilityPath(portID, channelID) - // check if the portId is already binded, if not bind it - _, ok := chain.App.ScopedIBCKeeper.GetCapability(chain.GetContext(), capName) - if !ok { - portCap, err := chain.App.ScopedIBCKeeper.NewCapability(chain.GetContext(), capName) - require.NoError(chain.t, err) - err = scopedKeeper.ClaimCapability(chain.GetContext(), portCap, capName) - require.NoError(chain.t, err) - } - - chain.NextBlock() -} - -// GetChannelCapability returns the channel capability for the given portID and channelID. -// The capability must exist, otherwise testing will fail. -func (chain *TestChain) GetChannelCapability(portID, channelID string) *capabilitytypes.Capability { - chanCap, ok := chain.App.ScopedIBCKeeper.GetCapability(chain.GetContext(), host.ChannelCapabilityPath(portID, channelID)) - require.True(chain.t, ok) - - return chanCap -} - -// GetTimeoutHeight is a convenience function which returns a IBC packet timeout height -// to be used for testing. It returns the current IBC height + 100 blocks -func (chain *TestChain) GetTimeoutHeight() clienttypes.Height { - return clienttypes.NewHeight(clienttypes.ParseChainID(chain.ChainID), uint64(chain.GetContext().BlockHeight())+100) -} - -func (chain *TestChain) Balance(acc sdk.AccAddress, denom string) sdk.Coin { - return chain.App.BankKeeper.GetBalance(chain.GetContext(), acc, denom) -} - -func (chain *TestChain) AllBalances(acc sdk.AccAddress) sdk.Coins { - return chain.App.BankKeeper.GetAllBalances(chain.GetContext(), acc) -} diff --git a/x/wasm/ibctesting/coordinator.go b/x/wasm/ibctesting/coordinator.go deleted file mode 100644 index 4f691ff..0000000 --- a/x/wasm/ibctesting/coordinator.go +++ /dev/null @@ -1,311 +0,0 @@ -package ibctesting - -import ( - "fmt" - "testing" - "time" - - abci "github.com/cometbft/cometbft/abci/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - host "github.com/cosmos/ibc-go/v7/modules/core/24-host" - ibctesting "github.com/cosmos/ibc-go/v7/testing" - "github.com/stretchr/testify/require" - - wasmkeeper "github.com/terpnetwork/terp-core/x/wasm/keeper" -) - -var ( - TimeIncrement = time.Second * 5 - globalStartTime = time.Date(2020, 1, 2, 0, 0, 0, 0, time.UTC) -) - -// Coordinator is a testing struct which contains N TestChain's. It handles keeping all chains -// in sync with regards to time. -type Coordinator struct { - t *testing.T - - CurrentTime time.Time - Chains map[string]*TestChain -} - -// NewCoordinator initializes Coordinator with N TestChain's -func NewCoordinator(t *testing.T, n int, opts ...[]wasmkeeper.Option) *Coordinator { - t.Helper() - chains := make(map[string]*TestChain) - coord := &Coordinator{ - t: t, - CurrentTime: globalStartTime, - } - - for i := 1; i <= n; i++ { - chainID := GetChainID(i) - var x []wasmkeeper.Option - if len(opts) > (i - 1) { - x = opts[i-1] - } - chains[chainID] = NewTestChain(t, coord, chainID, x...) - } - coord.Chains = chains - - return coord -} - -// IncrementTime iterates through all the TestChain's and increments their current header time -// by 5 seconds. -// -// CONTRACT: this function must be called after every Commit on any TestChain. -func (coord *Coordinator) IncrementTime() { - coord.IncrementTimeBy(TimeIncrement) -} - -// IncrementTimeBy iterates through all the TestChain's and increments their current header time -// by specified time. -func (coord *Coordinator) IncrementTimeBy(increment time.Duration) { - coord.CurrentTime = coord.CurrentTime.Add(increment).UTC() - coord.UpdateTime() -} - -// UpdateTime updates all clocks for the TestChains to the current global time. -func (coord *Coordinator) UpdateTime() { - for _, chain := range coord.Chains { - coord.UpdateTimeForChain(chain) - } -} - -// UpdateTimeForChain updates the clock for a specific chain. -func (coord *Coordinator) UpdateTimeForChain(chain *TestChain) { - chain.CurrentHeader.Time = coord.CurrentTime.UTC() - chain.App.BeginBlock(abci.RequestBeginBlock{Header: chain.CurrentHeader}) -} - -// Setup constructs a TM client, connection, and channel on both chains provided. It will -// fail if any error occurs. The clientID's, TestConnections, and TestChannels are returned -// for both chains. The channels created are connected to the ibc-transfer application. -func (coord *Coordinator) Setup(path *Path) { - coord.SetupConnections(path) - - // channels can also be referenced through the returned connections - coord.CreateChannels(path) -} - -// SetupClients is a helper function to create clients on both chains. It assumes the -// caller does not anticipate any errors. -func (coord *Coordinator) SetupClients(path *Path) { - err := path.EndpointA.CreateClient() - require.NoError(coord.t, err) - - err = path.EndpointB.CreateClient() - require.NoError(coord.t, err) -} - -// SetupClientConnections is a helper function to create clients and the appropriate -// connections on both the source and counterparty chain. It assumes the caller does not -// anticipate any errors. -func (coord *Coordinator) SetupConnections(path *Path) { - coord.SetupClients(path) - - coord.CreateConnections(path) -} - -// CreateConnection constructs and executes connection handshake messages in order to create -// OPEN channels on chainA and chainB. The connection information of for chainA and chainB -// are returned within a TestConnection struct. The function expects the connections to be -// successfully opened otherwise testing will fail. -func (coord *Coordinator) CreateConnections(path *Path) { - err := path.EndpointA.ConnOpenInit() - require.NoError(coord.t, err) - - err = path.EndpointB.ConnOpenTry() - require.NoError(coord.t, err) - - err = path.EndpointA.ConnOpenAck() - require.NoError(coord.t, err) - - err = path.EndpointB.ConnOpenConfirm() - require.NoError(coord.t, err) - - // ensure counterparty is up to date - err = path.EndpointA.UpdateClient() - require.NoError(coord.t, err) -} - -// CreateMockChannels constructs and executes channel handshake messages to create OPEN -// channels that use a mock application module that returns nil on all callbacks. This -// function is expects the channels to be successfully opened otherwise testing will -// fail. -func (coord *Coordinator) CreateMockChannels(path *Path) { - path.EndpointA.ChannelConfig.PortID = ibctesting.MockPort - path.EndpointB.ChannelConfig.PortID = ibctesting.MockPort - - coord.CreateChannels(path) -} - -// CreateTransferChannels constructs and executes channel handshake messages to create OPEN -// ibc-transfer channels on chainA and chainB. The function expects the channels to be -// successfully opened otherwise testing will fail. -func (coord *Coordinator) CreateTransferChannels(path *Path) { - path.EndpointA.ChannelConfig.PortID = ibctesting.TransferPort - path.EndpointB.ChannelConfig.PortID = ibctesting.TransferPort - - coord.CreateChannels(path) -} - -// CreateChannel constructs and executes channel handshake messages in order to create -// OPEN channels on chainA and chainB. The function expects the channels to be successfully -// opened otherwise testing will fail. -func (coord *Coordinator) CreateChannels(path *Path) { - err := path.EndpointA.ChanOpenInit() - require.NoError(coord.t, err) - - err = path.EndpointB.ChanOpenTry() - require.NoError(coord.t, err) - - err = path.EndpointA.ChanOpenAck() - require.NoError(coord.t, err) - - err = path.EndpointB.ChanOpenConfirm() - require.NoError(coord.t, err) - - // ensure counterparty is up to date - err = path.EndpointA.UpdateClient() - require.NoError(coord.t, err) -} - -// GetChain returns the TestChain using the given chainID and returns an error if it does -// not exist. -func (coord *Coordinator) GetChain(chainID string) *TestChain { - chain, found := coord.Chains[chainID] - require.True(coord.t, found, fmt.Sprintf("%s chain does not exist", chainID)) - return chain -} - -// GetChainID returns the chainID used for the provided index. -func GetChainID(index int) string { - return ibctesting.GetChainID(index) -} - -// CommitBlock commits a block on the provided indexes and then increments the global time. -// -// CONTRACT: the passed in list of indexes must not contain duplicates -func (coord *Coordinator) CommitBlock(chains ...*TestChain) { - for _, chain := range chains { - chain.NextBlock() - } - coord.IncrementTime() -} - -// CommitNBlocks commits n blocks to state and updates the block height by 1 for each commit. -func (coord *Coordinator) CommitNBlocks(chain *TestChain, n uint64) { - for i := uint64(0); i < n; i++ { - chain.App.BeginBlock(abci.RequestBeginBlock{Header: chain.CurrentHeader}) - chain.NextBlock() - coord.IncrementTime() - } -} - -// ConnOpenInitOnBothChains initializes a connection on both endpoints with the state INIT -// using the OpenInit handshake call. -func (coord *Coordinator) ConnOpenInitOnBothChains(path *Path) error { - if err := path.EndpointA.ConnOpenInit(); err != nil { - return err - } - - if err := path.EndpointB.ConnOpenInit(); err != nil { - return err - } - - if err := path.EndpointA.UpdateClient(); err != nil { - return err - } - - err := path.EndpointB.UpdateClient() - - return err -} - -// ChanOpenInitOnBothChains initializes a channel on the source chain and counterparty chain -// with the state INIT using the OpenInit handshake call. -func (coord *Coordinator) ChanOpenInitOnBothChains(path *Path) error { - // NOTE: only creation of a capability for a transfer or mock port is supported - // Other applications must bind to the port in InitGenesis or modify this code. - - if err := path.EndpointA.ChanOpenInit(); err != nil { - return err - } - - if err := path.EndpointB.ChanOpenInit(); err != nil { - return err - } - - if err := path.EndpointA.UpdateClient(); err != nil { - return err - } - - err := path.EndpointB.UpdateClient() - - return err -} - -// RelayAndAckPendingPackets sends pending packages from path.EndpointA to the counterparty chain and acks -func (coord *Coordinator) RelayAndAckPendingPackets(path *Path) error { - // get all the packet to relay src->dest - src := path.EndpointA - coord.t.Logf("Relay: %d Packets A->B, %d Packets B->A\n", len(src.Chain.PendingSendPackets), len(path.EndpointB.Chain.PendingSendPackets)) - for i, v := range src.Chain.PendingSendPackets { - err := path.RelayPacket(v, nil) - if err != nil { - return err - } - src.Chain.PendingSendPackets = append(src.Chain.PendingSendPackets[0:i], src.Chain.PendingSendPackets[i+1:]...) - } - - src = path.EndpointB - for i, v := range src.Chain.PendingSendPackets { - err := path.RelayPacket(v, nil) - if err != nil { - return err - } - src.Chain.PendingSendPackets = append(src.Chain.PendingSendPackets[0:i], src.Chain.PendingSendPackets[i+1:]...) - } - return nil -} - -// TimeoutPendingPackets returns the package to source chain to let the IBC app revert any operation. -// from A to A -func (coord *Coordinator) TimeoutPendingPackets(path *Path) error { - src := path.EndpointA - dest := path.EndpointB - - toSend := src.Chain.PendingSendPackets - coord.t.Logf("Timeout %d Packets A->A\n", len(toSend)) - - if err := src.UpdateClient(); err != nil { - return err - } - // Increment time and commit block so that 5 second delay period passes between send and receive - coord.IncrementTime() - coord.CommitBlock(src.Chain, dest.Chain) - for _, packet := range toSend { - // get proof of packet unreceived on dest - packetKey := host.PacketReceiptKey(packet.GetDestPort(), packet.GetDestChannel(), packet.GetSequence()) - proofUnreceived, proofHeight := dest.QueryProof(packetKey) - timeoutMsg := channeltypes.NewMsgTimeout(packet, packet.Sequence, proofUnreceived, proofHeight, src.Chain.SenderAccount.GetAddress().String()) - err := src.Chain.sendMsgs(timeoutMsg) - if err != nil { - return err - } - } - src.Chain.PendingSendPackets = nil - return nil -} - -// CloseChannel close channel on both sides -func (coord *Coordinator) CloseChannel(path *Path) { - err := path.EndpointA.ChanCloseInit() - require.NoError(coord.t, err) - coord.IncrementTime() - err = path.EndpointB.UpdateClient() - require.NoError(coord.t, err) - err = path.EndpointB.ChanCloseConfirm() - require.NoError(coord.t, err) -} diff --git a/x/wasm/ibctesting/endpoint.go b/x/wasm/ibctesting/endpoint.go deleted file mode 100644 index 4eb47ba..0000000 --- a/x/wasm/ibctesting/endpoint.go +++ /dev/null @@ -1,657 +0,0 @@ -package ibctesting - -import ( - "fmt" - "strings" - - "github.com/cosmos/cosmos-sdk/baseapp" - sdk "github.com/cosmos/cosmos-sdk/types" - clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" - connectiontypes "github.com/cosmos/ibc-go/v7/modules/core/03-connection/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - commitmenttypes "github.com/cosmos/ibc-go/v7/modules/core/23-commitment/types" - host "github.com/cosmos/ibc-go/v7/modules/core/24-host" - "github.com/cosmos/ibc-go/v7/modules/core/exported" - ibctm "github.com/cosmos/ibc-go/v7/modules/light-clients/07-tendermint" - ibctesting "github.com/cosmos/ibc-go/v7/testing" - "github.com/stretchr/testify/require" -) - -// Endpoint is a which represents a channel endpoint and its associated -// client and connections. It contains client, connection, and channel -// configuration parameters. Endpoint functions will utilize the parameters -// set in the configuration structs when executing IBC messages. -type Endpoint struct { - Chain *TestChain - Counterparty *Endpoint - ClientID string - ConnectionID string - ChannelID string - - ClientConfig ibctesting.ClientConfig - ConnectionConfig *ibctesting.ConnectionConfig - ChannelConfig *ibctesting.ChannelConfig -} - -// NewEndpoint constructs a new endpoint without the counterparty. -// CONTRACT: the counterparty endpoint must be set by the caller. -func NewEndpoint( - chain *TestChain, clientConfig ibctesting.ClientConfig, - connectionConfig *ibctesting.ConnectionConfig, channelConfig *ibctesting.ChannelConfig, -) *Endpoint { - return &Endpoint{ - Chain: chain, - ClientConfig: clientConfig, - ConnectionConfig: connectionConfig, - ChannelConfig: channelConfig, - } -} - -// NewDefaultEndpoint constructs a new endpoint using default values. -// CONTRACT: the counterparty endpoitn must be set by the caller. -func NewDefaultEndpoint(chain *TestChain) *Endpoint { - return &Endpoint{ - Chain: chain, - ClientConfig: ibctesting.NewTendermintConfig(), - ConnectionConfig: ibctesting.NewConnectionConfig(), - ChannelConfig: ibctesting.NewChannelConfig(), - } -} - -// QueryProof queries proof associated with this endpoint using the lastest client state -// height on the counterparty chain. -func (endpoint *Endpoint) QueryProof(key []byte) ([]byte, clienttypes.Height) { - // obtain the counterparty client representing the chain associated with the endpoint - clientState := endpoint.Counterparty.Chain.GetClientState(endpoint.Counterparty.ClientID) - - // query proof on the counterparty using the latest height of the IBC client - return endpoint.QueryProofAtHeight(key, clientState.GetLatestHeight().GetRevisionHeight()) -} - -// QueryProofAtHeight queries proof associated with this endpoint using the proof height -// provided -func (endpoint *Endpoint) QueryProofAtHeight(key []byte, height uint64) ([]byte, clienttypes.Height) { - // query proof on the counterparty using the latest height of the IBC client - return endpoint.Chain.QueryProofAtHeight(key, int64(height)) -} - -// CreateClient creates an IBC client on the endpoint. It will update the -// clientID for the endpoint if the message is successfully executed. -// NOTE: a solo machine client will be created with an empty diversifier. -func (endpoint *Endpoint) CreateClient() (err error) { - // ensure counterparty has committed state - endpoint.Chain.Coordinator.CommitBlock(endpoint.Counterparty.Chain) - - var ( - clientState exported.ClientState - consensusState exported.ConsensusState - ) - - switch endpoint.ClientConfig.GetClientType() { - case exported.Tendermint: - tmConfig, ok := endpoint.ClientConfig.(*ibctesting.TendermintConfig) - require.True(endpoint.Chain.t, ok) - - height := endpoint.Counterparty.Chain.LastHeader.GetHeight().(clienttypes.Height) - clientState = ibctm.NewClientState( - endpoint.Counterparty.Chain.ChainID, tmConfig.TrustLevel, tmConfig.TrustingPeriod, tmConfig.UnbondingPeriod, tmConfig.MaxClockDrift, - height, commitmenttypes.GetSDKSpecs(), ibctesting.UpgradePath) - consensusState = endpoint.Counterparty.Chain.LastHeader.ConsensusState() - case exported.Solomachine: - // TODO - // solo := NewSolomachine(chain.t, endpoint.Chain.Codec, clientID, "", 1) - // clientState = solo.ClientState() - // consensusState = solo.ConsensusState() - - default: - err = fmt.Errorf("client type %s is not supported", endpoint.ClientConfig.GetClientType()) - } - - if err != nil { - return err - } - - msg, err := clienttypes.NewMsgCreateClient( - clientState, consensusState, endpoint.Chain.SenderAccount.GetAddress().String(), - ) - require.NoError(endpoint.Chain.t, err) - - res, err := endpoint.Chain.SendMsgs(msg) - if err != nil { - return err - } - - endpoint.ClientID, err = ibctesting.ParseClientIDFromEvents(res.GetEvents()) - require.NoError(endpoint.Chain.t, err) - - return nil -} - -// UpdateClient updates the IBC client associated with the endpoint. -func (endpoint *Endpoint) UpdateClient() (err error) { - // ensure counterparty has committed state - endpoint.Chain.Coordinator.CommitBlock(endpoint.Counterparty.Chain) - - var header exported.ClientMessage - - switch endpoint.ClientConfig.GetClientType() { - case exported.Tendermint: - header, err = endpoint.Chain.ConstructUpdateTMClientHeader(endpoint.Counterparty.Chain, endpoint.ClientID) - - default: - err = fmt.Errorf("client type %s is not supported", endpoint.ClientConfig.GetClientType()) - } - - if err != nil { - return err - } - - msg, err := clienttypes.NewMsgUpdateClient( - endpoint.ClientID, header, - endpoint.Chain.SenderAccount.GetAddress().String(), - ) - require.NoError(endpoint.Chain.t, err) - - return endpoint.Chain.sendMsgs(msg) -} - -// UpgradeChain will upgrade a chain's chainID to the next revision number. -// It will also update the counterparty client. -// TODO: implement actual upgrade chain functionality via scheduling an upgrade -// and upgrading the client via MsgUpgradeClient -// see reference https://github.com/cosmos/ibc-go/pull/1169 -func (endpoint *Endpoint) UpgradeChain() error { - if strings.TrimSpace(endpoint.Counterparty.ClientID) == "" { - return fmt.Errorf("cannot upgrade chain if there is no counterparty client") - } - - clientState := endpoint.Counterparty.GetClientState().(*ibctm.ClientState) - - // increment revision number in chainID - - oldChainID := clientState.ChainId - if !clienttypes.IsRevisionFormat(oldChainID) { - return fmt.Errorf("cannot upgrade chain which is not of revision format: %s", oldChainID) - } - - revisionNumber := clienttypes.ParseChainID(oldChainID) - newChainID, err := clienttypes.SetRevisionNumber(oldChainID, revisionNumber+1) - if err != nil { - return err - } - - // update chain - baseapp.SetChainID(newChainID)(endpoint.Chain.App.BaseApp) - endpoint.Chain.ChainID = newChainID - endpoint.Chain.CurrentHeader.ChainID = newChainID - endpoint.Chain.NextBlock() // commit changes - - // update counterparty client manually - clientState.ChainId = newChainID - clientState.LatestHeight = clienttypes.NewHeight(revisionNumber+1, clientState.LatestHeight.GetRevisionHeight()+1) - endpoint.Counterparty.SetClientState(clientState) - - consensusState := &ibctm.ConsensusState{ - Timestamp: endpoint.Chain.LastHeader.GetTime(), - Root: commitmenttypes.NewMerkleRoot(endpoint.Chain.LastHeader.Header.GetAppHash()), - NextValidatorsHash: endpoint.Chain.LastHeader.Header.NextValidatorsHash, - } - endpoint.Counterparty.SetConsensusState(consensusState, clientState.GetLatestHeight()) - - // ensure the next update isn't identical to the one set in state - endpoint.Chain.Coordinator.IncrementTime() - endpoint.Chain.NextBlock() - - if err = endpoint.Counterparty.UpdateClient(); err != nil { - return err - } - - return nil -} - -// ConnOpenInit will construct and execute a MsgConnectionOpenInit on the associated endpoint. -func (endpoint *Endpoint) ConnOpenInit() error { - msg := connectiontypes.NewMsgConnectionOpenInit( - endpoint.ClientID, - endpoint.Counterparty.ClientID, - endpoint.Counterparty.Chain.GetPrefix(), ibctesting.DefaultOpenInitVersion, endpoint.ConnectionConfig.DelayPeriod, - endpoint.Chain.SenderAccount.GetAddress().String(), - ) - res, err := endpoint.Chain.SendMsgs(msg) - if err != nil { - return err - } - - endpoint.ConnectionID, err = ibctesting.ParseConnectionIDFromEvents(res.GetEvents()) - require.NoError(endpoint.Chain.t, err) - - return nil -} - -// ConnOpenTry will construct and execute a MsgConnectionOpenTry on the associated endpoint. -func (endpoint *Endpoint) ConnOpenTry() error { - err := endpoint.UpdateClient() - require.NoError(endpoint.Chain.t, err) - - counterpartyClient, proofClient, proofConsensus, consensusHeight, proofInit, proofHeight := endpoint.QueryConnectionHandshakeProof() - - msg := connectiontypes.NewMsgConnectionOpenTry( - endpoint.ClientID, endpoint.Counterparty.ConnectionID, endpoint.Counterparty.ClientID, - counterpartyClient, endpoint.Counterparty.Chain.GetPrefix(), []*connectiontypes.Version{ibctesting.ConnectionVersion}, endpoint.ConnectionConfig.DelayPeriod, - proofInit, proofClient, proofConsensus, - proofHeight, consensusHeight, - endpoint.Chain.SenderAccount.GetAddress().String(), - ) - res, err := endpoint.Chain.SendMsgs(msg) - if err != nil { - return err - } - - if endpoint.ConnectionID == "" { - endpoint.ConnectionID, err = ibctesting.ParseConnectionIDFromEvents(res.GetEvents()) - require.NoError(endpoint.Chain.t, err) - } - - return nil -} - -// ConnOpenAck will construct and execute a MsgConnectionOpenAck on the associated endpoint. -func (endpoint *Endpoint) ConnOpenAck() error { - err := endpoint.UpdateClient() - require.NoError(endpoint.Chain.t, err) - - counterpartyClient, proofClient, proofConsensus, consensusHeight, proofTry, proofHeight := endpoint.QueryConnectionHandshakeProof() - - msg := connectiontypes.NewMsgConnectionOpenAck( - endpoint.ConnectionID, endpoint.Counterparty.ConnectionID, counterpartyClient, // testing doesn't use flexible selection - proofTry, proofClient, proofConsensus, - proofHeight, consensusHeight, - ibctesting.ConnectionVersion, - endpoint.Chain.SenderAccount.GetAddress().String(), - ) - return endpoint.Chain.sendMsgs(msg) -} - -// ConnOpenConfirm will construct and execute a MsgConnectionOpenConfirm on the associated endpoint. -func (endpoint *Endpoint) ConnOpenConfirm() error { - err := endpoint.UpdateClient() - require.NoError(endpoint.Chain.t, err) - - connectionKey := host.ConnectionKey(endpoint.Counterparty.ConnectionID) - proof, height := endpoint.Counterparty.Chain.QueryProof(connectionKey) - - msg := connectiontypes.NewMsgConnectionOpenConfirm( - endpoint.ConnectionID, - proof, height, - endpoint.Chain.SenderAccount.GetAddress().String(), - ) - return endpoint.Chain.sendMsgs(msg) -} - -// QueryConnectionHandshakeProof returns all the proofs necessary to execute OpenTry or Open Ack of -// the connection handshakes. It returns the counterparty client state, proof of the counterparty -// client state, proof of the counterparty consensus state, the consensus state height, proof of -// the counterparty connection, and the proof height for all the proofs returned. -func (endpoint *Endpoint) QueryConnectionHandshakeProof() ( - clientState exported.ClientState, proofClient, - proofConsensus []byte, consensusHeight clienttypes.Height, - proofConnection []byte, proofHeight clienttypes.Height, -) { - // obtain the client state on the counterparty chain - clientState = endpoint.Counterparty.Chain.GetClientState(endpoint.Counterparty.ClientID) - - // query proof for the client state on the counterparty - clientKey := host.FullClientStateKey(endpoint.Counterparty.ClientID) - proofClient, proofHeight = endpoint.Counterparty.QueryProof(clientKey) - - consensusHeight = clientState.GetLatestHeight().(clienttypes.Height) - - // query proof for the consensus state on the counterparty - consensusKey := host.FullConsensusStateKey(endpoint.Counterparty.ClientID, consensusHeight) - proofConsensus, _ = endpoint.Counterparty.QueryProofAtHeight(consensusKey, proofHeight.GetRevisionHeight()) - - // query proof for the connection on the counterparty - connectionKey := host.ConnectionKey(endpoint.Counterparty.ConnectionID) - proofConnection, _ = endpoint.Counterparty.QueryProofAtHeight(connectionKey, proofHeight.GetRevisionHeight()) - - return -} - -// ChanOpenInit will construct and execute a MsgChannelOpenInit on the associated endpoint. -func (endpoint *Endpoint) ChanOpenInit() error { - msg := channeltypes.NewMsgChannelOpenInit( - endpoint.ChannelConfig.PortID, - endpoint.ChannelConfig.Version, endpoint.ChannelConfig.Order, []string{endpoint.ConnectionID}, - endpoint.Counterparty.ChannelConfig.PortID, - endpoint.Chain.SenderAccount.GetAddress().String(), - ) - res, err := endpoint.Chain.SendMsgs(msg) - if err != nil { - return err - } - - endpoint.ChannelID, err = ibctesting.ParseChannelIDFromEvents(res.GetEvents()) - require.NoError(endpoint.Chain.t, err) - - // update version to selected app version - // NOTE: this update must be performed after SendMsgs() - endpoint.ChannelConfig.Version = endpoint.GetChannel().Version - - return nil -} - -// ChanOpenTry will construct and execute a MsgChannelOpenTry on the associated endpoint. -func (endpoint *Endpoint) ChanOpenTry() error { - err := endpoint.UpdateClient() - require.NoError(endpoint.Chain.t, err) - - channelKey := host.ChannelKey(endpoint.Counterparty.ChannelConfig.PortID, endpoint.Counterparty.ChannelID) - proof, height := endpoint.Counterparty.Chain.QueryProof(channelKey) - - msg := channeltypes.NewMsgChannelOpenTry( - endpoint.ChannelConfig.PortID, - endpoint.ChannelConfig.Version, endpoint.ChannelConfig.Order, []string{endpoint.ConnectionID}, - endpoint.Counterparty.ChannelConfig.PortID, endpoint.Counterparty.ChannelID, endpoint.Counterparty.ChannelConfig.Version, - proof, height, - endpoint.Chain.SenderAccount.GetAddress().String(), - ) - res, err := endpoint.Chain.SendMsgs(msg) - if err != nil { - return err - } - - if endpoint.ChannelID == "" { - endpoint.ChannelID, err = ibctesting.ParseChannelIDFromEvents(res.GetEvents()) - require.NoError(endpoint.Chain.t, err) - } - - // update version to selected app version - // NOTE: this update must be performed after the endpoint channelID is set - endpoint.ChannelConfig.Version = endpoint.GetChannel().Version - - return nil -} - -// ChanOpenAck will construct and execute a MsgChannelOpenAck on the associated endpoint. -func (endpoint *Endpoint) ChanOpenAck() error { - err := endpoint.UpdateClient() - require.NoError(endpoint.Chain.t, err) - - channelKey := host.ChannelKey(endpoint.Counterparty.ChannelConfig.PortID, endpoint.Counterparty.ChannelID) - proof, height := endpoint.Counterparty.Chain.QueryProof(channelKey) - - msg := channeltypes.NewMsgChannelOpenAck( - endpoint.ChannelConfig.PortID, endpoint.ChannelID, - endpoint.Counterparty.ChannelID, endpoint.Counterparty.ChannelConfig.Version, // testing doesn't use flexible selection - proof, height, - endpoint.Chain.SenderAccount.GetAddress().String(), - ) - if err := endpoint.Chain.sendMsgs(msg); err != nil { - return err - } - - endpoint.ChannelConfig.Version = endpoint.GetChannel().Version - return nil -} - -// ChanOpenConfirm will construct and execute a MsgChannelOpenConfirm on the associated endpoint. -func (endpoint *Endpoint) ChanOpenConfirm() error { - err := endpoint.UpdateClient() - require.NoError(endpoint.Chain.t, err) - - channelKey := host.ChannelKey(endpoint.Counterparty.ChannelConfig.PortID, endpoint.Counterparty.ChannelID) - proof, height := endpoint.Counterparty.Chain.QueryProof(channelKey) - - msg := channeltypes.NewMsgChannelOpenConfirm( - endpoint.ChannelConfig.PortID, endpoint.ChannelID, - proof, height, - endpoint.Chain.SenderAccount.GetAddress().String(), - ) - return endpoint.Chain.sendMsgs(msg) -} - -// ChanCloseInit will construct and execute a MsgChannelCloseInit on the associated endpoint. -// -// NOTE: does not work with ibc-transfer module -func (endpoint *Endpoint) ChanCloseInit() error { - msg := channeltypes.NewMsgChannelCloseInit( - endpoint.ChannelConfig.PortID, endpoint.ChannelID, - endpoint.Chain.SenderAccount.GetAddress().String(), - ) - return endpoint.Chain.sendMsgs(msg) -} - -// ChanCloseConfirm will construct and execute a NewMsgChannelCloseConfirm on the associated endpoint. -func (endpoint *Endpoint) ChanCloseConfirm() error { - channelKey := host.ChannelKey(endpoint.Counterparty.ChannelConfig.PortID, endpoint.Counterparty.ChannelID) - proof, proofHeight := endpoint.Counterparty.QueryProof(channelKey) - - msg := channeltypes.NewMsgChannelCloseConfirm( - endpoint.ChannelConfig.PortID, endpoint.ChannelID, - proof, proofHeight, - endpoint.Chain.SenderAccount.GetAddress().String(), - ) - return endpoint.Chain.sendMsgs(msg) -} - -// SendPacket sends a packet through the channel keeper using the associated endpoint -// The counterparty client is updated so proofs can be sent to the counterparty chain. -// The packet sequence generated for the packet to be sent is returned. An error -// is returned if one occurs. -func (endpoint *Endpoint) SendPacket( - timeoutHeight clienttypes.Height, - timeoutTimestamp uint64, - data []byte, -) (uint64, error) { - channelCap := endpoint.Chain.GetChannelCapability(endpoint.ChannelConfig.PortID, endpoint.ChannelID) - - // no need to send message, acting as a module - sequence, err := endpoint.Chain.App.IBCKeeper.ChannelKeeper.SendPacket(endpoint.Chain.GetContext(), channelCap, endpoint.ChannelConfig.PortID, endpoint.ChannelID, timeoutHeight, timeoutTimestamp, data) - if err != nil { - return 0, err - } - - // commit changes since no message was sent - endpoint.Chain.Coordinator.CommitBlock(endpoint.Chain) - - err = endpoint.Counterparty.UpdateClient() - if err != nil { - return 0, err - } - - return sequence, nil -} - -// RecvPacket receives a packet on the associated endpoint. -// The counterparty client is updated. -func (endpoint *Endpoint) RecvPacket(packet channeltypes.Packet) error { - _, err := endpoint.RecvPacketWithResult(packet) - if err != nil { - return err - } - - return nil -} - -// RecvPacketWithResult receives a packet on the associated endpoint and the result -// of the transaction is returned. The counterparty client is updated. -func (endpoint *Endpoint) RecvPacketWithResult(packet channeltypes.Packet) (*sdk.Result, error) { - // get proof of packet commitment on source - packetKey := host.PacketCommitmentKey(packet.GetSourcePort(), packet.GetSourceChannel(), packet.GetSequence()) - proof, proofHeight := endpoint.Counterparty.Chain.QueryProof(packetKey) - - recvMsg := channeltypes.NewMsgRecvPacket(packet, proof, proofHeight, endpoint.Chain.SenderAccount.GetAddress().String()) - - // receive on counterparty and update source client - res, err := endpoint.Chain.SendMsgs(recvMsg) - if err != nil { - return nil, err - } - - if err := endpoint.Counterparty.UpdateClient(); err != nil { - return nil, err - } - - return res, nil -} - -// WriteAcknowledgement writes an acknowledgement on the channel associated with the endpoint. -// The counterparty client is updated. -func (endpoint *Endpoint) WriteAcknowledgement(ack exported.Acknowledgement, packet exported.PacketI) error { - channelCap := endpoint.Chain.GetChannelCapability(packet.GetDestPort(), packet.GetDestChannel()) - - // no need to send message, acting as a handler - err := endpoint.Chain.App.IBCKeeper.ChannelKeeper.WriteAcknowledgement(endpoint.Chain.GetContext(), channelCap, packet, ack) - if err != nil { - return err - } - - // commit changes since no message was sent - endpoint.Chain.Coordinator.CommitBlock(endpoint.Chain) - - return endpoint.Counterparty.UpdateClient() -} - -// AcknowledgePacket sends a MsgAcknowledgement to the channel associated with the endpoint. -func (endpoint *Endpoint) AcknowledgePacket(packet channeltypes.Packet, ack []byte) error { - // get proof of acknowledgement on counterparty - packetKey := host.PacketAcknowledgementKey(packet.GetDestPort(), packet.GetDestChannel(), packet.GetSequence()) - proof, proofHeight := endpoint.Counterparty.QueryProof(packetKey) - - ackMsg := channeltypes.NewMsgAcknowledgement(packet, ack, proof, proofHeight, endpoint.Chain.SenderAccount.GetAddress().String()) - - return endpoint.Chain.sendMsgs(ackMsg) -} - -// TimeoutPacket sends a MsgTimeout to the channel associated with the endpoint. -func (endpoint *Endpoint) TimeoutPacket(packet channeltypes.Packet) error { - // get proof for timeout based on channel order - var packetKey []byte - - switch endpoint.ChannelConfig.Order { - case channeltypes.ORDERED: - packetKey = host.NextSequenceRecvKey(packet.GetDestPort(), packet.GetDestChannel()) - case channeltypes.UNORDERED: - packetKey = host.PacketReceiptKey(packet.GetDestPort(), packet.GetDestChannel(), packet.GetSequence()) - default: - return fmt.Errorf("unsupported order type %s", endpoint.ChannelConfig.Order) - } - - proof, proofHeight := endpoint.Counterparty.QueryProof(packetKey) - nextSeqRecv, found := endpoint.Counterparty.Chain.App.IBCKeeper.ChannelKeeper.GetNextSequenceRecv(endpoint.Counterparty.Chain.GetContext(), endpoint.ChannelConfig.PortID, endpoint.ChannelID) - require.True(endpoint.Chain.t, found) - - timeoutMsg := channeltypes.NewMsgTimeout( - packet, nextSeqRecv, - proof, proofHeight, endpoint.Chain.SenderAccount.GetAddress().String(), - ) - - return endpoint.Chain.sendMsgs(timeoutMsg) -} - -// TimeoutOnClose sends a MsgTimeoutOnClose to the channel associated with the endpoint. -func (endpoint *Endpoint) TimeoutOnClose(packet channeltypes.Packet) error { - // get proof for timeout based on channel order - var packetKey []byte - - switch endpoint.ChannelConfig.Order { - case channeltypes.ORDERED: - packetKey = host.NextSequenceRecvKey(packet.GetDestPort(), packet.GetDestChannel()) - case channeltypes.UNORDERED: - packetKey = host.PacketReceiptKey(packet.GetDestPort(), packet.GetDestChannel(), packet.GetSequence()) - default: - return fmt.Errorf("unsupported order type %s", endpoint.ChannelConfig.Order) - } - - proof, proofHeight := endpoint.Counterparty.QueryProof(packetKey) - - channelKey := host.ChannelKey(packet.GetDestPort(), packet.GetDestChannel()) - proofClosed, _ := endpoint.Counterparty.QueryProof(channelKey) - - nextSeqRecv, found := endpoint.Counterparty.Chain.App.IBCKeeper.ChannelKeeper.GetNextSequenceRecv(endpoint.Counterparty.Chain.GetContext(), endpoint.ChannelConfig.PortID, endpoint.ChannelID) - require.True(endpoint.Chain.t, found) - - timeoutOnCloseMsg := channeltypes.NewMsgTimeoutOnClose( - packet, nextSeqRecv, - proof, proofClosed, proofHeight, endpoint.Chain.SenderAccount.GetAddress().String(), - ) - - return endpoint.Chain.sendMsgs(timeoutOnCloseMsg) -} - -// SetChannelClosed sets a channel state to CLOSED. -func (endpoint *Endpoint) SetChannelClosed() error { - channel := endpoint.GetChannel() - - channel.State = channeltypes.CLOSED - endpoint.Chain.App.IBCKeeper.ChannelKeeper.SetChannel(endpoint.Chain.GetContext(), endpoint.ChannelConfig.PortID, endpoint.ChannelID, channel) - - endpoint.Chain.Coordinator.CommitBlock(endpoint.Chain) - - return endpoint.Counterparty.UpdateClient() -} - -// GetClientState retrieves the Client State for this endpoint. The -// client state is expected to exist otherwise testing will fail. -func (endpoint *Endpoint) GetClientState() exported.ClientState { - return endpoint.Chain.GetClientState(endpoint.ClientID) -} - -// SetClientState sets the client state for this endpoint. -func (endpoint *Endpoint) SetClientState(clientState exported.ClientState) { - endpoint.Chain.App.IBCKeeper.ClientKeeper.SetClientState(endpoint.Chain.GetContext(), endpoint.ClientID, clientState) -} - -// GetConsensusState retrieves the Consensus State for this endpoint at the provided height. -// The consensus state is expected to exist otherwise testing will fail. -func (endpoint *Endpoint) GetConsensusState(height exported.Height) exported.ConsensusState { - consensusState, found := endpoint.Chain.GetConsensusState(endpoint.ClientID, height) - require.True(endpoint.Chain.t, found) - - return consensusState -} - -// SetConsensusState sets the consensus state for this endpoint. -func (endpoint *Endpoint) SetConsensusState(consensusState exported.ConsensusState, height exported.Height) { - endpoint.Chain.App.IBCKeeper.ClientKeeper.SetClientConsensusState(endpoint.Chain.GetContext(), endpoint.ClientID, height, consensusState) -} - -// GetConnection retrieves an IBC Connection for the endpoint. The -// connection is expected to exist otherwise testing will fail. -func (endpoint *Endpoint) GetConnection() connectiontypes.ConnectionEnd { - connection, found := endpoint.Chain.App.IBCKeeper.ConnectionKeeper.GetConnection(endpoint.Chain.GetContext(), endpoint.ConnectionID) - require.True(endpoint.Chain.t, found) - - return connection -} - -// SetConnection sets the connection for this endpoint. -func (endpoint *Endpoint) SetConnection(connection connectiontypes.ConnectionEnd) { - endpoint.Chain.App.IBCKeeper.ConnectionKeeper.SetConnection(endpoint.Chain.GetContext(), endpoint.ConnectionID, connection) -} - -// GetChannel retrieves an IBC Channel for the endpoint. The channel -// is expected to exist otherwise testing will fail. -func (endpoint *Endpoint) GetChannel() channeltypes.Channel { - channel, found := endpoint.Chain.App.IBCKeeper.ChannelKeeper.GetChannel(endpoint.Chain.GetContext(), endpoint.ChannelConfig.PortID, endpoint.ChannelID) - require.True(endpoint.Chain.t, found) - - return channel -} - -// SetChannel sets the channel for this endpoint. -func (endpoint *Endpoint) SetChannel(channel channeltypes.Channel) { - endpoint.Chain.App.IBCKeeper.ChannelKeeper.SetChannel(endpoint.Chain.GetContext(), endpoint.ChannelConfig.PortID, endpoint.ChannelID, channel) -} - -// QueryClientStateProof performs and abci query for a client stat associated -// with this endpoint and returns the ClientState along with the proof. -func (endpoint *Endpoint) QueryClientStateProof() (exported.ClientState, []byte) { - // retrieve client state to provide proof for - clientState := endpoint.GetClientState() - - clientKey := host.FullClientStateKey(endpoint.ClientID) - proofClient, _ := endpoint.QueryProof(clientKey) - - return clientState, proofClient -} diff --git a/x/wasm/ibctesting/event_utils.go b/x/wasm/ibctesting/event_utils.go deleted file mode 100644 index a376901..0000000 --- a/x/wasm/ibctesting/event_utils.go +++ /dev/null @@ -1,118 +0,0 @@ -package ibctesting - -import ( - "encoding/hex" - "fmt" - "strconv" - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" - - abci "github.com/cometbft/cometbft/abci/types" - clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" -) - -func getSendPackets(evts []abci.Event) []channeltypes.Packet { - var res []channeltypes.Packet - for _, evt := range evts { - if evt.Type == channeltypes.EventTypeSendPacket { - packet := parsePacketFromEvent(evt) - res = append(res, packet) - } - } - return res -} - -// Used for various debug statements above when needed... do not remove -// func showEvent(evt abci.Event) { -// fmt.Printf("evt.Type: %s\n", evt.Type) -// for _, attr := range evt.Attributes { -// fmt.Printf(" %s = %s\n", string(attr.Key), string(attr.Value)) -// } -//} - -func parsePacketFromEvent(evt abci.Event) channeltypes.Packet { - return channeltypes.Packet{ - Sequence: getUintField(evt, channeltypes.AttributeKeySequence), - SourcePort: getField(evt, channeltypes.AttributeKeySrcPort), - SourceChannel: getField(evt, channeltypes.AttributeKeySrcChannel), - DestinationPort: getField(evt, channeltypes.AttributeKeyDstPort), - DestinationChannel: getField(evt, channeltypes.AttributeKeyDstChannel), - Data: getHexField(evt, channeltypes.AttributeKeyDataHex), - TimeoutHeight: parseTimeoutHeight(getField(evt, channeltypes.AttributeKeyTimeoutHeight)), - TimeoutTimestamp: getUintField(evt, channeltypes.AttributeKeyTimeoutTimestamp), - } -} - -func getHexField(evt abci.Event, key string) []byte { - got := getField(evt, key) - if got == "" { - return nil - } - bz, err := hex.DecodeString(got) - if err != nil { - panic(err) - } - return bz -} - -// return the value for the attribute with the given name -func getField(evt abci.Event, key string) string { - for _, attr := range evt.Attributes { - if attr.Key == key { - return attr.Value - } - } - return "" -} - -func getUintField(evt abci.Event, key string) uint64 { - raw := getField(evt, key) - return toUint64(raw) -} - -func toUint64(raw string) uint64 { - if raw == "" { - return 0 - } - i, err := strconv.ParseUint(raw, 10, 64) - if err != nil { - panic(err) - } - return i -} - -func parseTimeoutHeight(raw string) clienttypes.Height { - chunks := strings.Split(raw, "-") - return clienttypes.Height{ - RevisionNumber: toUint64(chunks[0]), - RevisionHeight: toUint64(chunks[1]), - } -} - -func ParsePortIDFromEvents(events sdk.Events) (string, error) { - for _, ev := range events { - if ev.Type == channeltypes.EventTypeChannelOpenInit || ev.Type == channeltypes.EventTypeChannelOpenTry { - for _, attr := range ev.Attributes { - if attr.Key == channeltypes.AttributeKeyPortID { - return attr.Value, nil - } - } - } - } - return "", fmt.Errorf("port id event attribute not found") -} - -func ParseChannelVersionFromEvents(events sdk.Events) (string, error) { - for _, ev := range events { - if ev.Type == channeltypes.EventTypeChannelOpenInit || ev.Type == channeltypes.EventTypeChannelOpenTry { - for _, attr := range ev.Attributes { - if attr.Key == channeltypes.AttributeVersion { - return attr.Value, nil - } - } - } - } - return "", fmt.Errorf("version event attribute not found") -} diff --git a/x/wasm/ibctesting/faucet.go b/x/wasm/ibctesting/faucet.go deleted file mode 100644 index 46da6c3..0000000 --- a/x/wasm/ibctesting/faucet.go +++ /dev/null @@ -1,53 +0,0 @@ -package ibctesting - -import ( - "cosmossdk.io/math" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" - sdk "github.com/cosmos/cosmos-sdk/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/app" -) - -// Fund an address with the given amount in default denom -func (chain *TestChain) Fund(addr sdk.AccAddress, amount math.Int) { - require.NoError(chain.t, chain.sendMsgs(&banktypes.MsgSend{ - FromAddress: chain.SenderAccount.GetAddress().String(), - ToAddress: addr.String(), - Amount: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, amount)), - })) -} - -// SendNonDefaultSenderMsgs delivers a transaction through the application. It returns the result and error if one -// occurred. -func (chain *TestChain) SendNonDefaultSenderMsgs(senderPrivKey cryptotypes.PrivKey, msgs ...sdk.Msg) (*sdk.Result, error) { - require.NotEqual(chain.t, chain.SenderPrivKey, senderPrivKey, "use SendMsgs method") - - // ensure the chain has the latest time - chain.Coordinator.UpdateTimeForChain(chain) - - addr := sdk.AccAddress(senderPrivKey.PubKey().Address().Bytes()) - account := chain.App.AccountKeeper.GetAccount(chain.GetContext(), addr) - require.NotNil(chain.t, account) - _, r, err := app.SignAndDeliverWithoutCommit( - chain.t, - chain.TxConfig, - chain.App.BaseApp, - chain.GetContext().BlockHeader(), - msgs, - chain.ChainID, - []uint64{account.GetAccountNumber()}, - []uint64{account.GetSequence()}, - senderPrivKey, - ) - - // SignAndDeliverWithoutCommit calls app.Commit() - chain.NextBlock() - chain.Coordinator.IncrementTime() - if err != nil { - return r, err - } - chain.CaptureIBCEvents(r) - return r, nil -} diff --git a/x/wasm/ibctesting/path.go b/x/wasm/ibctesting/path.go deleted file mode 100644 index c7f1af8..0000000 --- a/x/wasm/ibctesting/path.go +++ /dev/null @@ -1,109 +0,0 @@ -package ibctesting - -import ( - "bytes" - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - ibctesting "github.com/cosmos/ibc-go/v7/testing" -) - -// Path contains two endpoints representing two chains connected over IBC -type Path struct { - EndpointA *Endpoint - EndpointB *Endpoint -} - -// NewPath constructs an endpoint for each chain using the default values -// for the endpoints. Each endpoint is updated to have a pointer to the -// counterparty endpoint. -func NewPath(chainA, chainB *TestChain) *Path { - endpointA := NewDefaultEndpoint(chainA) - endpointB := NewDefaultEndpoint(chainB) - - endpointA.Counterparty = endpointB - endpointB.Counterparty = endpointA - - return &Path{ - EndpointA: endpointA, - EndpointB: endpointB, - } -} - -// SetChannelOrdered sets the channel order for both endpoints to ORDERED. -func (path *Path) SetChannelOrdered() { - path.EndpointA.ChannelConfig.Order = channeltypes.ORDERED - path.EndpointB.ChannelConfig.Order = channeltypes.ORDERED -} - -// RelayPacket attempts to relay the packet first on EndpointA and then on EndpointB -// if EndpointA does not contain a packet commitment for that packet. An error is returned -// if a relay step fails or the packet commitment does not exist on either endpoint. -func (path *Path) RelayPacket(packet channeltypes.Packet, _ []byte) error { - pc := path.EndpointA.Chain.App.IBCKeeper.ChannelKeeper.GetPacketCommitment(path.EndpointA.Chain.GetContext(), packet.GetSourcePort(), packet.GetSourceChannel(), packet.GetSequence()) - if bytes.Equal(pc, channeltypes.CommitPacket(path.EndpointA.Chain.App.AppCodec(), packet)) { - - // packet found, relay from A to B - if err := path.EndpointB.UpdateClient(); err != nil { - return err - } - - res, err := path.EndpointB.RecvPacketWithResult(packet) - if err != nil { - return err - } - - ack, err := ibctesting.ParseAckFromEvents(res.GetEvents()) - if err != nil { - return err - } - - err = path.EndpointA.AcknowledgePacket(packet, ack) - - return err - } - - pc = path.EndpointB.Chain.App.IBCKeeper.ChannelKeeper.GetPacketCommitment(path.EndpointB.Chain.GetContext(), packet.GetSourcePort(), packet.GetSourceChannel(), packet.GetSequence()) - if bytes.Equal(pc, channeltypes.CommitPacket(path.EndpointB.Chain.App.AppCodec(), packet)) { - - // packet found, relay B to A - if err := path.EndpointA.UpdateClient(); err != nil { - return err - } - - res, err := path.EndpointA.RecvPacketWithResult(packet) - if err != nil { - return err - } - - ack, err := ibctesting.ParseAckFromEvents(res.GetEvents()) - if err != nil { - return err - } - - err = path.EndpointB.AcknowledgePacket(packet, ack) - return err - } - - return fmt.Errorf("packet commitment does not exist on either endpoint for provided packet") -} - -// SendMsg delivers the provided messages to the chain. The counterparty -// client is updated with the new source consensus state. -func (path *Path) SendMsg(msgs ...sdk.Msg) error { - if err := path.EndpointA.Chain.sendMsgs(msgs...); err != nil { - return err - } - if err := path.EndpointA.UpdateClient(); err != nil { - return err - } - return path.EndpointB.UpdateClient() -} - -func (path *Path) Invert() *Path { - return &Path{ - EndpointA: path.EndpointB, - EndpointB: path.EndpointA, - } -} diff --git a/x/wasm/ibctesting/wasm.go b/x/wasm/ibctesting/wasm.go deleted file mode 100644 index d8e5b50..0000000 --- a/x/wasm/ibctesting/wasm.go +++ /dev/null @@ -1,129 +0,0 @@ -package ibctesting - -import ( - "bytes" - "compress/gzip" - "encoding/json" - "fmt" - "os" - "strings" - - ibctesting "github.com/cosmos/ibc-go/v7/testing" - - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cometbft/cometbft/libs/rand" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/gogoproto/proto" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -var wasmIdent = []byte("\x00\x61\x73\x6D") - -// SeedNewContractInstance stores some wasm code and instantiates a new contract on this chain. -// This method can be called to prepare the store with some valid CodeInfo and ContractInfo. The returned -// Address is the contract address for this instance. Test should make use of this data and/or use NewIBCContractMockWasmer -// for using a contract mock in Go. -func (chain *TestChain) SeedNewContractInstance() sdk.AccAddress { - pInstResp := chain.StoreCode(append(wasmIdent, rand.Bytes(10)...)) - codeID := pInstResp.CodeID - - anyAddressStr := chain.SenderAccount.GetAddress().String() - initMsg := []byte(fmt.Sprintf(`{"verifier": %q, "beneficiary": %q}`, anyAddressStr, anyAddressStr)) - return chain.InstantiateContract(codeID, initMsg) -} - -func (chain *TestChain) StoreCodeFile(filename string) types.MsgStoreCodeResponse { - wasmCode, err := os.ReadFile(filename) - require.NoError(chain.t, err) - if strings.HasSuffix(filename, "wasm") { // compress for gas limit - var buf bytes.Buffer - gz := gzip.NewWriter(&buf) - _, err := gz.Write(wasmCode) - require.NoError(chain.t, err) - err = gz.Close() - require.NoError(chain.t, err) - wasmCode = buf.Bytes() - } - return chain.StoreCode(wasmCode) -} - -func (chain *TestChain) StoreCode(byteCode []byte) types.MsgStoreCodeResponse { - storeMsg := &types.MsgStoreCode{ - Sender: chain.SenderAccount.GetAddress().String(), - WASMByteCode: byteCode, - } - r, err := chain.SendMsgs(storeMsg) - require.NoError(chain.t, err) - // unmarshal protobuf response from data - require.Len(chain.t, r.MsgResponses, 1) - require.NotEmpty(chain.t, r.MsgResponses[0].GetCachedValue()) - pInstResp := r.MsgResponses[0].GetCachedValue().(*types.MsgStoreCodeResponse) - require.NotEmpty(chain.t, pInstResp.CodeID) - require.NotEmpty(chain.t, pInstResp.Checksum) - return *pInstResp -} - -func (chain *TestChain) InstantiateContract(codeID uint64, initMsg []byte) sdk.AccAddress { - instantiateMsg := &types.MsgInstantiateContract{ - Sender: chain.SenderAccount.GetAddress().String(), - Admin: chain.SenderAccount.GetAddress().String(), - CodeID: codeID, - Label: "ibc-test", - Msg: initMsg, - Funds: sdk.Coins{ibctesting.TestCoin}, - } - - r, err := chain.SendMsgs(instantiateMsg) - require.NoError(chain.t, err) - require.Len(chain.t, r.MsgResponses, 1) - require.NotEmpty(chain.t, r.MsgResponses[0].GetCachedValue()) - pExecResp := r.MsgResponses[0].GetCachedValue().(*types.MsgInstantiateContractResponse) - a, err := sdk.AccAddressFromBech32(pExecResp.Address) - require.NoError(chain.t, err) - return a -} - -// SmartQuery This will serialize the query message and submit it to the contract. -// The response is parsed into the provided interface. -// Usage: SmartQuery(addr, QueryMsg{Foo: 1}, &response) -func (chain *TestChain) SmartQuery(contractAddr string, queryMsg interface{}, response interface{}) error { - msg, err := json.Marshal(queryMsg) - if err != nil { - return err - } - - req := types.QuerySmartContractStateRequest{ - Address: contractAddr, - QueryData: msg, - } - reqBin, err := proto.Marshal(&req) - if err != nil { - return err - } - - // TODO: what is the query? - res := chain.App.Query(abci.RequestQuery{ - Path: "/cosmwasm.wasm.v1.Query/SmartContractState", - Data: reqBin, - }) - - if res.Code != 0 { - return fmt.Errorf("query failed: (%d) %s", res.Code, res.Log) - } - - // unpack protobuf - var resp types.QuerySmartContractStateResponse - err = proto.Unmarshal(res.Value, &resp) - if err != nil { - return err - } - // unpack json content - return json.Unmarshal(resp.Data, response) -} - -// ContractInfo is a helper function to returns the ContractInfo for the given contract address -func (chain *TestChain) ContractInfo(contractAddr sdk.AccAddress) *types.ContractInfo { - return chain.App.WasmKeeper.GetContractInfo(chain.GetContext(), contractAddr) -} diff --git a/x/wasm/ioutils/ioutil.go b/x/wasm/ioutils/ioutil.go deleted file mode 100644 index 93adb4f..0000000 --- a/x/wasm/ioutils/ioutil.go +++ /dev/null @@ -1,41 +0,0 @@ -package ioutils - -import ( - "bytes" - "compress/gzip" - "io" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// Uncompress expects a valid gzip source to unpack or fails. See IsGzip -func Uncompress(gzipSrc []byte, limit uint64) ([]byte, error) { - if uint64(len(gzipSrc)) > limit { - return nil, types.ErrLimit - } - zr, err := gzip.NewReader(bytes.NewReader(gzipSrc)) - if err != nil { - return nil, err - } - zr.Multistream(false) - defer zr.Close() - return io.ReadAll(LimitReader(zr, int64(limit))) -} - -// LimitReader returns a Reader that reads from r -// but stops with types.ErrLimit after n bytes. -// The underlying implementation is a *io.LimitedReader. -func LimitReader(r io.Reader, n int64) io.Reader { - return &LimitedReader{r: &io.LimitedReader{R: r, N: n}} -} - -type LimitedReader struct { - r *io.LimitedReader -} - -func (l *LimitedReader) Read(p []byte) (n int, err error) { - if l.r.N <= 0 { - return 0, types.ErrLimit - } - return l.r.Read(p) -} diff --git a/x/wasm/ioutils/ioutil_test.go b/x/wasm/ioutils/ioutil_test.go deleted file mode 100644 index 50f1a81..0000000 --- a/x/wasm/ioutils/ioutil_test.go +++ /dev/null @@ -1,82 +0,0 @@ -package ioutils - -import ( - "bytes" - "compress/gzip" - "errors" - "io" - "os" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestUncompress(t *testing.T) { - wasmRaw, err := os.ReadFile("../keeper/testdata/hackatom.wasm") - require.NoError(t, err) - - wasmGzipped, err := os.ReadFile("../keeper/testdata/hackatom.wasm.gzip") - require.NoError(t, err) - - const maxSize = 400_000 - - specs := map[string]struct { - src []byte - expError error - expResult []byte - }{ - "handle wasm compressed": { - src: wasmGzipped, - expResult: wasmRaw, - }, - "handle gzip identifier only": { - src: gzipIdent, - expError: io.ErrUnexpectedEOF, - }, - "handle broken gzip": { - src: append(gzipIdent, byte(0x1)), - expError: io.ErrUnexpectedEOF, - }, - "handle incomplete gzip": { - src: wasmGzipped[:len(wasmGzipped)-5], - expError: io.ErrUnexpectedEOF, - }, - "handle limit gzip output": { - src: asGzip(bytes.Repeat([]byte{0x1}, maxSize)), - expResult: bytes.Repeat([]byte{0x1}, maxSize), - }, - "handle big gzip output": { - src: asGzip(bytes.Repeat([]byte{0x1}, maxSize+1)), - expError: types.ErrLimit, - }, - "handle other big gzip output": { - src: asGzip(bytes.Repeat([]byte{0x1}, 2*maxSize)), - expError: types.ErrLimit, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - r, err := Uncompress(spec.src, maxSize) - require.True(t, errors.Is(spec.expError, err), "exp %v got %+v", spec.expError, err) - if spec.expError != nil { - return - } - assert.Equal(t, spec.expResult, r) - }) - } -} - -func asGzip(src []byte) []byte { - var buf bytes.Buffer - zipper := gzip.NewWriter(&buf) - if _, err := io.Copy(zipper, bytes.NewReader(src)); err != nil { - panic(err) - } - if err := zipper.Close(); err != nil { - panic(err) - } - return buf.Bytes() -} diff --git a/x/wasm/ioutils/utils.go b/x/wasm/ioutils/utils.go deleted file mode 100644 index 9c9cd38..0000000 --- a/x/wasm/ioutils/utils.go +++ /dev/null @@ -1,45 +0,0 @@ -package ioutils - -import ( - "bytes" - "compress/gzip" -) - -// Note: []byte can never be const as they are inherently mutable -var ( - // magic bytes to identify gzip. - // See https://www.ietf.org/rfc/rfc1952.txt - // and https://github.com/golang/go/blob/master/src/net/http/sniff.go#L186 - gzipIdent = []byte("\x1F\x8B\x08") - - // magic number for Wasm is "\0asm" - // See https://webassembly.github.io/spec/core/binary/modules.html#binary-module - wasmIdent = []byte("\x00\x61\x73\x6D") -) - -// IsGzip returns checks if the file contents are gzip compressed -func IsGzip(input []byte) bool { - return len(input) >= 3 && bytes.Equal(gzipIdent, input[0:3]) -} - -// IsWasm checks if the file contents are of wasm binary -func IsWasm(input []byte) bool { - return bytes.Equal(input[:4], wasmIdent) -} - -// GzipIt compresses the input ([]byte) -func GzipIt(input []byte) ([]byte, error) { - // Create gzip writer. - var b bytes.Buffer - w := gzip.NewWriter(&b) - _, err := w.Write(input) - if err != nil { - return nil, err - } - err = w.Close() // You must close this first to flush the bytes to the buffer. - if err != nil { - return nil, err - } - - return b.Bytes(), nil -} diff --git a/x/wasm/ioutils/utils_test.go b/x/wasm/ioutils/utils_test.go deleted file mode 100644 index 2dea0c5..0000000 --- a/x/wasm/ioutils/utils_test.go +++ /dev/null @@ -1,68 +0,0 @@ -package ioutils - -import ( - "os" - "testing" - - "github.com/stretchr/testify/require" -) - -func GetTestData() ([]byte, []byte, []byte, error) { - wasmCode, err := os.ReadFile("../keeper/testdata/hackatom.wasm") - if err != nil { - return nil, nil, nil, err - } - - gzipData, err := GzipIt(wasmCode) - if err != nil { - return nil, nil, nil, err - } - - someRandomStr := []byte("hello world") - - return wasmCode, someRandomStr, gzipData, nil -} - -func TestIsWasm(t *testing.T) { - wasmCode, someRandomStr, gzipData, err := GetTestData() - require.NoError(t, err) - - t.Log("should return false for some random string data") - require.False(t, IsWasm(someRandomStr)) - t.Log("should return false for gzip data") - require.False(t, IsWasm(gzipData)) - t.Log("should return true for exact wasm") - require.True(t, IsWasm(wasmCode)) -} - -func TestIsGzip(t *testing.T) { - wasmCode, someRandomStr, gzipData, err := GetTestData() - require.NoError(t, err) - - require.False(t, IsGzip(wasmCode)) - require.False(t, IsGzip(someRandomStr)) - require.False(t, IsGzip(nil)) - require.True(t, IsGzip(gzipData[0:3])) - require.True(t, IsGzip(gzipData)) -} - -func TestGzipIt(t *testing.T) { - wasmCode, someRandomStr, _, err := GetTestData() - originalGzipData := []byte{ - 31, 139, 8, 0, 0, 0, 0, 0, 0, 255, 202, 72, 205, 201, 201, 87, 40, 207, 47, 202, 73, 1, - 4, 0, 0, 255, 255, 133, 17, 74, 13, 11, 0, 0, 0, - } - - require.NoError(t, err) - - t.Log("gzip wasm with no error") - _, err = GzipIt(wasmCode) - require.NoError(t, err) - - t.Log("gzip of a string should return exact gzip data") - strToGzip, err := GzipIt(someRandomStr) - - require.True(t, IsGzip(strToGzip)) - require.NoError(t, err) - require.Equal(t, originalGzipData, strToGzip) -} diff --git a/x/wasm/keeper/addresses.go b/x/wasm/keeper/addresses.go deleted file mode 100644 index 80f8ab5..0000000 --- a/x/wasm/keeper/addresses.go +++ /dev/null @@ -1,76 +0,0 @@ -package keeper - -import ( - "encoding/binary" - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// AddressGenerator abstract address generator to be used for a single contract address -type AddressGenerator func(ctx sdk.Context, codeID uint64, checksum []byte) sdk.AccAddress - -// ClassicAddressGenerator generates a contract address using codeID and instanceID sequence -func (k Keeper) ClassicAddressGenerator() AddressGenerator { - return func(ctx sdk.Context, codeID uint64, _ []byte) sdk.AccAddress { - instanceID := k.autoIncrementID(ctx, types.KeyLastInstanceID) - return BuildContractAddressClassic(codeID, instanceID) - } -} - -// PredicableAddressGenerator generates a predictable contract address -func PredicableAddressGenerator(creator sdk.AccAddress, salt []byte, msg []byte, fixMsg bool) AddressGenerator { - return func(ctx sdk.Context, _ uint64, checksum []byte) sdk.AccAddress { - if !fixMsg { // clear msg to not be included in the address generation - msg = []byte{} - } - return BuildContractAddressPredictable(checksum, creator, salt, msg) - } -} - -// BuildContractAddressClassic builds an sdk account address for a contract. -func BuildContractAddressClassic(codeID, instanceID uint64) sdk.AccAddress { - contractID := make([]byte, 16) - binary.BigEndian.PutUint64(contractID[:8], codeID) - binary.BigEndian.PutUint64(contractID[8:], instanceID) - return address.Module(types.ModuleName, contractID)[:types.ContractAddrLen] -} - -// BuildContractAddressPredictable generates a contract address for the wasm module with len = types.ContractAddrLen using the -// Cosmos SDK address.Module function. -// Internally a key is built containing: -// (len(checksum) | checksum | len(sender_address) | sender_address | len(salt) | salt| len(initMsg) | initMsg). -// -// All method parameter values must be valid and not nil. -func BuildContractAddressPredictable(checksum []byte, creator sdk.AccAddress, salt, initMsg types.RawContractMessage) sdk.AccAddress { - if len(checksum) != 32 { - panic("invalid checksum") - } - if err := sdk.VerifyAddressFormat(creator); err != nil { - panic(fmt.Sprintf("creator: %s", err)) - } - if err := types.ValidateSalt(salt); err != nil { - panic(fmt.Sprintf("salt: %s", err)) - } - if err := initMsg.ValidateBasic(); len(initMsg) != 0 && err != nil { - panic(fmt.Sprintf("initMsg: %s", err)) - } - checksum = UInt64LengthPrefix(checksum) - creator = UInt64LengthPrefix(creator) - salt = UInt64LengthPrefix(salt) - initMsg = UInt64LengthPrefix(initMsg) - key := make([]byte, len(checksum)+len(creator)+len(salt)+len(initMsg)) - copy(key[0:], checksum) - copy(key[len(checksum):], creator) - copy(key[len(checksum)+len(creator):], salt) - copy(key[len(checksum)+len(creator)+len(salt):], initMsg) - return address.Module(types.ModuleName, key)[:types.ContractAddrLen] -} - -// UInt64LengthPrefix prepend big endian encoded byte length -func UInt64LengthPrefix(bz []byte) []byte { - return append(sdk.Uint64ToBigEndian(uint64(len(bz))), bz...) -} diff --git a/x/wasm/keeper/addresses_test.go b/x/wasm/keeper/addresses_test.go deleted file mode 100644 index 399c3e7..0000000 --- a/x/wasm/keeper/addresses_test.go +++ /dev/null @@ -1,432 +0,0 @@ -package keeper - -import ( - "encoding/json" - "fmt" - "testing" - - tmbytes "github.com/cometbft/cometbft/libs/bytes" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" -) - -func TestBuildContractAddress(t *testing.T) { - x, y := sdk.GetConfig().GetBech32AccountAddrPrefix(), sdk.GetConfig().GetBech32AccountPubPrefix() - t.Cleanup(func() { - sdk.GetConfig().SetBech32PrefixForAccount(x, y) - }) - sdk.GetConfig().SetBech32PrefixForAccount("purple", "purple") - - // test vectors generated via cosmjs: https://github.com/cosmos/cosmjs/pull/1253/files - type Spec struct { - In struct { - Checksum tmbytes.HexBytes `json:"checksum"` - Creator sdk.AccAddress `json:"creator"` - Salt tmbytes.HexBytes `json:"salt"` - Msg string `json:"msg"` - } `json:"in"` - Out struct { - Address sdk.AccAddress `json:"address"` - } `json:"out"` - } - var specs []Spec - require.NoError(t, json.Unmarshal([]byte(goldenMasterPredictableContractAddr), &specs)) - require.NotEmpty(t, specs) - for i, spec := range specs { - t.Run(fmt.Sprintf("case %d", i), func(t *testing.T) { - // when - gotAddr := BuildContractAddressPredictable(spec.In.Checksum, spec.In.Creator, spec.In.Salt.Bytes(), []byte(spec.In.Msg)) - - require.Equal(t, spec.Out.Address.String(), gotAddr.String()) - require.NoError(t, sdk.VerifyAddressFormat(gotAddr)) - }) - } -} - -const goldenMasterPredictableContractAddr = `[ - { - "in": { - "checksum": "13a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a5", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvhxf2py", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbcccccccccc", - "salt": "61", - "msg": null - }, - "intermediate": { - "key": "7761736d00000000000000002013a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a500000000000000149999999999aaaaaaaaaabbbbbbbbbbcccccccccc0000000000000001610000000000000000", - "addressData": "5e865d3e45ad3e961f77fd77d46543417ced44d924dc3e079b5415ff6775f847" - }, - "out": { - "address": "purple1t6r960j945lfv8mhl4mage2rg97w63xeynwrupum2s2l7em4lprs9ce5hk" - } - }, - { - "in": { - "checksum": "13a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a5", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvhxf2py", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbcccccccccc", - "salt": "61", - "msg": "{}" - }, - "intermediate": { - "key": "7761736d00000000000000002013a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a500000000000000149999999999aaaaaaaaaabbbbbbbbbbcccccccccc00000000000000016100000000000000027b7d", - "addressData": "0995499608947a5281e2c7ebd71bdb26a1ad981946dad57f6c4d3ee35de77835" - }, - "out": { - "address": "purple1px25n9sgj3a99q0zcl4awx7my6s6mxqegmdd2lmvf5lwxh080q6suttktr" - } - }, - { - "in": { - "checksum": "13a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a5", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvhxf2py", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbcccccccccc", - "salt": "61", - "msg": "{\"some\":123,\"structure\":{\"nested\":[\"ok\",true]}}" - }, - "intermediate": { - "key": "7761736d00000000000000002013a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a500000000000000149999999999aaaaaaaaaabbbbbbbbbbcccccccccc000000000000000161000000000000002f7b22736f6d65223a3132332c22737472756374757265223a7b226e6573746564223a5b226f6b222c747275655d7d7d", - "addressData": "83326e554723b15bac664ceabc8a5887e27003abe9fbd992af8c7bcea4745167" - }, - "out": { - "address": "purple1svexu428ywc4htrxfn4tezjcsl38qqata8aany4033auafr529ns4v254c" - } - }, - { - "in": { - "checksum": "13a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a5", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvhxf2py", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbcccccccccc", - "salt": "aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae", - "msg": null - }, - "intermediate": { - "key": "7761736d00000000000000002013a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a500000000000000149999999999aaaaaaaaaabbbbbbbbbbcccccccccc0000000000000040aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae0000000000000000", - "addressData": "9384c6248c0bb171e306fd7da0993ec1e20eba006452a3a9e078883eb3594564" - }, - "out": { - "address": "purple1jwzvvfyvpwchrccxl476pxf7c83qawsqv3f2820q0zyrav6eg4jqdcq7gc" - } - }, - { - "in": { - "checksum": "13a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a5", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvhxf2py", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbcccccccccc", - "salt": "aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae", - "msg": "{}" - }, - "intermediate": { - "key": "7761736d00000000000000002013a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a500000000000000149999999999aaaaaaaaaabbbbbbbbbbcccccccccc0000000000000040aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae00000000000000027b7d", - "addressData": "9a8d5f98fb186825401a26206158e7a1213311a9b6a87944469913655af52ffb" - }, - "out": { - "address": "purple1n2x4lx8mrp5z2sq6ycsxzk885ysnxydfk658j3zxnyfk2kh49lasesxf6j" - } - }, - { - "in": { - "checksum": "13a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a5", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvhxf2py", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbcccccccccc", - "salt": "aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae", - "msg": "{\"some\":123,\"structure\":{\"nested\":[\"ok\",true]}}" - }, - "intermediate": { - "key": "7761736d00000000000000002013a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a500000000000000149999999999aaaaaaaaaabbbbbbbbbbcccccccccc0000000000000040aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae000000000000002f7b22736f6d65223a3132332c22737472756374757265223a7b226e6573746564223a5b226f6b222c747275655d7d7d", - "addressData": "932f07bc53f7d0b0b43cb5a54ac3e245b205e6ae6f7c1d991dc6af4a2ff9ac18" - }, - "out": { - "address": "purple1jvhs00zn7lgtpdpukkj54slzgkeqte4wda7pmxgac6h55tle4svq8cmp60" - } - }, - { - "in": { - "checksum": "13a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a5", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvmhwamhwaamhwamhwlllsatsy6m", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff", - "salt": "61", - "msg": null - }, - "intermediate": { - "key": "7761736d00000000000000002013a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a500000000000000209999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff0000000000000001610000000000000000", - "addressData": "9725e94f528d8b78d33c25f3dfcd60e6142d8be60ab36f6a5b59036fd51560db" - }, - "out": { - "address": "purple1juj7jn6j3k9h35euyhealntquc2zmzlxp2ek76jmtypkl4g4vrdsfwmwxk" - } - }, - { - "in": { - "checksum": "13a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a5", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvmhwamhwaamhwamhwlllsatsy6m", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff", - "salt": "61", - "msg": "{}" - }, - "intermediate": { - "key": "7761736d00000000000000002013a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a500000000000000209999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff00000000000000016100000000000000027b7d", - "addressData": "b056e539bbaf447ba18f3f13b792970111fc78933eb6700f4d227b5216d63658" - }, - "out": { - "address": "purple1kptw2wdm4az8hgv08ufm0y5hqyglc7yn86m8qr6dyfa4y9kkxevqmkm9q3" - } - }, - { - "in": { - "checksum": "13a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a5", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvmhwamhwaamhwamhwlllsatsy6m", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff", - "salt": "61", - "msg": "{\"some\":123,\"structure\":{\"nested\":[\"ok\",true]}}" - }, - "intermediate": { - "key": "7761736d00000000000000002013a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a500000000000000209999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff000000000000000161000000000000002f7b22736f6d65223a3132332c22737472756374757265223a7b226e6573746564223a5b226f6b222c747275655d7d7d", - "addressData": "6c98434180f052294ff89fb6d2dae34f9f4468b0b8e6e7c002b2a44adee39abd" - }, - "out": { - "address": "purple1djvyxsvq7pfzjnlcn7md9khrf705g69shrnw0sqzk2jy4hhrn27sjh2ysy" - } - }, - { - "in": { - "checksum": "13a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a5", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvmhwamhwaamhwamhwlllsatsy6m", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff", - "salt": "aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae", - "msg": null - }, - "intermediate": { - "key": "7761736d00000000000000002013a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a500000000000000209999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff0000000000000040aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae0000000000000000", - "addressData": "0aaf1c31c5d529d21d898775bc35b3416f47bfd99188c334c6c716102cbd3101" - }, - "out": { - "address": "purple1p2h3cvw9655ay8vfsa6mcddng9h5007ejxyvxdxxcutpqt9axyqsagmmay" - } - }, - { - "in": { - "checksum": "13a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a5", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvmhwamhwaamhwamhwlllsatsy6m", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff", - "salt": "aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae", - "msg": "{}" - }, - "intermediate": { - "key": "7761736d00000000000000002013a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a500000000000000209999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff0000000000000040aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae00000000000000027b7d", - "addressData": "36fe6ab732187cdfed46290b448b32eb7f4798e7a4968b0537de8a842cbf030e" - }, - "out": { - "address": "purple1xmlx4dejrp7dlm2x9y95fzejadl50x885jtgkpfhm69ggt9lqv8qk3vn4f" - } - }, - { - "in": { - "checksum": "13a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a5", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvmhwamhwaamhwamhwlllsatsy6m", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff", - "salt": "aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae", - "msg": "{\"some\":123,\"structure\":{\"nested\":[\"ok\",true]}}" - }, - "intermediate": { - "key": "7761736d00000000000000002013a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a500000000000000209999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff0000000000000040aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae000000000000002f7b22736f6d65223a3132332c22737472756374757265223a7b226e6573746564223a5b226f6b222c747275655d7d7d", - "addressData": "a0d0c942adac6f3e5e7c23116c4c42a24e96e0ab75f53690ec2d3de16067c751" - }, - "out": { - "address": "purple15rgvjs4d43hnuhnuyvgkcnzz5f8fdc9twh6ndy8v9577zcr8cags40l9dt" - } - }, - { - "in": { - "checksum": "1da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvhxf2py", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbcccccccccc", - "salt": "61", - "msg": null - }, - "intermediate": { - "key": "7761736d0000000000000000201da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b00000000000000149999999999aaaaaaaaaabbbbbbbbbbcccccccccc0000000000000001610000000000000000", - "addressData": "b95c467218d408a0f93046f227b6ece7fe18133ff30113db4d2a7becdfeca141" - }, - "out": { - "address": "purple1h9wyvusc6sy2p7fsgmez0dhvullpsyel7vq38k6d9fa7ehlv59qsvnyh36" - } - }, - { - "in": { - "checksum": "1da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvhxf2py", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbcccccccccc", - "salt": "61", - "msg": "{}" - }, - "intermediate": { - "key": "7761736d0000000000000000201da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b00000000000000149999999999aaaaaaaaaabbbbbbbbbbcccccccccc00000000000000016100000000000000027b7d", - "addressData": "23fe45dbbd45dc6cd25244a74b6e99e7a65bf0bac2f2842a05049d37555a3ae6" - }, - "out": { - "address": "purple1y0lytkaaghwxe5jjgjn5km5eu7n9hu96ctegg2s9qjwnw4268tnqxhg60a" - } - }, - { - "in": { - "checksum": "1da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvhxf2py", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbcccccccccc", - "salt": "61", - "msg": "{\"some\":123,\"structure\":{\"nested\":[\"ok\",true]}}" - }, - "intermediate": { - "key": "7761736d0000000000000000201da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b00000000000000149999999999aaaaaaaaaabbbbbbbbbbcccccccccc000000000000000161000000000000002f7b22736f6d65223a3132332c22737472756374757265223a7b226e6573746564223a5b226f6b222c747275655d7d7d", - "addressData": "6faea261ed63baa65b05726269e83b217fa6205dc7d9fb74f9667d004a69c082" - }, - "out": { - "address": "purple1d7h2yc0dvwa2vkc9wf3xn6pmy9l6vgzaclvlka8eve7sqjnfczpqqsdnwu" - } - }, - { - "in": { - "checksum": "1da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvhxf2py", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbcccccccccc", - "salt": "aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae", - "msg": null - }, - "intermediate": { - "key": "7761736d0000000000000000201da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b00000000000000149999999999aaaaaaaaaabbbbbbbbbbcccccccccc0000000000000040aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae0000000000000000", - "addressData": "67a3ab6384729925fdb144574628ce96836fe098d2c6be4e84ac106b2728d96c" - }, - "out": { - "address": "purple1v736kcuyw2vjtld3g3t5v2xwj6pklcyc6trtun5y4sgxkfegm9kq7vgpnt" - } - }, - { - "in": { - "checksum": "1da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvhxf2py", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbcccccccccc", - "salt": "aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae", - "msg": "{}" - }, - "intermediate": { - "key": "7761736d0000000000000000201da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b00000000000000149999999999aaaaaaaaaabbbbbbbbbbcccccccccc0000000000000040aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae00000000000000027b7d", - "addressData": "23a121263bfce05c144f4af86f3d8a9f87dc56f9dc48dbcffc8c5a614da4c661" - }, - "out": { - "address": "purple1ywsjzf3mlns9c9z0ftux70v2n7rac4hem3ydhnlu33dxzndycesssc7x2m" - } - }, - { - "in": { - "checksum": "1da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvhxf2py", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbcccccccccc", - "salt": "aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae", - "msg": "{\"some\":123,\"structure\":{\"nested\":[\"ok\",true]}}" - }, - "intermediate": { - "key": "7761736d0000000000000000201da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b00000000000000149999999999aaaaaaaaaabbbbbbbbbbcccccccccc0000000000000040aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae000000000000002f7b22736f6d65223a3132332c22737472756374757265223a7b226e6573746564223a5b226f6b222c747275655d7d7d", - "addressData": "dd90dba6d6fcd5fb9c9c8f536314eb1bb29cb5aa084b633c5806b926a5636b58" - }, - "out": { - "address": "purple1mkgdhfkkln2lh8yu3afkx98trwefedd2pp9kx0zcq6ujdftrddvq50esay" - } - }, - { - "in": { - "checksum": "1da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvmhwamhwaamhwamhwlllsatsy6m", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff", - "salt": "61", - "msg": null - }, - "intermediate": { - "key": "7761736d0000000000000000201da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b00000000000000209999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff0000000000000001610000000000000000", - "addressData": "547a743022f4f1af05b102f57bf1c1c7d7ee81bae427dc20d36b2c4ec57612ae" - }, - "out": { - "address": "purple123a8gvpz7nc67pd3qt6hhuwpclt7aqd6usnacgxndvkya3tkz2hq5hz38f" - } - }, - { - "in": { - "checksum": "1da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvmhwamhwaamhwamhwlllsatsy6m", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff", - "salt": "61", - "msg": "{}" - }, - "intermediate": { - "key": "7761736d0000000000000000201da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b00000000000000209999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff00000000000000016100000000000000027b7d", - "addressData": "416e169110e4b411bc53162d7503b2bbf14d6b36b1413a4f4c9af622696e9665" - }, - "out": { - "address": "purple1g9hpdygsuj6pr0znzckh2qajh0c566ekk9qn5n6vntmzy6twjejsrl9alk" - } - }, - { - "in": { - "checksum": "1da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvmhwamhwaamhwamhwlllsatsy6m", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff", - "salt": "61", - "msg": "{\"some\":123,\"structure\":{\"nested\":[\"ok\",true]}}" - }, - "intermediate": { - "key": "7761736d0000000000000000201da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b00000000000000209999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff000000000000000161000000000000002f7b22736f6d65223a3132332c22737472756374757265223a7b226e6573746564223a5b226f6b222c747275655d7d7d", - "addressData": "619a0988b92d8796cea91dea63cbb1f1aefa4a6b6ee5c5d1e937007252697220" - }, - "out": { - "address": "purple1vxdqnz9e9kredn4frh4x8ja37xh05jntdmjut50fxuq8y5nfwgsquu9mxh" - } - }, - { - "in": { - "checksum": "1da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvmhwamhwaamhwamhwlllsatsy6m", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff", - "salt": "aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae", - "msg": null - }, - "intermediate": { - "key": "7761736d0000000000000000201da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b00000000000000209999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff0000000000000040aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae0000000000000000", - "addressData": "d8af856a6a04852d19b647ad6d4336eb26e077f740aef1a0331db34d299a885a" - }, - "out": { - "address": "purple1mzhc26n2qjzj6xdkg7kk6sekavnwqalhgzh0rgpnrke562v63pdq8grp8q" - } - }, - { - "in": { - "checksum": "1da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvmhwamhwaamhwamhwlllsatsy6m", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff", - "salt": "aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae", - "msg": "{}" - }, - "intermediate": { - "key": "7761736d0000000000000000201da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b00000000000000209999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff0000000000000040aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae00000000000000027b7d", - "addressData": "c7fb7bea96daab23e416c4fcf328215303005e1d0d5424257335568e5381e33c" - }, - "out": { - "address": "purple1clahh65km24j8eqkcn70x2pp2vpsqhsap42zgftnx4tgu5upuv7q9ywjws" - } - }, - { - "in": { - "checksum": "1da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvmhwamhwaamhwamhwlllsatsy6m", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff", - "salt": "aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae", - "msg": "{\"some\":123,\"structure\":{\"nested\":[\"ok\",true]}}" - }, - "intermediate": { - "key": "7761736d0000000000000000201da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b00000000000000209999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff0000000000000040aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae000000000000002f7b22736f6d65223a3132332c22737472756374757265223a7b226e6573746564223a5b226f6b222c747275655d7d7d", - "addressData": "ccdf9dea141a6c2475870529ab38fae9dec30df28e005894fe6578b66133ab4a" - }, - "out": { - "address": "purple1en0em6s5rfkzgav8q556kw86a80vxr0j3cq93987v4utvcfn4d9q0tql4w" - } - } -] -` diff --git a/x/wasm/keeper/ante.go b/x/wasm/keeper/ante.go deleted file mode 100644 index 27dd580..0000000 --- a/x/wasm/keeper/ante.go +++ /dev/null @@ -1,97 +0,0 @@ -package keeper - -import ( - "encoding/binary" - - storetypes "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// CountTXDecorator ante handler to count the tx position in a block. -type CountTXDecorator struct { - storeKey storetypes.StoreKey -} - -// NewCountTXDecorator constructor -func NewCountTXDecorator(storeKey storetypes.StoreKey) *CountTXDecorator { - return &CountTXDecorator{storeKey: storeKey} -} - -// AnteHandle handler stores a tx counter with current height encoded in the store to let the app handle -// global rollback behavior instead of keeping state in the handler itself. -// The ante handler passes the counter value via sdk.Context upstream. See `types.TXCounter(ctx)` to read the value. -// Simulations don't get a tx counter value assigned. -func (a CountTXDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) { - if simulate { - return next(ctx, tx, simulate) - } - store := ctx.KVStore(a.storeKey) - currentHeight := ctx.BlockHeight() - - var txCounter uint32 // start with 0 - // load counter when exists - if bz := store.Get(types.TXCounterPrefix); bz != nil { - lastHeight, val := decodeHeightCounter(bz) - if currentHeight == lastHeight { - // then use stored counter - txCounter = val - } // else use `0` from above to start with - } - // store next counter value for current height - store.Set(types.TXCounterPrefix, encodeHeightCounter(currentHeight, txCounter+1)) - - return next(types.WithTXCounter(ctx, txCounter), tx, simulate) -} - -func encodeHeightCounter(height int64, counter uint32) []byte { - b := make([]byte, 4) - binary.BigEndian.PutUint32(b, counter) - return append(sdk.Uint64ToBigEndian(uint64(height)), b...) -} - -func decodeHeightCounter(bz []byte) (int64, uint32) { - return int64(sdk.BigEndianToUint64(bz[0:8])), binary.BigEndian.Uint32(bz[8:]) -} - -// LimitSimulationGasDecorator ante decorator to limit gas in simulation calls -type LimitSimulationGasDecorator struct { - gasLimit *sdk.Gas -} - -// NewLimitSimulationGasDecorator constructor accepts nil value to fallback to block gas limit. -func NewLimitSimulationGasDecorator(gasLimit *sdk.Gas) *LimitSimulationGasDecorator { - if gasLimit != nil && *gasLimit == 0 { - panic("gas limit must not be zero") - } - return &LimitSimulationGasDecorator{gasLimit: gasLimit} -} - -// AnteHandle that limits the maximum gas available in simulations only. -// A custom max value can be configured and will be applied when set. The value should not -// exceed the max block gas limit. -// Different values on nodes are not consensus breaking as they affect only -// simulations but may have effect on client user experience. -// -// When no custom value is set then the max block gas is used as default limit. -func (d LimitSimulationGasDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) { - if !simulate { - // Wasm code is not executed in checkTX so that we don't need to limit it further. - // Tendermint rejects the TX afterwards when the tx.gas > max block gas. - // On deliverTX we rely on the tendermint/sdk mechanics that ensure - // tx has gas set and gas < max block gas - return next(ctx, tx, simulate) - } - - // apply custom node gas limit - if d.gasLimit != nil { - return next(ctx.WithGasMeter(sdk.NewGasMeter(*d.gasLimit)), tx, simulate) - } - - // default to max block gas when set, to be on the safe side - if maxGas := ctx.ConsensusParams().GetBlock().MaxGas; maxGas > 0 { - return next(ctx.WithGasMeter(sdk.NewGasMeter(sdk.Gas(maxGas))), tx, simulate) - } - return next(ctx, tx, simulate) -} diff --git a/x/wasm/keeper/ante_test.go b/x/wasm/keeper/ante_test.go deleted file mode 100644 index 0fa3221..0000000 --- a/x/wasm/keeper/ante_test.go +++ /dev/null @@ -1,189 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - dbm "github.com/cometbft/cometbft-db" - "github.com/cometbft/cometbft/libs/log" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/cosmos/cosmos-sdk/store" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/keeper" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestCountTxDecorator(t *testing.T) { - keyWasm := sdk.NewKVStoreKey(types.StoreKey) - db := dbm.NewMemDB() - ms := store.NewCommitMultiStore(db) - ms.MountStoreWithDB(keyWasm, storetypes.StoreTypeIAVL, db) - require.NoError(t, ms.LoadLatestVersion()) - const myCurrentBlockHeight = 100 - - specs := map[string]struct { - setupDB func(t *testing.T, ctx sdk.Context) - simulate bool - nextAssertAnte func(ctx sdk.Context, tx sdk.Tx, simulate bool) (sdk.Context, error) - expErr bool - }{ - "no initial counter set": { - setupDB: func(t *testing.T, ctx sdk.Context) {}, - nextAssertAnte: func(ctx sdk.Context, tx sdk.Tx, simulate bool) (sdk.Context, error) { - gotCounter, ok := types.TXCounter(ctx) - require.True(t, ok) - assert.Equal(t, uint32(0), gotCounter) - // and stored +1 - bz := ctx.MultiStore().GetKVStore(keyWasm).Get(types.TXCounterPrefix) - assert.Equal(t, []byte{0, 0, 0, 0, 0, 0, 0, myCurrentBlockHeight, 0, 0, 0, 1}, bz) - return ctx, nil - }, - }, - "persistent counter incremented - big endian": { - setupDB: func(t *testing.T, ctx sdk.Context) { - bz := []byte{0, 0, 0, 0, 0, 0, 0, myCurrentBlockHeight, 1, 0, 0, 2} - ctx.MultiStore().GetKVStore(keyWasm).Set(types.TXCounterPrefix, bz) - }, - nextAssertAnte: func(ctx sdk.Context, tx sdk.Tx, simulate bool) (sdk.Context, error) { - gotCounter, ok := types.TXCounter(ctx) - require.True(t, ok) - assert.Equal(t, uint32(1<<24+2), gotCounter) - // and stored +1 - bz := ctx.MultiStore().GetKVStore(keyWasm).Get(types.TXCounterPrefix) - assert.Equal(t, []byte{0, 0, 0, 0, 0, 0, 0, myCurrentBlockHeight, 1, 0, 0, 3}, bz) - return ctx, nil - }, - }, - "old height counter replaced": { - setupDB: func(t *testing.T, ctx sdk.Context) { - previousHeight := byte(myCurrentBlockHeight - 1) - bz := []byte{0, 0, 0, 0, 0, 0, 0, previousHeight, 0, 0, 0, 1} - ctx.MultiStore().GetKVStore(keyWasm).Set(types.TXCounterPrefix, bz) - }, - nextAssertAnte: func(ctx sdk.Context, tx sdk.Tx, simulate bool) (sdk.Context, error) { - gotCounter, ok := types.TXCounter(ctx) - require.True(t, ok) - assert.Equal(t, uint32(0), gotCounter) - // and stored +1 - bz := ctx.MultiStore().GetKVStore(keyWasm).Get(types.TXCounterPrefix) - assert.Equal(t, []byte{0, 0, 0, 0, 0, 0, 0, myCurrentBlockHeight, 0, 0, 0, 1}, bz) - return ctx, nil - }, - }, - "simulation not persisted": { - setupDB: func(t *testing.T, ctx sdk.Context) { - }, - simulate: true, - nextAssertAnte: func(ctx sdk.Context, tx sdk.Tx, simulate bool) (sdk.Context, error) { - _, ok := types.TXCounter(ctx) - assert.False(t, ok) - require.True(t, simulate) - // and not stored - assert.False(t, ctx.MultiStore().GetKVStore(keyWasm).Has(types.TXCounterPrefix)) - return ctx, nil - }, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - ctx := sdk.NewContext(ms.CacheMultiStore(), tmproto.Header{ - Height: myCurrentBlockHeight, - Time: time.Date(2021, time.September, 27, 12, 0, 0, 0, time.UTC), - }, false, log.NewNopLogger()) - - spec.setupDB(t, ctx) - var anyTx sdk.Tx - - // when - ante := keeper.NewCountTXDecorator(keyWasm) - _, gotErr := ante.AnteHandle(ctx, anyTx, spec.simulate, spec.nextAssertAnte) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - }) - } -} - -func TestLimitSimulationGasDecorator(t *testing.T) { - var ( - hundred sdk.Gas = 100 - zero sdk.Gas = 0 - ) - specs := map[string]struct { - customLimit *sdk.Gas - consumeGas sdk.Gas - maxBlockGas int64 - simulation bool - expErr interface{} - }{ - "custom limit set": { - customLimit: &hundred, - consumeGas: hundred + 1, - maxBlockGas: -1, - simulation: true, - expErr: sdk.ErrorOutOfGas{Descriptor: "testing"}, - }, - "block limit set": { - maxBlockGas: 100, - consumeGas: hundred + 1, - simulation: true, - expErr: sdk.ErrorOutOfGas{Descriptor: "testing"}, - }, - "no limits set": { - maxBlockGas: -1, - consumeGas: hundred + 1, - simulation: true, - }, - "both limits set, custom applies": { - customLimit: &hundred, - consumeGas: hundred - 1, - maxBlockGas: 10, - simulation: true, - }, - "not a simulation": { - customLimit: &hundred, - consumeGas: hundred + 1, - simulation: false, - }, - "zero custom limit": { - customLimit: &zero, - simulation: true, - expErr: "gas limit must not be zero", - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - nextAnte := consumeGasAnteHandler(spec.consumeGas) - ctx := sdk.Context{}. - WithGasMeter(sdk.NewInfiniteGasMeter()). - WithConsensusParams(&tmproto.ConsensusParams{ - Block: &tmproto.BlockParams{MaxGas: spec.maxBlockGas}, - }) - // when - if spec.expErr != nil { - require.PanicsWithValue(t, spec.expErr, func() { - ante := keeper.NewLimitSimulationGasDecorator(spec.customLimit) - _, err := ante.AnteHandle(ctx, nil, spec.simulation, nextAnte) - require.NoError(t, err) - }) - return - } - ante := keeper.NewLimitSimulationGasDecorator(spec.customLimit) - _, err := ante.AnteHandle(ctx, nil, spec.simulation, nextAnte) - require.NoError(t, err) - }) - } -} - -func consumeGasAnteHandler(gasToConsume sdk.Gas) sdk.AnteHandler { - return func(ctx sdk.Context, tx sdk.Tx, simulate bool) (sdk.Context, error) { - ctx.GasMeter().ConsumeGas(gasToConsume, "testing") - return ctx, nil - } -} diff --git a/x/wasm/keeper/api.go b/x/wasm/keeper/api.go deleted file mode 100644 index 88f3b82..0000000 --- a/x/wasm/keeper/api.go +++ /dev/null @@ -1,43 +0,0 @@ -package keeper - -import ( - wasmvm "github.com/CosmWasm/wasmvm" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - // DefaultGasCostHumanAddress is how much SDK gas we charge to convert to a human address format - DefaultGasCostHumanAddress = 5 - // DefaultGasCostCanonicalAddress is how much SDK gas we charge to convert to a canonical address format - DefaultGasCostCanonicalAddress = 4 - - // DefaultDeserializationCostPerByte The formula should be `len(data) * deserializationCostPerByte` - DefaultDeserializationCostPerByte = 1 -) - -var ( - costHumanize = DefaultGasCostHumanAddress * DefaultGasMultiplier - costCanonical = DefaultGasCostCanonicalAddress * DefaultGasMultiplier - costJSONDeserialization = wasmvmtypes.UFraction{ - Numerator: DefaultDeserializationCostPerByte * DefaultGasMultiplier, - Denominator: 1, - } -) - -func humanAddress(canon []byte) (string, uint64, error) { - if err := sdk.VerifyAddressFormat(canon); err != nil { - return "", costHumanize, err - } - return sdk.AccAddress(canon).String(), costHumanize, nil -} - -func canonicalAddress(human string) ([]byte, uint64, error) { - bz, err := sdk.AccAddressFromBech32(human) - return bz, costCanonical, err -} - -var cosmwasmAPI = wasmvm.GoAPI{ - HumanAddress: humanAddress, - CanonicalAddress: canonicalAddress, -} diff --git a/x/wasm/keeper/authz_policy.go b/x/wasm/keeper/authz_policy.go deleted file mode 100644 index 36308a7..0000000 --- a/x/wasm/keeper/authz_policy.go +++ /dev/null @@ -1,63 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// ChainAccessConfigs chain settings -type ChainAccessConfigs struct { - Upload types.AccessConfig - Instantiate types.AccessConfig -} - -// NewChainAccessConfigs constructor -func NewChainAccessConfigs(upload types.AccessConfig, instantiate types.AccessConfig) ChainAccessConfigs { - return ChainAccessConfigs{Upload: upload, Instantiate: instantiate} -} - -type AuthorizationPolicy interface { - CanCreateCode(chainConfigs ChainAccessConfigs, actor sdk.AccAddress, contractConfig types.AccessConfig) bool - CanInstantiateContract(c types.AccessConfig, actor sdk.AccAddress) bool - CanModifyContract(admin, actor sdk.AccAddress) bool - CanModifyCodeAccessConfig(creator, actor sdk.AccAddress, isSubset bool) bool -} - -type DefaultAuthorizationPolicy struct{} - -func (p DefaultAuthorizationPolicy) CanCreateCode(chainConfigs ChainAccessConfigs, actor sdk.AccAddress, contractConfig types.AccessConfig) bool { - return chainConfigs.Upload.Allowed(actor) && - contractConfig.IsSubset(chainConfigs.Instantiate) -} - -func (p DefaultAuthorizationPolicy) CanInstantiateContract(config types.AccessConfig, actor sdk.AccAddress) bool { - return config.Allowed(actor) -} - -func (p DefaultAuthorizationPolicy) CanModifyContract(admin, actor sdk.AccAddress) bool { - return admin != nil && admin.Equals(actor) -} - -func (p DefaultAuthorizationPolicy) CanModifyCodeAccessConfig(creator, actor sdk.AccAddress, isSubset bool) bool { - return creator != nil && creator.Equals(actor) && isSubset -} - -type GovAuthorizationPolicy struct{} - -// CanCreateCode implements AuthorizationPolicy.CanCreateCode to allow gov actions. Always returns true. -func (p GovAuthorizationPolicy) CanCreateCode(ChainAccessConfigs, sdk.AccAddress, types.AccessConfig) bool { - return true -} - -func (p GovAuthorizationPolicy) CanInstantiateContract(types.AccessConfig, sdk.AccAddress) bool { - return true -} - -func (p GovAuthorizationPolicy) CanModifyContract(sdk.AccAddress, sdk.AccAddress) bool { - return true -} - -func (p GovAuthorizationPolicy) CanModifyCodeAccessConfig(sdk.AccAddress, sdk.AccAddress, bool) bool { - return true -} diff --git a/x/wasm/keeper/authz_policy_test.go b/x/wasm/keeper/authz_policy_test.go deleted file mode 100644 index 0e9c725..0000000 --- a/x/wasm/keeper/authz_policy_test.go +++ /dev/null @@ -1,345 +0,0 @@ -package keeper - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestDefaultAuthzPolicyCanCreateCode(t *testing.T) { - myActorAddress := RandomAccountAddress(t) - otherAddress := RandomAccountAddress(t) - specs := map[string]struct { - chainConfigs ChainAccessConfigs - contractInstConf types.AccessConfig - actor sdk.AccAddress - exp bool - panics bool - }{ - "upload nobody": { - chainConfigs: NewChainAccessConfigs(types.AllowNobody, types.AllowEverybody), - contractInstConf: types.AllowEverybody, - exp: false, - }, - "upload everybody": { - chainConfigs: NewChainAccessConfigs(types.AllowEverybody, types.AllowEverybody), - contractInstConf: types.AllowEverybody, - exp: true, - }, - "upload only address - same": { - chainConfigs: NewChainAccessConfigs(types.AccessTypeOnlyAddress.With(myActorAddress), types.AllowEverybody), - contractInstConf: types.AllowEverybody, - exp: true, - }, - "upload only address - different": { - chainConfigs: NewChainAccessConfigs(types.AccessTypeOnlyAddress.With(otherAddress), types.AllowEverybody), - contractInstConf: types.AllowEverybody, - exp: false, - }, - "upload any address - included": { - chainConfigs: NewChainAccessConfigs(types.AccessTypeAnyOfAddresses.With(otherAddress, myActorAddress), types.AllowEverybody), - contractInstConf: types.AllowEverybody, - exp: true, - }, - "upload any address - not included": { - chainConfigs: NewChainAccessConfigs(types.AccessTypeAnyOfAddresses.With(otherAddress), types.AllowEverybody), - contractInstConf: types.AllowEverybody, - exp: false, - }, - "contract config - subtype": { - chainConfigs: NewChainAccessConfigs(types.AllowEverybody, types.AllowEverybody), - contractInstConf: types.AccessTypeAnyOfAddresses.With(myActorAddress), - exp: true, - }, - "contract config - not subtype": { - chainConfigs: NewChainAccessConfigs(types.AllowEverybody, types.AllowNobody), - contractInstConf: types.AllowEverybody, - exp: false, - }, - "upload undefined config - panics": { - chainConfigs: NewChainAccessConfigs(types.AccessConfig{}, types.AllowEverybody), - contractInstConf: types.AllowEverybody, - panics: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - policy := DefaultAuthorizationPolicy{} - if !spec.panics { - got := policy.CanCreateCode(spec.chainConfigs, myActorAddress, spec.contractInstConf) - assert.Equal(t, spec.exp, got) - return - } - assert.Panics(t, func() { - policy.CanCreateCode(spec.chainConfigs, myActorAddress, spec.contractInstConf) - }) - }) - } -} - -func TestDefaultAuthzPolicyCanInstantiateContract(t *testing.T) { - myActorAddress := RandomAccountAddress(t) - otherAddress := RandomAccountAddress(t) - specs := map[string]struct { - config types.AccessConfig - actor sdk.AccAddress - exp bool - panics bool - }{ - "nobody": { - config: types.AllowNobody, - exp: false, - }, - "everybody": { - config: types.AllowEverybody, - exp: true, - }, - "only address - same": { - config: types.AccessTypeOnlyAddress.With(myActorAddress), - exp: true, - }, - "only address - different": { - config: types.AccessTypeOnlyAddress.With(otherAddress), - exp: false, - }, - "any address - included": { - config: types.AccessTypeAnyOfAddresses.With(otherAddress, myActorAddress), - exp: true, - }, - "any address - not included": { - config: types.AccessTypeAnyOfAddresses.With(otherAddress), - exp: false, - }, - "undefined config - panics": { - config: types.AccessConfig{}, - panics: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - policy := DefaultAuthorizationPolicy{} - if !spec.panics { - got := policy.CanInstantiateContract(spec.config, myActorAddress) - assert.Equal(t, spec.exp, got) - return - } - assert.Panics(t, func() { - policy.CanInstantiateContract(spec.config, myActorAddress) - }) - }) - } -} - -func TestDefaultAuthzPolicyCanModifyContract(t *testing.T) { - myActorAddress := RandomAccountAddress(t) - otherAddress := RandomAccountAddress(t) - - specs := map[string]struct { - admin sdk.AccAddress - exp bool - }{ - "same as actor": { - admin: myActorAddress, - exp: true, - }, - "different admin": { - admin: otherAddress, - exp: false, - }, - "no admin": { - exp: false, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - policy := DefaultAuthorizationPolicy{} - got := policy.CanModifyContract(spec.admin, myActorAddress) - assert.Equal(t, spec.exp, got) - }) - } -} - -func TestDefaultAuthzPolicyCanModifyCodeAccessConfig(t *testing.T) { - myActorAddress := RandomAccountAddress(t) - otherAddress := RandomAccountAddress(t) - - specs := map[string]struct { - admin sdk.AccAddress - subset bool - exp bool - }{ - "same as actor - subset": { - admin: myActorAddress, - subset: true, - exp: true, - }, - "same as actor - not subset": { - admin: myActorAddress, - subset: false, - exp: false, - }, - "different admin": { - admin: otherAddress, - exp: false, - }, - "no admin": { - exp: false, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - policy := DefaultAuthorizationPolicy{} - got := policy.CanModifyCodeAccessConfig(spec.admin, myActorAddress, spec.subset) - assert.Equal(t, spec.exp, got) - }) - } -} - -func TestGovAuthzPolicyCanCreateCode(t *testing.T) { - myActorAddress := RandomAccountAddress(t) - otherAddress := RandomAccountAddress(t) - specs := map[string]struct { - chainConfigs ChainAccessConfigs - contractInstConf types.AccessConfig - actor sdk.AccAddress - }{ - "upload nobody": { - chainConfigs: NewChainAccessConfigs(types.AllowNobody, types.AllowEverybody), - contractInstConf: types.AllowEverybody, - }, - "upload everybody": { - chainConfigs: NewChainAccessConfigs(types.AllowEverybody, types.AllowEverybody), - contractInstConf: types.AllowEverybody, - }, - "upload only address - same": { - chainConfigs: NewChainAccessConfigs(types.AccessTypeOnlyAddress.With(myActorAddress), types.AllowEverybody), - contractInstConf: types.AllowEverybody, - }, - "upload only address - different": { - chainConfigs: NewChainAccessConfigs(types.AccessTypeOnlyAddress.With(otherAddress), types.AllowEverybody), - contractInstConf: types.AllowEverybody, - }, - "upload any address - included": { - chainConfigs: NewChainAccessConfigs(types.AccessTypeAnyOfAddresses.With(otherAddress, myActorAddress), types.AllowEverybody), - contractInstConf: types.AllowEverybody, - }, - "upload any address - not included": { - chainConfigs: NewChainAccessConfigs(types.AccessTypeAnyOfAddresses.With(otherAddress), types.AllowEverybody), - contractInstConf: types.AllowEverybody, - }, - "contract config - subtype": { - chainConfigs: NewChainAccessConfigs(types.AllowEverybody, types.AllowEverybody), - contractInstConf: types.AccessTypeAnyOfAddresses.With(myActorAddress), - }, - "contract config - not subtype": { - chainConfigs: NewChainAccessConfigs(types.AllowEverybody, types.AllowNobody), - contractInstConf: types.AllowEverybody, - }, - "upload undefined config - not panics": { - chainConfigs: NewChainAccessConfigs(types.AccessConfig{}, types.AllowEverybody), - contractInstConf: types.AllowEverybody, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - policy := GovAuthorizationPolicy{} - got := policy.CanCreateCode(spec.chainConfigs, myActorAddress, spec.contractInstConf) - assert.True(t, got) - }) - } -} - -func TestGovAuthzPolicyCanInstantiateContract(t *testing.T) { - myActorAddress := RandomAccountAddress(t) - otherAddress := RandomAccountAddress(t) - specs := map[string]struct { - config types.AccessConfig - actor sdk.AccAddress - }{ - "nobody": { - config: types.AllowNobody, - }, - "everybody": { - config: types.AllowEverybody, - }, - "only address - same": { - config: types.AccessTypeOnlyAddress.With(myActorAddress), - }, - "only address - different": { - config: types.AccessTypeOnlyAddress.With(otherAddress), - }, - "any address - included": { - config: types.AccessTypeAnyOfAddresses.With(otherAddress, myActorAddress), - }, - "any address - not included": { - config: types.AccessTypeAnyOfAddresses.With(otherAddress), - }, - "undefined config - panics": { - config: types.AccessConfig{}, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - policy := GovAuthorizationPolicy{} - got := policy.CanInstantiateContract(spec.config, myActorAddress) - assert.True(t, got) - }) - } -} - -func TestGovAuthzPolicyCanModifyContract(t *testing.T) { - myActorAddress := RandomAccountAddress(t) - otherAddress := RandomAccountAddress(t) - - specs := map[string]struct { - admin sdk.AccAddress - }{ - "same as actor": { - admin: myActorAddress, - }, - "different admin": { - admin: otherAddress, - }, - "no admin": {}, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - policy := GovAuthorizationPolicy{} - got := policy.CanModifyContract(spec.admin, myActorAddress) - assert.True(t, got) - }) - } -} - -func TestGovAuthzPolicyCanModifyCodeAccessConfig(t *testing.T) { - myActorAddress := RandomAccountAddress(t) - otherAddress := RandomAccountAddress(t) - - specs := map[string]struct { - admin sdk.AccAddress - subset bool - }{ - "same as actor - subset": { - admin: myActorAddress, - subset: true, - }, - "same as actor - not subset": { - admin: myActorAddress, - subset: false, - }, - "different admin": { - admin: otherAddress, - }, - "no admin": {}, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - policy := GovAuthorizationPolicy{} - got := policy.CanModifyCodeAccessConfig(spec.admin, myActorAddress, spec.subset) - assert.True(t, got) - }) - } -} diff --git a/x/wasm/keeper/bench_test.go b/x/wasm/keeper/bench_test.go deleted file mode 100644 index 2780665..0000000 --- a/x/wasm/keeper/bench_test.go +++ /dev/null @@ -1,102 +0,0 @@ -package keeper - -import ( - "os" - "testing" - - dbm "github.com/cometbft/cometbft-db" - "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// BenchmarkVerification benchmarks secp256k1 verification which is 1000 gas based on cpu time. -// -// Just this function is copied from -// https://github.com/cosmos/cosmos-sdk/blob/90e9370bd80d9a3d41f7203ddb71166865561569/crypto/keys/internal/benchmarking/bench.go#L48-L62 -// And thus under the GO license (BSD style) -func BenchmarkGasNormalization(b *testing.B) { - priv := secp256k1.GenPrivKey() - pub := priv.PubKey() - - // use a short message, so this time doesn't get dominated by hashing. - message := []byte("Hello, world!") - signature, err := priv.Sign(message) - if err != nil { - b.Fatal(err) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - pub.VerifySignature(message, signature) - } -} - -// By comparing the timing for queries on pinned vs unpinned, the difference gives us the overhead of -// instantiating an unpinned contract. That value can be used to determine a reasonable gas price -// for the InstantiationCost -func BenchmarkInstantiationOverhead(b *testing.B) { - specs := map[string]struct { - pinned bool - db func() dbm.DB - }{ - "unpinned, memory db": { - db: func() dbm.DB { return dbm.NewMemDB() }, - }, - "pinned, memory db": { - db: func() dbm.DB { return dbm.NewMemDB() }, - pinned: true, - }, - } - for name, spec := range specs { - b.Run(name, func(b *testing.B) { - wasmConfig := types.WasmConfig{MemoryCacheSize: 0} - ctx, keepers := createTestInput(b, false, AvailableCapabilities, wasmConfig, spec.db()) - example := InstantiateHackatomExampleContract(b, ctx, keepers) - if spec.pinned { - require.NoError(b, keepers.ContractKeeper.PinCode(ctx, example.CodeID)) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - _, err := keepers.WasmKeeper.QuerySmart(ctx, example.Contract, []byte(`{"verifier":{}}`)) - require.NoError(b, err) - } - }) - } -} - -// Calculate the time it takes to compile some wasm code the first time. -// This will help us adjust pricing for UploadCode -func BenchmarkCompilation(b *testing.B) { - specs := map[string]struct { - wasmFile string - }{ - "hackatom": { - wasmFile: "./testdata/hackatom.wasm", - }, - "burner": { - wasmFile: "./testdata/burner.wasm", - }, - "ibc_reflect": { - wasmFile: "./testdata/ibc_reflect.wasm", - }, - } - - for name, spec := range specs { - b.Run(name, func(b *testing.B) { - wasmConfig := types.WasmConfig{MemoryCacheSize: 0} - db := dbm.NewMemDB() - ctx, keepers := createTestInput(b, false, AvailableCapabilities, wasmConfig, db) - - // print out code size for comparisons - code, err := os.ReadFile(spec.wasmFile) - require.NoError(b, err) - b.Logf("\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b(size: %d) ", len(code)) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - _ = StoreExampleContract(b, ctx, keepers, spec.wasmFile) - } - }) - } -} diff --git a/x/wasm/keeper/contract_keeper.go b/x/wasm/keeper/contract_keeper.go deleted file mode 100644 index 2a74039..0000000 --- a/x/wasm/keeper/contract_keeper.go +++ /dev/null @@ -1,130 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -var _ types.ContractOpsKeeper = PermissionedKeeper{} - -// decoratedKeeper contains a subset of the wasm keeper that are already or can be guarded by an authorization policy in the future -type decoratedKeeper interface { - create(ctx sdk.Context, creator sdk.AccAddress, wasmCode []byte, instantiateAccess *types.AccessConfig, authZ AuthorizationPolicy) (codeID uint64, checksum []byte, err error) - - instantiate( - ctx sdk.Context, - codeID uint64, - creator, admin sdk.AccAddress, - initMsg []byte, - label string, - deposit sdk.Coins, - addressGenerator AddressGenerator, - authZ AuthorizationPolicy, - ) (sdk.AccAddress, []byte, error) - - migrate(ctx sdk.Context, contractAddress sdk.AccAddress, caller sdk.AccAddress, newCodeID uint64, msg []byte, authZ AuthorizationPolicy) ([]byte, error) - setContractAdmin(ctx sdk.Context, contractAddress, caller, newAdmin sdk.AccAddress, authZ AuthorizationPolicy) error - pinCode(ctx sdk.Context, codeID uint64) error - unpinCode(ctx sdk.Context, codeID uint64) error - execute(ctx sdk.Context, contractAddress sdk.AccAddress, caller sdk.AccAddress, msg []byte, coins sdk.Coins) ([]byte, error) - Sudo(ctx sdk.Context, contractAddress sdk.AccAddress, msg []byte) ([]byte, error) - setContractInfoExtension(ctx sdk.Context, contract sdk.AccAddress, extra types.ContractInfoExtension) error - setAccessConfig(ctx sdk.Context, codeID uint64, caller sdk.AccAddress, newConfig types.AccessConfig, autz AuthorizationPolicy) error - ClassicAddressGenerator() AddressGenerator -} - -type PermissionedKeeper struct { - authZPolicy AuthorizationPolicy - nested decoratedKeeper -} - -func NewPermissionedKeeper(nested decoratedKeeper, authZPolicy AuthorizationPolicy) *PermissionedKeeper { - return &PermissionedKeeper{authZPolicy: authZPolicy, nested: nested} -} - -func NewGovPermissionKeeper(nested decoratedKeeper) *PermissionedKeeper { - return NewPermissionedKeeper(nested, GovAuthorizationPolicy{}) -} - -func NewDefaultPermissionKeeper(nested decoratedKeeper) *PermissionedKeeper { - return NewPermissionedKeeper(nested, DefaultAuthorizationPolicy{}) -} - -func (p PermissionedKeeper) Create(ctx sdk.Context, creator sdk.AccAddress, wasmCode []byte, instantiateAccess *types.AccessConfig) (codeID uint64, checksum []byte, err error) { - return p.nested.create(ctx, creator, wasmCode, instantiateAccess, p.authZPolicy) -} - -// Instantiate creates an instance of a WASM contract using the classic sequence based address generator -func (p PermissionedKeeper) Instantiate( - ctx sdk.Context, - codeID uint64, - creator, admin sdk.AccAddress, - initMsg []byte, - label string, - deposit sdk.Coins, -) (sdk.AccAddress, []byte, error) { - return p.nested.instantiate(ctx, codeID, creator, admin, initMsg, label, deposit, p.nested.ClassicAddressGenerator(), p.authZPolicy) -} - -// Instantiate2 creates an instance of a WASM contract using the predictable address generator -func (p PermissionedKeeper) Instantiate2( - ctx sdk.Context, - codeID uint64, - creator, admin sdk.AccAddress, - initMsg []byte, - label string, - deposit sdk.Coins, - salt []byte, - fixMsg bool, -) (sdk.AccAddress, []byte, error) { - return p.nested.instantiate( - ctx, - codeID, - creator, - admin, - initMsg, - label, - deposit, - PredicableAddressGenerator(creator, salt, initMsg, fixMsg), - p.authZPolicy, - ) -} - -func (p PermissionedKeeper) Execute(ctx sdk.Context, contractAddress sdk.AccAddress, caller sdk.AccAddress, msg []byte, coins sdk.Coins) ([]byte, error) { - return p.nested.execute(ctx, contractAddress, caller, msg, coins) -} - -func (p PermissionedKeeper) Migrate(ctx sdk.Context, contractAddress sdk.AccAddress, caller sdk.AccAddress, newCodeID uint64, msg []byte) ([]byte, error) { - return p.nested.migrate(ctx, contractAddress, caller, newCodeID, msg, p.authZPolicy) -} - -func (p PermissionedKeeper) Sudo(ctx sdk.Context, contractAddress sdk.AccAddress, msg []byte) ([]byte, error) { - return p.nested.Sudo(ctx, contractAddress, msg) -} - -func (p PermissionedKeeper) UpdateContractAdmin(ctx sdk.Context, contractAddress sdk.AccAddress, caller sdk.AccAddress, newAdmin sdk.AccAddress) error { - return p.nested.setContractAdmin(ctx, contractAddress, caller, newAdmin, p.authZPolicy) -} - -func (p PermissionedKeeper) ClearContractAdmin(ctx sdk.Context, contractAddress sdk.AccAddress, caller sdk.AccAddress) error { - return p.nested.setContractAdmin(ctx, contractAddress, caller, nil, p.authZPolicy) -} - -func (p PermissionedKeeper) PinCode(ctx sdk.Context, codeID uint64) error { - return p.nested.pinCode(ctx, codeID) -} - -func (p PermissionedKeeper) UnpinCode(ctx sdk.Context, codeID uint64) error { - return p.nested.unpinCode(ctx, codeID) -} - -// SetContractInfoExtension updates the extra attributes that can be stored with the contract info -func (p PermissionedKeeper) SetContractInfoExtension(ctx sdk.Context, contract sdk.AccAddress, extra types.ContractInfoExtension) error { - return p.nested.setContractInfoExtension(ctx, contract, extra) -} - -// SetAccessConfig updates the access config of a code id. -func (p PermissionedKeeper) SetAccessConfig(ctx sdk.Context, codeID uint64, caller sdk.AccAddress, newConfig types.AccessConfig) error { - return p.nested.setAccessConfig(ctx, codeID, caller, newConfig, p.authZPolicy) -} diff --git a/x/wasm/keeper/contract_keeper_test.go b/x/wasm/keeper/contract_keeper_test.go deleted file mode 100644 index aa660d1..0000000 --- a/x/wasm/keeper/contract_keeper_test.go +++ /dev/null @@ -1,169 +0,0 @@ -package keeper - -import ( - "encoding/json" - "fmt" - "math" - "strings" - "testing" - - "github.com/terpnetwork/terp-core/x/wasm/keeper/wasmtesting" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestInstantiate2(t *testing.T) { - parentCtx, keepers := CreateTestInput(t, false, AvailableCapabilities) - parentCtx = parentCtx.WithGasMeter(sdk.NewInfiniteGasMeter()) - - example := StoreHackatomExampleContract(t, parentCtx, keepers) - otherExample := StoreReflectContract(t, parentCtx, keepers) - mock := &wasmtesting.MockWasmer{} - wasmtesting.MakeInstantiable(mock) - keepers.WasmKeeper.wasmVM = mock // set mock to not fail on contract init message - - verifierAddr := RandomAccountAddress(t) - beneficiaryAddr := RandomAccountAddress(t) - initMsg := mustMarshal(t, HackatomExampleInitMsg{Verifier: verifierAddr, Beneficiary: beneficiaryAddr}) - otherAddr := keepers.Faucet.NewFundedRandomAccount(parentCtx, sdk.NewInt64Coin("denom", 1_000_000_000)) - - const ( - mySalt = "my salt" - myLabel = "my label" - ) - // create instances for duplicate checks - exampleContract := func(t *testing.T, ctx sdk.Context, fixMsg bool) { - _, _, err := keepers.ContractKeeper.Instantiate2( - ctx, - example.CodeID, - example.CreatorAddr, - nil, - initMsg, - myLabel, - sdk.NewCoins(sdk.NewInt64Coin("denom", 1)), - []byte(mySalt), - fixMsg, - ) - require.NoError(t, err) - } - exampleWithFixMsg := func(t *testing.T, ctx sdk.Context) { - exampleContract(t, ctx, true) - } - exampleWithoutFixMsg := func(t *testing.T, ctx sdk.Context) { - exampleContract(t, ctx, false) - } - specs := map[string]struct { - setup func(t *testing.T, ctx sdk.Context) - codeID uint64 - sender sdk.AccAddress - salt []byte - initMsg json.RawMessage - fixMsg bool - expErr error - }{ - "fix msg - generates different address than without fixMsg": { - setup: exampleWithoutFixMsg, - codeID: example.CodeID, - sender: example.CreatorAddr, - salt: []byte(mySalt), - initMsg: initMsg, - fixMsg: true, - }, - "fix msg - different sender": { - setup: exampleWithFixMsg, - codeID: example.CodeID, - sender: otherAddr, - salt: []byte(mySalt), - initMsg: initMsg, - fixMsg: true, - }, - "fix msg - different code": { - setup: exampleWithFixMsg, - codeID: otherExample.CodeID, - sender: example.CreatorAddr, - salt: []byte(mySalt), - initMsg: []byte(`{}`), - fixMsg: true, - }, - "fix msg - different salt": { - setup: exampleWithFixMsg, - codeID: example.CodeID, - sender: example.CreatorAddr, - salt: []byte("other salt"), - initMsg: initMsg, - fixMsg: true, - }, - "fix msg - different init msg": { - setup: exampleWithFixMsg, - codeID: example.CodeID, - sender: example.CreatorAddr, - salt: []byte(mySalt), - initMsg: mustMarshal(t, HackatomExampleInitMsg{Verifier: otherAddr, Beneficiary: beneficiaryAddr}), - fixMsg: true, - }, - "different sender": { - setup: exampleWithoutFixMsg, - codeID: example.CodeID, - sender: otherAddr, - salt: []byte(mySalt), - initMsg: initMsg, - }, - "different code": { - setup: exampleWithoutFixMsg, - codeID: otherExample.CodeID, - sender: example.CreatorAddr, - salt: []byte(mySalt), - initMsg: []byte(`{}`), - }, - "different salt": { - setup: exampleWithoutFixMsg, - codeID: example.CodeID, - sender: example.CreatorAddr, - salt: []byte(`other salt`), - initMsg: initMsg, - }, - "different init msg - reject same address": { - setup: exampleWithoutFixMsg, - codeID: example.CodeID, - sender: example.CreatorAddr, - salt: []byte(mySalt), - initMsg: mustMarshal(t, HackatomExampleInitMsg{Verifier: otherAddr, Beneficiary: beneficiaryAddr}), - expErr: types.ErrDuplicate, - }, - "fix msg - long msg": { - setup: exampleWithFixMsg, - codeID: example.CodeID, - sender: otherAddr, - salt: []byte(mySalt), - initMsg: []byte(fmt.Sprintf(`{"foo":%q}`, strings.Repeat("b", math.MaxInt16+1))), // too long kills CI - fixMsg: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - ctx, _ := parentCtx.CacheContext() - spec.setup(t, ctx) - gotAddr, _, gotErr := keepers.ContractKeeper.Instantiate2( - ctx, - spec.codeID, - spec.sender, - nil, - spec.initMsg, - myLabel, - sdk.NewCoins(sdk.NewInt64Coin("denom", 2)), - spec.salt, - spec.fixMsg, - ) - if spec.expErr != nil { - assert.ErrorIs(t, gotErr, spec.expErr) - return - } - require.NoError(t, gotErr) - assert.NotEmpty(t, gotAddr) - }) - } -} diff --git a/x/wasm/keeper/events.go b/x/wasm/keeper/events.go deleted file mode 100644 index 47068aa..0000000 --- a/x/wasm/keeper/events.go +++ /dev/null @@ -1,68 +0,0 @@ -package keeper - -import ( - "fmt" - "strings" - - errorsmod "cosmossdk.io/errors" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// newWasmModuleEvent creates with wasm module event for interacting with the given contract. Adds custom attributes -// to this event. -func newWasmModuleEvent(customAttributes []wasmvmtypes.EventAttribute, contractAddr sdk.AccAddress) (sdk.Events, error) { - attrs, err := contractSDKEventAttributes(customAttributes, contractAddr) - if err != nil { - return nil, err - } - - // each wasm invocation always returns one sdk.Event - return sdk.Events{sdk.NewEvent(types.WasmModuleEventType, attrs...)}, nil -} - -const eventTypeMinLength = 2 - -// newCustomEvents converts wasmvm events from a contract response to sdk type events -func newCustomEvents(evts wasmvmtypes.Events, contractAddr sdk.AccAddress) (sdk.Events, error) { - events := make(sdk.Events, 0, len(evts)) - for _, e := range evts { - typ := strings.TrimSpace(e.Type) - if len(typ) <= eventTypeMinLength { - return nil, errorsmod.Wrap(types.ErrInvalidEvent, fmt.Sprintf("Event type too short: '%s'", typ)) - } - attributes, err := contractSDKEventAttributes(e.Attributes, contractAddr) - if err != nil { - return nil, err - } - events = append(events, sdk.NewEvent(fmt.Sprintf("%s%s", types.CustomContractEventPrefix, typ), attributes...)) - } - return events, nil -} - -// convert and add contract address issuing this event -func contractSDKEventAttributes(customAttributes []wasmvmtypes.EventAttribute, contractAddr sdk.AccAddress) ([]sdk.Attribute, error) { - attrs := []sdk.Attribute{sdk.NewAttribute(types.AttributeKeyContractAddr, contractAddr.String())} - // append attributes from wasm to the sdk.Event - for _, l := range customAttributes { - // ensure key and value are non-empty (and trim what is there) - key := strings.TrimSpace(l.Key) - if len(key) == 0 { - return nil, errorsmod.Wrap(types.ErrInvalidEvent, fmt.Sprintf("Empty attribute key. Value: %s", l.Value)) - } - value := strings.TrimSpace(l.Value) - // TODO: check if this is legal in the SDK - if it is, we can remove this check - if len(value) == 0 { - return nil, errorsmod.Wrap(types.ErrInvalidEvent, fmt.Sprintf("Empty attribute value. Key: %s", key)) - } - // and reserve all _* keys for our use (not contract) - if strings.HasPrefix(key, types.AttributeReservedPrefix) { - return nil, errorsmod.Wrap(types.ErrInvalidEvent, fmt.Sprintf("Attribute key starts with reserved prefix %s: '%s'", types.AttributeReservedPrefix, key)) - } - attrs = append(attrs, sdk.NewAttribute(key, value)) - } - return attrs, nil -} diff --git a/x/wasm/keeper/events_test.go b/x/wasm/keeper/events_test.go deleted file mode 100644 index 5320b28..0000000 --- a/x/wasm/keeper/events_test.go +++ /dev/null @@ -1,290 +0,0 @@ -package keeper - -import ( - "context" - "testing" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestHasWasmModuleEvent(t *testing.T) { - myContractAddr := RandomAccountAddress(t) - specs := map[string]struct { - srcEvents []sdk.Event - exp bool - }{ - "event found": { - srcEvents: []sdk.Event{ - sdk.NewEvent(types.WasmModuleEventType, sdk.NewAttribute("_contract_address", myContractAddr.String())), - }, - exp: true, - }, - "different event: not found": { - srcEvents: []sdk.Event{ - sdk.NewEvent(types.CustomContractEventPrefix, sdk.NewAttribute("_contract_address", myContractAddr.String())), - }, - exp: false, - }, - "event with different address: not found": { - srcEvents: []sdk.Event{ - sdk.NewEvent(types.WasmModuleEventType, sdk.NewAttribute("_contract_address", RandomBech32AccountAddress(t))), - }, - exp: false, - }, - "no event": { - srcEvents: []sdk.Event{}, - exp: false, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - em := sdk.NewEventManager() - em.EmitEvents(spec.srcEvents) - ctx := sdk.Context{}.WithContext(context.Background()).WithEventManager(em) - - got := hasWasmModuleEvent(ctx, myContractAddr) - assert.Equal(t, spec.exp, got) - }) - } -} - -func TestNewCustomEvents(t *testing.T) { - myContract := RandomAccountAddress(t) - specs := map[string]struct { - src wasmvmtypes.Events - exp sdk.Events - isError bool - }{ - "all good": { - src: wasmvmtypes.Events{{ - Type: "foo", - Attributes: []wasmvmtypes.EventAttribute{{Key: "myKey", Value: "myVal"}}, - }}, - exp: sdk.Events{sdk.NewEvent("wasm-foo", - sdk.NewAttribute("_contract_address", myContract.String()), - sdk.NewAttribute("myKey", "myVal"))}, - }, - "multiple attributes": { - src: wasmvmtypes.Events{{ - Type: "foo", - Attributes: []wasmvmtypes.EventAttribute{ - {Key: "myKey", Value: "myVal"}, - {Key: "myOtherKey", Value: "myOtherVal"}, - }, - }}, - exp: sdk.Events{sdk.NewEvent("wasm-foo", - sdk.NewAttribute("_contract_address", myContract.String()), - sdk.NewAttribute("myKey", "myVal"), - sdk.NewAttribute("myOtherKey", "myOtherVal"))}, - }, - "multiple events": { - src: wasmvmtypes.Events{{ - Type: "foo", - Attributes: []wasmvmtypes.EventAttribute{{Key: "myKey", Value: "myVal"}}, - }, { - Type: "bar", - Attributes: []wasmvmtypes.EventAttribute{{Key: "otherKey", Value: "otherVal"}}, - }}, - exp: sdk.Events{ - sdk.NewEvent("wasm-foo", - sdk.NewAttribute("_contract_address", myContract.String()), - sdk.NewAttribute("myKey", "myVal")), - sdk.NewEvent("wasm-bar", - sdk.NewAttribute("_contract_address", myContract.String()), - sdk.NewAttribute("otherKey", "otherVal")), - }, - }, - "without attributes": { - src: wasmvmtypes.Events{{ - Type: "foo", - }}, - exp: sdk.Events{sdk.NewEvent("wasm-foo", - sdk.NewAttribute("_contract_address", myContract.String()))}, - }, - "error on short event type": { - src: wasmvmtypes.Events{{ - Type: "f", - }}, - isError: true, - }, - "error on _contract_address": { - src: wasmvmtypes.Events{{ - Type: "foo", - Attributes: []wasmvmtypes.EventAttribute{{Key: "_contract_address", Value: RandomBech32AccountAddress(t)}}, - }}, - isError: true, - }, - "error on reserved prefix": { - src: wasmvmtypes.Events{{ - Type: "wasm", - Attributes: []wasmvmtypes.EventAttribute{ - {Key: "_reserved", Value: "is skipped"}, - {Key: "normal", Value: "is used"}, - }, - }}, - isError: true, - }, - "error on empty value": { - src: wasmvmtypes.Events{{ - Type: "boom", - Attributes: []wasmvmtypes.EventAttribute{ - {Key: "some", Value: "data"}, - {Key: "key", Value: ""}, - }, - }}, - isError: true, - }, - "error on empty key": { - src: wasmvmtypes.Events{{ - Type: "boom", - Attributes: []wasmvmtypes.EventAttribute{ - {Key: "some", Value: "data"}, - {Key: "", Value: "value"}, - }, - }}, - isError: true, - }, - "error on whitespace type": { - src: wasmvmtypes.Events{{ - Type: " f ", - Attributes: []wasmvmtypes.EventAttribute{ - {Key: "some", Value: "data"}, - }, - }}, - isError: true, - }, - "error on only whitespace key": { - src: wasmvmtypes.Events{{ - Type: "boom", - Attributes: []wasmvmtypes.EventAttribute{ - {Key: "some", Value: "data"}, - {Key: "\n\n\n\n", Value: "value"}, - }, - }}, - isError: true, - }, - "error on only whitespace value": { - src: wasmvmtypes.Events{{ - Type: "boom", - Attributes: []wasmvmtypes.EventAttribute{ - {Key: "some", Value: "data"}, - {Key: "myKey", Value: " \t\r\n"}, - }, - }}, - isError: true, - }, - "strip out whitespace": { - src: wasmvmtypes.Events{{ - Type: " food\n", - Attributes: []wasmvmtypes.EventAttribute{{Key: "my Key", Value: "\tmyVal"}}, - }}, - exp: sdk.Events{sdk.NewEvent("wasm-food", - sdk.NewAttribute("_contract_address", myContract.String()), - sdk.NewAttribute("my Key", "myVal"))}, - }, - "empty event elements": { - src: make(wasmvmtypes.Events, 10), - isError: true, - }, - "nil": { - exp: sdk.Events{}, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - gotEvent, err := newCustomEvents(spec.src, myContract) - if spec.isError { - assert.Error(t, err) - } else { - assert.NoError(t, err) - assert.Equal(t, spec.exp, gotEvent) - } - }) - } -} - -func TestNewWasmModuleEvent(t *testing.T) { - myContract := RandomAccountAddress(t) - specs := map[string]struct { - src []wasmvmtypes.EventAttribute - exp sdk.Events - isError bool - }{ - "all good": { - src: []wasmvmtypes.EventAttribute{{Key: "myKey", Value: "myVal"}}, - exp: sdk.Events{sdk.NewEvent("wasm", - sdk.NewAttribute("_contract_address", myContract.String()), - sdk.NewAttribute("myKey", "myVal"))}, - }, - "multiple attributes": { - src: []wasmvmtypes.EventAttribute{ - {Key: "myKey", Value: "myVal"}, - {Key: "myOtherKey", Value: "myOtherVal"}, - }, - exp: sdk.Events{sdk.NewEvent("wasm", - sdk.NewAttribute("_contract_address", myContract.String()), - sdk.NewAttribute("myKey", "myVal"), - sdk.NewAttribute("myOtherKey", "myOtherVal"))}, - }, - "without attributes": { - exp: sdk.Events{sdk.NewEvent("wasm", - sdk.NewAttribute("_contract_address", myContract.String()))}, - }, - "error on _contract_address": { - src: []wasmvmtypes.EventAttribute{{Key: "_contract_address", Value: RandomBech32AccountAddress(t)}}, - isError: true, - }, - "error on whitespace key": { - src: []wasmvmtypes.EventAttribute{{Key: " ", Value: "value"}}, - isError: true, - }, - "error on whitespace value": { - src: []wasmvmtypes.EventAttribute{{Key: "key", Value: "\n\n\n"}}, - isError: true, - }, - "strip whitespace": { - src: []wasmvmtypes.EventAttribute{{Key: " my-real-key ", Value: "\n\n\nsome-val\t\t\t"}}, - exp: sdk.Events{sdk.NewEvent("wasm", - sdk.NewAttribute("_contract_address", myContract.String()), - sdk.NewAttribute("my-real-key", "some-val"))}, - }, - "empty elements": { - src: make([]wasmvmtypes.EventAttribute, 10), - isError: true, - }, - "nil": { - exp: sdk.Events{sdk.NewEvent("wasm", - sdk.NewAttribute("_contract_address", myContract.String()), - )}, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - gotEvent, err := newWasmModuleEvent(spec.src, myContract) - if spec.isError { - assert.Error(t, err) - } else { - assert.NoError(t, err) - assert.Equal(t, spec.exp, gotEvent) - } - }) - } -} - -// returns true when a wasm module event was emitted for this contract already -func hasWasmModuleEvent(ctx sdk.Context, contractAddr sdk.AccAddress) bool { - for _, e := range ctx.EventManager().Events() { - if e.Type == types.WasmModuleEventType { - for _, a := range e.Attributes { - if a.Key == types.AttributeKeyContractAddr && a.Value == contractAddr.String() { - return true - } - } - } - } - return false -} diff --git a/x/wasm/keeper/gas_register.go b/x/wasm/keeper/gas_register.go deleted file mode 100644 index e26a19a..0000000 --- a/x/wasm/keeper/gas_register.go +++ /dev/null @@ -1,253 +0,0 @@ -package keeper - -import ( - errorsmod "cosmossdk.io/errors" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -const ( - // DefaultGasMultiplier is how many CosmWasm gas points = 1 Cosmos SDK gas point. - // - // CosmWasm gas strategy is documented in https://github.com/CosmWasm/cosmwasm/blob/v1.0.0-beta/docs/GAS.md. - // Cosmos SDK reference costs can be found here: https://github.com/cosmos/cosmos-sdk/blob/v0.42.10/store/types/gas.go#L198-L209. - // - // The original multiplier of 100 up to CosmWasm 0.16 was based on - // "A write at ~3000 gas and ~200us = 10 gas per us (microsecond) cpu/io - // Rough timing have 88k gas at 90us, which is equal to 1k sdk gas... (one read)" - // as well as manual Wasmer benchmarks from 2019. This was then multiplied by 150_000 - // in the 0.16 -> 1.0 upgrade (https://github.com/CosmWasm/cosmwasm/pull/1120). - // - // The multiplier deserves more reproducible benchmarking and a strategy that allows easy adjustments. - // This is tracked in https://github.com/terpnetwork/terp-core/issues/566 and https://github.com/terpnetwork/terp-core/issues/631. - // Gas adjustments are consensus breaking but may happen in any release marked as consensus breaking. - // Do not make assumptions on how much gas an operation will consume in places that are hard to adjust, - // such as hardcoding them in contracts. - // - // Please note that all gas prices returned to wasmvm should have this multiplied. - // Benchmarks and numbers were discussed in: https://github.com/terpnetwork/terp-core/pull/634#issuecomment-938055852 - DefaultGasMultiplier uint64 = 140_000_000 - // DefaultInstanceCost is how much SDK gas we charge each time we load a WASM instance. - // Creating a new instance is costly, and this helps put a recursion limit to contracts calling contracts. - // Benchmarks and numbers were discussed in: https://github.com/terpnetwork/terp-core/pull/634#issuecomment-938056803 - DefaultInstanceCost uint64 = 60_000 - // DefaultCompileCost is how much SDK gas is charged *per byte* for compiling WASM code. - // Benchmarks and numbers were discussed in: https://github.com/terpnetwork/terp-core/pull/634#issuecomment-938056803 - DefaultCompileCost uint64 = 3 - // DefaultEventAttributeDataCost is how much SDK gas is charged *per byte* for attribute data in events. - // This is used with len(key) + len(value) - DefaultEventAttributeDataCost uint64 = 1 - // DefaultContractMessageDataCost is how much SDK gas is charged *per byte* of the message that goes to the contract - // This is used with len(msg). Note that the message is deserialized in the receiving contract and this is charged - // with wasm gas already. The derserialization of results is also charged in wasmvm. I am unsure if we need to add - // additional costs here. - // Note: also used for error fields on reply, and data on reply. Maybe these should be pulled out to a different (non-zero) field - DefaultContractMessageDataCost uint64 = 0 - // DefaultPerAttributeCost is how much SDK gas we charge per attribute count. - DefaultPerAttributeCost uint64 = 10 - // DefaultPerCustomEventCost is how much SDK gas we charge per event count. - DefaultPerCustomEventCost uint64 = 20 - // DefaultEventAttributeDataFreeTier number of bytes of total attribute data we do not charge. - DefaultEventAttributeDataFreeTier = 100 -) - -// default: 0.15 gas. -// see https://github.com/terpnetwork/terp-core/pull/898#discussion_r937727200 -var defaultPerByteUncompressCost = wasmvmtypes.UFraction{ - Numerator: 15, - Denominator: 100, -} - -// DefaultPerByteUncompressCost is how much SDK gas we charge per source byte to unpack -func DefaultPerByteUncompressCost() wasmvmtypes.UFraction { - return defaultPerByteUncompressCost -} - -// GasRegister abstract source for gas costs -type GasRegister interface { - // NewContractInstanceCosts costs to create a new contract instance from code - NewContractInstanceCosts(pinned bool, msgLen int) sdk.Gas - // CompileCosts costs to persist and "compile" a new wasm contract - CompileCosts(byteLength int) sdk.Gas - // UncompressCosts costs to unpack a new wasm contract - UncompressCosts(byteLength int) sdk.Gas - // InstantiateContractCosts costs when interacting with a wasm contract - InstantiateContractCosts(pinned bool, msgLen int) sdk.Gas - // ReplyCosts costs to to handle a message reply - ReplyCosts(pinned bool, reply wasmvmtypes.Reply) sdk.Gas - // EventCosts costs to persist an event - EventCosts(attrs []wasmvmtypes.EventAttribute, events wasmvmtypes.Events) sdk.Gas - // ToWasmVMGas converts from sdk gas to wasmvm gas - ToWasmVMGas(source sdk.Gas) uint64 - // FromWasmVMGas converts from wasmvm gas to sdk gas - FromWasmVMGas(source uint64) sdk.Gas -} - -// WasmGasRegisterConfig config type -type WasmGasRegisterConfig struct { - // InstanceCost costs when interacting with a wasm contract - InstanceCost sdk.Gas - // CompileCosts costs to persist and "compile" a new wasm contract - CompileCost sdk.Gas - // UncompressCost costs per byte to unpack a contract - UncompressCost wasmvmtypes.UFraction - // GasMultiplier is how many cosmwasm gas points = 1 sdk gas point - // SDK reference costs can be found here: https://github.com/cosmos/cosmos-sdk/blob/02c6c9fafd58da88550ab4d7d494724a477c8a68/store/types/gas.go#L153-L164 - GasMultiplier sdk.Gas - // EventPerAttributeCost is how much SDK gas is charged *per byte* for attribute data in events. - // This is used with len(key) + len(value) - EventPerAttributeCost sdk.Gas - // EventAttributeDataCost is how much SDK gas is charged *per byte* for attribute data in events. - // This is used with len(key) + len(value) - EventAttributeDataCost sdk.Gas - // EventAttributeDataFreeTier number of bytes of total attribute data that is free of charge - EventAttributeDataFreeTier uint64 - // ContractMessageDataCost SDK gas charged *per byte* of the message that goes to the contract - // This is used with len(msg) - ContractMessageDataCost sdk.Gas - // CustomEventCost cost per custom event - CustomEventCost uint64 -} - -// DefaultGasRegisterConfig default values -func DefaultGasRegisterConfig() WasmGasRegisterConfig { - return WasmGasRegisterConfig{ - InstanceCost: DefaultInstanceCost, - CompileCost: DefaultCompileCost, - GasMultiplier: DefaultGasMultiplier, - EventPerAttributeCost: DefaultPerAttributeCost, - CustomEventCost: DefaultPerCustomEventCost, - EventAttributeDataCost: DefaultEventAttributeDataCost, - EventAttributeDataFreeTier: DefaultEventAttributeDataFreeTier, - ContractMessageDataCost: DefaultContractMessageDataCost, - UncompressCost: DefaultPerByteUncompressCost(), - } -} - -// WasmGasRegister implements GasRegister interface -type WasmGasRegister struct { - c WasmGasRegisterConfig -} - -// NewDefaultWasmGasRegister creates instance with default values -func NewDefaultWasmGasRegister() WasmGasRegister { - return NewWasmGasRegister(DefaultGasRegisterConfig()) -} - -// NewWasmGasRegister constructor -func NewWasmGasRegister(c WasmGasRegisterConfig) WasmGasRegister { - if c.GasMultiplier == 0 { - panic(errorsmod.Wrap(sdkerrors.ErrLogic, "GasMultiplier can not be 0")) - } - return WasmGasRegister{ - c: c, - } -} - -// NewContractInstanceCosts costs to create a new contract instance from code -func (g WasmGasRegister) NewContractInstanceCosts(pinned bool, msgLen int) storetypes.Gas { - return g.InstantiateContractCosts(pinned, msgLen) -} - -// CompileCosts costs to persist and "compile" a new wasm contract -func (g WasmGasRegister) CompileCosts(byteLength int) storetypes.Gas { - if byteLength < 0 { - panic(errorsmod.Wrap(types.ErrInvalid, "negative length")) - } - return g.c.CompileCost * uint64(byteLength) -} - -// UncompressCosts costs to unpack a new wasm contract -func (g WasmGasRegister) UncompressCosts(byteLength int) sdk.Gas { - if byteLength < 0 { - panic(errorsmod.Wrap(types.ErrInvalid, "negative length")) - } - return g.c.UncompressCost.Mul(uint64(byteLength)).Floor() -} - -// InstantiateContractCosts costs when interacting with a wasm contract -func (g WasmGasRegister) InstantiateContractCosts(pinned bool, msgLen int) sdk.Gas { - if msgLen < 0 { - panic(errorsmod.Wrap(types.ErrInvalid, "negative length")) - } - dataCosts := sdk.Gas(msgLen) * g.c.ContractMessageDataCost - if pinned { - return dataCosts - } - return g.c.InstanceCost + dataCosts -} - -// ReplyCosts costs to to handle a message reply -func (g WasmGasRegister) ReplyCosts(pinned bool, reply wasmvmtypes.Reply) sdk.Gas { - var eventGas sdk.Gas - msgLen := len(reply.Result.Err) - if reply.Result.Ok != nil { - msgLen += len(reply.Result.Ok.Data) - var attrs []wasmvmtypes.EventAttribute - for _, e := range reply.Result.Ok.Events { - eventGas += sdk.Gas(len(e.Type)) * g.c.EventAttributeDataCost - attrs = append(attrs, e.Attributes...) - } - // apply free tier on the whole set not per event - eventGas += g.EventCosts(attrs, nil) - } - return eventGas + g.InstantiateContractCosts(pinned, msgLen) -} - -// EventCosts costs to persist an event -func (g WasmGasRegister) EventCosts(attrs []wasmvmtypes.EventAttribute, events wasmvmtypes.Events) sdk.Gas { - gas, remainingFreeTier := g.eventAttributeCosts(attrs, g.c.EventAttributeDataFreeTier) - for _, e := range events { - gas += g.c.CustomEventCost - gas += sdk.Gas(len(e.Type)) * g.c.EventAttributeDataCost // no free tier with event type - var attrCost sdk.Gas - attrCost, remainingFreeTier = g.eventAttributeCosts(e.Attributes, remainingFreeTier) - gas += attrCost - } - return gas -} - -func (g WasmGasRegister) eventAttributeCosts(attrs []wasmvmtypes.EventAttribute, freeTier uint64) (sdk.Gas, uint64) { - if len(attrs) == 0 { - return 0, freeTier - } - var storedBytes uint64 - for _, l := range attrs { - storedBytes += uint64(len(l.Key)) + uint64(len(l.Value)) - } - storedBytes, freeTier = calcWithFreeTier(storedBytes, freeTier) - // total Length * costs + attribute count * costs - r := sdk.NewIntFromUint64(g.c.EventAttributeDataCost).Mul(sdk.NewIntFromUint64(storedBytes)). - Add(sdk.NewIntFromUint64(g.c.EventPerAttributeCost).Mul(sdk.NewIntFromUint64(uint64(len(attrs))))) - if !r.IsUint64() { - panic(sdk.ErrorOutOfGas{Descriptor: "overflow"}) - } - return r.Uint64(), freeTier -} - -// apply free tier -func calcWithFreeTier(storedBytes uint64, freeTier uint64) (uint64, uint64) { - if storedBytes <= freeTier { - return 0, freeTier - storedBytes - } - storedBytes -= freeTier - return storedBytes, 0 -} - -// ToWasmVMGas convert to wasmVM contract runtime gas unit -func (g WasmGasRegister) ToWasmVMGas(source storetypes.Gas) uint64 { - x := source * g.c.GasMultiplier - if x < source { - panic(sdk.ErrorOutOfGas{Descriptor: "overflow"}) - } - return x -} - -// FromWasmVMGas converts to SDK gas unit -func (g WasmGasRegister) FromWasmVMGas(source uint64) sdk.Gas { - return source / g.c.GasMultiplier -} diff --git a/x/wasm/keeper/gas_register_test.go b/x/wasm/keeper/gas_register_test.go deleted file mode 100644 index 3a29e07..0000000 --- a/x/wasm/keeper/gas_register_test.go +++ /dev/null @@ -1,472 +0,0 @@ -package keeper - -import ( - "math" - "strings" - "testing" - - "github.com/terpnetwork/terp-core/x/wasm/types" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" -) - -func TestCompileCosts(t *testing.T) { - specs := map[string]struct { - srcLen int - srcConfig WasmGasRegisterConfig - exp sdk.Gas - expPanic bool - }{ - "one byte": { - srcLen: 1, - srcConfig: DefaultGasRegisterConfig(), - exp: sdk.Gas(3), // DefaultCompileCost - }, - "zero byte": { - srcLen: 0, - srcConfig: DefaultGasRegisterConfig(), - exp: sdk.Gas(0), - }, - "negative len": { - srcLen: -1, - srcConfig: DefaultGasRegisterConfig(), - expPanic: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - if spec.expPanic { - assert.Panics(t, func() { - NewWasmGasRegister(spec.srcConfig).CompileCosts(spec.srcLen) - }) - return - } - gotGas := NewWasmGasRegister(spec.srcConfig).CompileCosts(spec.srcLen) - assert.Equal(t, spec.exp, gotGas) - }) - } -} - -func TestNewContractInstanceCosts(t *testing.T) { - specs := map[string]struct { - srcLen int - srcConfig WasmGasRegisterConfig - pinned bool - exp sdk.Gas - expPanic bool - }{ - "small msg - pinned": { - srcLen: 1, - srcConfig: DefaultGasRegisterConfig(), - pinned: true, - exp: DefaultContractMessageDataCost, - }, - "big msg - pinned": { - srcLen: math.MaxUint32, - srcConfig: DefaultGasRegisterConfig(), - pinned: true, - exp: DefaultContractMessageDataCost * sdk.Gas(math.MaxUint32), - }, - "empty msg - pinned": { - srcLen: 0, - pinned: true, - srcConfig: DefaultGasRegisterConfig(), - exp: sdk.Gas(0), - }, - "small msg - unpinned": { - srcLen: 1, - srcConfig: DefaultGasRegisterConfig(), - exp: DefaultContractMessageDataCost + DefaultInstanceCost, - }, - "big msg - unpinned": { - srcLen: math.MaxUint32, - srcConfig: DefaultGasRegisterConfig(), - exp: DefaultContractMessageDataCost*math.MaxUint32 + DefaultInstanceCost, - }, - "empty msg - unpinned": { - srcLen: 0, - srcConfig: DefaultGasRegisterConfig(), - exp: DefaultInstanceCost, - }, - - "negative len": { - srcLen: -1, - srcConfig: DefaultGasRegisterConfig(), - expPanic: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - if spec.expPanic { - assert.Panics(t, func() { - NewWasmGasRegister(spec.srcConfig).NewContractInstanceCosts(spec.pinned, spec.srcLen) - }) - return - } - gotGas := NewWasmGasRegister(spec.srcConfig).NewContractInstanceCosts(spec.pinned, spec.srcLen) - assert.Equal(t, spec.exp, gotGas) - }) - } -} - -func TestContractInstanceCosts(t *testing.T) { - // same as TestNewContractInstanceCosts currently - specs := map[string]struct { - srcLen int - srcConfig WasmGasRegisterConfig - pinned bool - exp sdk.Gas - expPanic bool - }{ - "small msg - pinned": { - srcLen: 1, - srcConfig: DefaultGasRegisterConfig(), - pinned: true, - exp: DefaultContractMessageDataCost, - }, - "big msg - pinned": { - srcLen: math.MaxUint32, - srcConfig: DefaultGasRegisterConfig(), - pinned: true, - exp: DefaultContractMessageDataCost * math.MaxUint32, - }, - "empty msg - pinned": { - srcLen: 0, - pinned: true, - srcConfig: DefaultGasRegisterConfig(), - exp: sdk.Gas(0), - }, - "small msg - unpinned": { - srcLen: 1, - srcConfig: DefaultGasRegisterConfig(), - exp: DefaultContractMessageDataCost + DefaultInstanceCost, - }, - "big msg - unpinned": { - srcLen: math.MaxUint32, - srcConfig: DefaultGasRegisterConfig(), - exp: DefaultContractMessageDataCost*math.MaxUint32 + DefaultInstanceCost, - }, - "empty msg - unpinned": { - srcLen: 0, - srcConfig: DefaultGasRegisterConfig(), - exp: DefaultInstanceCost, - }, - - "negative len": { - srcLen: -1, - srcConfig: DefaultGasRegisterConfig(), - expPanic: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - if spec.expPanic { - assert.Panics(t, func() { - NewWasmGasRegister(spec.srcConfig).InstantiateContractCosts(spec.pinned, spec.srcLen) - }) - return - } - gotGas := NewWasmGasRegister(spec.srcConfig).InstantiateContractCosts(spec.pinned, spec.srcLen) - assert.Equal(t, spec.exp, gotGas) - }) - } -} - -func TestReplyCost(t *testing.T) { - specs := map[string]struct { - src wasmvmtypes.Reply - srcConfig WasmGasRegisterConfig - pinned bool - exp sdk.Gas - expPanic bool - }{ - "subcall response with events and data - pinned": { - src: wasmvmtypes.Reply{ - Result: wasmvmtypes.SubMsgResult{ - Ok: &wasmvmtypes.SubMsgResponse{ - Events: []wasmvmtypes.Event{ - {Type: "foo", Attributes: []wasmvmtypes.EventAttribute{{Key: "myKey", Value: "myData"}}}, - }, - Data: []byte{0x1}, - }, - }, - }, - srcConfig: DefaultGasRegisterConfig(), - pinned: true, - exp: 3*DefaultEventAttributeDataCost + DefaultPerAttributeCost + DefaultContractMessageDataCost, // 3 == len("foo") - }, - "subcall response with events - pinned": { - src: wasmvmtypes.Reply{ - Result: wasmvmtypes.SubMsgResult{ - Ok: &wasmvmtypes.SubMsgResponse{ - Events: []wasmvmtypes.Event{ - {Type: "foo", Attributes: []wasmvmtypes.EventAttribute{{Key: "myKey", Value: "myData"}}}, - }, - }, - }, - }, - srcConfig: DefaultGasRegisterConfig(), - pinned: true, - exp: 3*DefaultEventAttributeDataCost + DefaultPerAttributeCost, // 3 == len("foo") - }, - "subcall response with events exceeds free tier- pinned": { - src: wasmvmtypes.Reply{ - Result: wasmvmtypes.SubMsgResult{ - Ok: &wasmvmtypes.SubMsgResponse{ - Events: []wasmvmtypes.Event{ - {Type: "foo", Attributes: []wasmvmtypes.EventAttribute{{Key: strings.Repeat("x", DefaultEventAttributeDataFreeTier), Value: "myData"}}}, - }, - }, - }, - }, - srcConfig: DefaultGasRegisterConfig(), - pinned: true, - exp: (3+6)*DefaultEventAttributeDataCost + DefaultPerAttributeCost, // 3 == len("foo"), 6 == len("myData") - }, - "subcall response error - pinned": { - src: wasmvmtypes.Reply{ - Result: wasmvmtypes.SubMsgResult{ - Err: "foo", - }, - }, - srcConfig: DefaultGasRegisterConfig(), - pinned: true, - exp: 3 * DefaultContractMessageDataCost, - }, - "subcall response with events and data - unpinned": { - src: wasmvmtypes.Reply{ - Result: wasmvmtypes.SubMsgResult{ - Ok: &wasmvmtypes.SubMsgResponse{ - Events: []wasmvmtypes.Event{ - {Type: "foo", Attributes: []wasmvmtypes.EventAttribute{{Key: "myKey", Value: "myData"}}}, - }, - Data: []byte{0x1}, - }, - }, - }, - srcConfig: DefaultGasRegisterConfig(), - exp: DefaultInstanceCost + 3*DefaultEventAttributeDataCost + DefaultPerAttributeCost + DefaultContractMessageDataCost, - }, - "subcall response with events - unpinned": { - src: wasmvmtypes.Reply{ - Result: wasmvmtypes.SubMsgResult{ - Ok: &wasmvmtypes.SubMsgResponse{ - Events: []wasmvmtypes.Event{ - {Type: "foo", Attributes: []wasmvmtypes.EventAttribute{{Key: "myKey", Value: "myData"}}}, - }, - }, - }, - }, - srcConfig: DefaultGasRegisterConfig(), - exp: DefaultInstanceCost + 3*DefaultEventAttributeDataCost + DefaultPerAttributeCost, - }, - "subcall response with events exceeds free tier- unpinned": { - src: wasmvmtypes.Reply{ - Result: wasmvmtypes.SubMsgResult{ - Ok: &wasmvmtypes.SubMsgResponse{ - Events: []wasmvmtypes.Event{ - {Type: "foo", Attributes: []wasmvmtypes.EventAttribute{{Key: strings.Repeat("x", DefaultEventAttributeDataFreeTier), Value: "myData"}}}, - }, - }, - }, - }, - srcConfig: DefaultGasRegisterConfig(), - exp: DefaultInstanceCost + (3+6)*DefaultEventAttributeDataCost + DefaultPerAttributeCost, // 3 == len("foo"), 6 == len("myData") - }, - "subcall response error - unpinned": { - src: wasmvmtypes.Reply{ - Result: wasmvmtypes.SubMsgResult{ - Err: "foo", - }, - }, - srcConfig: DefaultGasRegisterConfig(), - exp: DefaultInstanceCost + 3*DefaultContractMessageDataCost, - }, - "subcall response with empty events": { - src: wasmvmtypes.Reply{ - Result: wasmvmtypes.SubMsgResult{ - Ok: &wasmvmtypes.SubMsgResponse{ - Events: make([]wasmvmtypes.Event, 10), - }, - }, - }, - srcConfig: DefaultGasRegisterConfig(), - exp: DefaultInstanceCost, - }, - "subcall response with events unset": { - src: wasmvmtypes.Reply{ - Result: wasmvmtypes.SubMsgResult{ - Ok: &wasmvmtypes.SubMsgResponse{}, - }, - }, - srcConfig: DefaultGasRegisterConfig(), - exp: DefaultInstanceCost, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - if spec.expPanic { - assert.Panics(t, func() { - NewWasmGasRegister(spec.srcConfig).ReplyCosts(spec.pinned, spec.src) - }) - return - } - gotGas := NewWasmGasRegister(spec.srcConfig).ReplyCosts(spec.pinned, spec.src) - assert.Equal(t, spec.exp, gotGas) - }) - } -} - -func TestEventCosts(t *testing.T) { - // most cases are covered in TestReplyCost already. This ensures some edge cases - specs := map[string]struct { - srcAttrs []wasmvmtypes.EventAttribute - srcEvents wasmvmtypes.Events - expGas sdk.Gas - }{ - "empty events": { - srcEvents: make([]wasmvmtypes.Event, 1), - expGas: DefaultPerCustomEventCost, - }, - "empty attributes": { - srcAttrs: make([]wasmvmtypes.EventAttribute, 1), - expGas: DefaultPerAttributeCost, - }, - "both nil": { - expGas: 0, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - gotGas := NewDefaultWasmGasRegister().EventCosts(spec.srcAttrs, spec.srcEvents) - assert.Equal(t, spec.expGas, gotGas) - }) - } -} - -func TestToWasmVMGasConversion(t *testing.T) { - specs := map[string]struct { - src storetypes.Gas - srcConfig WasmGasRegisterConfig - exp uint64 - expPanic bool - }{ - "0": { - src: 0, - exp: 0, - srcConfig: DefaultGasRegisterConfig(), - }, - "max": { - srcConfig: WasmGasRegisterConfig{ - GasMultiplier: 1, - }, - src: math.MaxUint64, - exp: math.MaxUint64, - }, - "overflow": { - srcConfig: WasmGasRegisterConfig{ - GasMultiplier: 2, - }, - src: math.MaxUint64, - expPanic: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - if spec.expPanic { - assert.Panics(t, func() { - r := NewWasmGasRegister(spec.srcConfig) - _ = r.ToWasmVMGas(spec.src) - }) - return - } - r := NewWasmGasRegister(spec.srcConfig) - got := r.ToWasmVMGas(spec.src) - assert.Equal(t, spec.exp, got) - }) - } -} - -func TestFromWasmVMGasConversion(t *testing.T) { - specs := map[string]struct { - src uint64 - exp storetypes.Gas - srcConfig WasmGasRegisterConfig - expPanic bool - }{ - "0": { - src: 0, - exp: 0, - srcConfig: DefaultGasRegisterConfig(), - }, - "max": { - srcConfig: WasmGasRegisterConfig{ - GasMultiplier: 1, - }, - src: math.MaxUint64, - exp: math.MaxUint64, - }, - "missconfigured": { - srcConfig: WasmGasRegisterConfig{ - GasMultiplier: 0, - }, - src: 1, - expPanic: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - if spec.expPanic { - assert.Panics(t, func() { - r := NewWasmGasRegister(spec.srcConfig) - _ = r.FromWasmVMGas(spec.src) - }) - return - } - r := NewWasmGasRegister(spec.srcConfig) - got := r.FromWasmVMGas(spec.src) - assert.Equal(t, spec.exp, got) - }) - } -} - -func TestUncompressCosts(t *testing.T) { - specs := map[string]struct { - lenIn int - exp sdk.Gas - expPanic bool - }{ - "0": { - exp: 0, - }, - "even": { - lenIn: 100, - exp: 15, - }, - "round down when uneven": { - lenIn: 19, - exp: 2, - }, - "max len": { - lenIn: types.MaxWasmSize, - exp: 122880, - }, - "invalid len": { - lenIn: -1, - expPanic: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - if spec.expPanic { - assert.Panics(t, func() { NewDefaultWasmGasRegister().UncompressCosts(spec.lenIn) }) - return - } - got := NewDefaultWasmGasRegister().UncompressCosts(spec.lenIn) - assert.Equal(t, spec.exp, got) - }) - } -} diff --git a/x/wasm/keeper/genesis.go b/x/wasm/keeper/genesis.go deleted file mode 100644 index 0e467ea..0000000 --- a/x/wasm/keeper/genesis.go +++ /dev/null @@ -1,120 +0,0 @@ -package keeper - -import ( - errorsmod "cosmossdk.io/errors" - abci "github.com/cometbft/cometbft/abci/types" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// ValidatorSetSource is a subset of the staking keeper -type ValidatorSetSource interface { - ApplyAndReturnValidatorSetUpdates(sdk.Context) (updates []abci.ValidatorUpdate, err error) -} - -// InitGenesis sets supply information for genesis. -// -// CONTRACT: all types of accounts must have been already initialized/created -func InitGenesis(ctx sdk.Context, keeper *Keeper, data types.GenesisState) ([]abci.ValidatorUpdate, error) { - contractKeeper := NewGovPermissionKeeper(keeper) - err := keeper.SetParams(ctx, data.Params) - if err != nil { - return nil, errorsmod.Wrapf(err, "set params") - } - - var maxCodeID uint64 - for i, code := range data.Codes { - err := keeper.importCode(ctx, code.CodeID, code.CodeInfo, code.CodeBytes) - if err != nil { - return nil, errorsmod.Wrapf(err, "code %d with id: %d", i, code.CodeID) - } - if code.CodeID > maxCodeID { - maxCodeID = code.CodeID - } - if code.Pinned { - if err := contractKeeper.PinCode(ctx, code.CodeID); err != nil { - return nil, errorsmod.Wrapf(err, "contract number %d", i) - } - } - } - - var maxContractID int - for i, contract := range data.Contracts { - contractAddr, err := sdk.AccAddressFromBech32(contract.ContractAddress) - if err != nil { - return nil, errorsmod.Wrapf(err, "address in contract number %d", i) - } - err = keeper.importContract(ctx, contractAddr, &contract.ContractInfo, contract.ContractState, contract.ContractCodeHistory) - if err != nil { - return nil, errorsmod.Wrapf(err, "contract number %d", i) - } - maxContractID = i + 1 // not ideal but max(contractID) is not persisted otherwise - } - - for i, seq := range data.Sequences { - err := keeper.importAutoIncrementID(ctx, seq.IDKey, seq.Value) - if err != nil { - return nil, errorsmod.Wrapf(err, "sequence number %d", i) - } - } - - // sanity check seq values - seqVal := keeper.PeekAutoIncrementID(ctx, types.KeyLastCodeID) - if seqVal <= maxCodeID { - return nil, errorsmod.Wrapf(types.ErrInvalid, "seq %s with value: %d must be greater than: %d ", string(types.KeyLastCodeID), seqVal, maxCodeID) - } - seqVal = keeper.PeekAutoIncrementID(ctx, types.KeyLastInstanceID) - if seqVal <= uint64(maxContractID) { - return nil, errorsmod.Wrapf(types.ErrInvalid, "seq %s with value: %d must be greater than: %d ", string(types.KeyLastInstanceID), seqVal, maxContractID) - } - return nil, nil -} - -// ExportGenesis returns a GenesisState for a given context and keeper. -func ExportGenesis(ctx sdk.Context, keeper *Keeper) *types.GenesisState { - var genState types.GenesisState - - genState.Params = keeper.GetParams(ctx) - - keeper.IterateCodeInfos(ctx, func(codeID uint64, info types.CodeInfo) bool { - bytecode, err := keeper.GetByteCode(ctx, codeID) - if err != nil { - panic(err) - } - genState.Codes = append(genState.Codes, types.Code{ - CodeID: codeID, - CodeInfo: info, - CodeBytes: bytecode, - Pinned: keeper.IsPinnedCode(ctx, codeID), - }) - return false - }) - - keeper.IterateContractInfo(ctx, func(addr sdk.AccAddress, contract types.ContractInfo) bool { - var state []types.Model - keeper.IterateContractState(ctx, addr, func(key, value []byte) bool { - state = append(state, types.Model{Key: key, Value: value}) - return false - }) - - contractCodeHistory := keeper.GetContractHistory(ctx, addr) - - genState.Contracts = append(genState.Contracts, types.Contract{ - ContractAddress: addr.String(), - ContractInfo: contract, - ContractState: state, - ContractCodeHistory: contractCodeHistory, - }) - return false - }) - - for _, k := range [][]byte{types.KeyLastCodeID, types.KeyLastInstanceID} { - genState.Sequences = append(genState.Sequences, types.Sequence{ - IDKey: k, - Value: keeper.PeekAutoIncrementID(ctx, k), - }) - } - - return &genState -} diff --git a/x/wasm/keeper/genesis_test.go b/x/wasm/keeper/genesis_test.go deleted file mode 100644 index 6be1689..0000000 --- a/x/wasm/keeper/genesis_test.go +++ /dev/null @@ -1,705 +0,0 @@ -package keeper - -import ( - "crypto/sha256" - "encoding/base64" - "fmt" - "math/rand" - "os" - "testing" - "time" - - abci "github.com/cometbft/cometbft/abci/types" - - "github.com/cosmos/cosmos-sdk/baseapp" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - - dbm "github.com/cometbft/cometbft-db" - "github.com/cometbft/cometbft/libs/log" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/cosmos/cosmos-sdk/store" - sdk "github.com/cosmos/cosmos-sdk/types" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - fuzz "github.com/google/gofuzz" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -const firstCodeID = 1 - -func TestGenesisExportImport(t *testing.T) { - wasmKeeper, srcCtx := setupKeeper(t) - contractKeeper := NewGovPermissionKeeper(wasmKeeper) - - wasmCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - - // store some test data - f := fuzz.New().Funcs(ModelFuzzers...) - - err = wasmKeeper.SetParams(srcCtx, types.DefaultParams()) - require.NoError(t, err) - - for i := 0; i < 25; i++ { - var ( - codeInfo types.CodeInfo - contract types.ContractInfo - stateModels []types.Model - history []types.ContractCodeHistoryEntry - pinned bool - contractExtension bool - ) - f.Fuzz(&codeInfo) - f.Fuzz(&contract) - f.Fuzz(&stateModels) - f.NilChance(0).Fuzz(&history) - f.Fuzz(&pinned) - f.Fuzz(&contractExtension) - - creatorAddr, err := sdk.AccAddressFromBech32(codeInfo.Creator) - require.NoError(t, err) - codeID, _, err := contractKeeper.Create(srcCtx, creatorAddr, wasmCode, &codeInfo.InstantiateConfig) - require.NoError(t, err) - if pinned { - err = contractKeeper.PinCode(srcCtx, codeID) - require.NoError(t, err) - } - if contractExtension { - anyTime := time.Now().UTC() - var nestedType v1beta1.TextProposal - f.NilChance(0).Fuzz(&nestedType) - myExtension, err := v1beta1.NewProposal(&nestedType, 1, anyTime, anyTime) - require.NoError(t, err) - err = contract.SetExtension(&myExtension) - require.NoError(t, err) - } - - contract.CodeID = codeID - contractAddr := wasmKeeper.ClassicAddressGenerator()(srcCtx, codeID, nil) - wasmKeeper.storeContractInfo(srcCtx, contractAddr, &contract) - wasmKeeper.appendToContractHistory(srcCtx, contractAddr, history...) - err = wasmKeeper.importContractState(srcCtx, contractAddr, stateModels) - require.NoError(t, err) - } - var wasmParams types.Params - f.NilChance(0).Fuzz(&wasmParams) - err = wasmKeeper.SetParams(srcCtx, wasmParams) - require.NoError(t, err) - - // export - exportedState := ExportGenesis(srcCtx, wasmKeeper) - // order should not matter - rand.Shuffle(len(exportedState.Codes), func(i, j int) { - exportedState.Codes[i], exportedState.Codes[j] = exportedState.Codes[j], exportedState.Codes[i] - }) - rand.Shuffle(len(exportedState.Contracts), func(i, j int) { - exportedState.Contracts[i], exportedState.Contracts[j] = exportedState.Contracts[j], exportedState.Contracts[i] - }) - rand.Shuffle(len(exportedState.Sequences), func(i, j int) { - exportedState.Sequences[i], exportedState.Sequences[j] = exportedState.Sequences[j], exportedState.Sequences[i] - }) - exportedGenesis, err := wasmKeeper.cdc.MarshalJSON(exportedState) - require.NoError(t, err) - - // setup new instances - dstKeeper, dstCtx := setupKeeper(t) - - // reset contract code index in source DB for comparison with dest DB - wasmKeeper.IterateContractInfo(srcCtx, func(address sdk.AccAddress, info types.ContractInfo) bool { - creatorAddress := sdk.MustAccAddressFromBech32(info.Creator) - history := wasmKeeper.GetContractHistory(srcCtx, address) - - wasmKeeper.addToContractCodeSecondaryIndex(srcCtx, address, history[len(history)-1]) - wasmKeeper.addToContractCreatorSecondaryIndex(srcCtx, creatorAddress, history[0].Updated, address) - return false - }) - - // re-import - var importState types.GenesisState - err = dstKeeper.cdc.UnmarshalJSON(exportedGenesis, &importState) - require.NoError(t, err) - _, err = InitGenesis(dstCtx, dstKeeper, importState) - require.NoError(t, err) - - // compare whole DB - - srcIT := srcCtx.KVStore(wasmKeeper.storeKey).Iterator(nil, nil) - dstIT := dstCtx.KVStore(dstKeeper.storeKey).Iterator(nil, nil) - - for i := 0; srcIT.Valid(); i++ { - require.True(t, dstIT.Valid(), "[%s] destination DB has less elements than source. Missing: %x", wasmKeeper.storeKey.Name(), srcIT.Key()) - require.Equal(t, srcIT.Key(), dstIT.Key(), i) - require.Equal(t, srcIT.Value(), dstIT.Value(), "[%s] element (%d): %X", wasmKeeper.storeKey.Name(), i, srcIT.Key()) - dstIT.Next() - srcIT.Next() - } - if !assert.False(t, dstIT.Valid()) { - t.Fatalf("dest Iterator still has key :%X", dstIT.Key()) - } - srcIT.Close() - dstIT.Close() -} - -func TestGenesisInit(t *testing.T) { - wasmCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - - myCodeInfo := types.CodeInfoFixture(types.WithSHA256CodeHash(wasmCode)) - specs := map[string]struct { - src types.GenesisState - expSuccess bool - }{ - "happy path: code info correct": { - src: types.GenesisState{ - Codes: []types.Code{{ - CodeID: firstCodeID, - CodeInfo: myCodeInfo, - CodeBytes: wasmCode, - }}, - Sequences: []types.Sequence{ - {IDKey: types.KeyLastCodeID, Value: 2}, - {IDKey: types.KeyLastInstanceID, Value: 1}, - }, - Params: types.DefaultParams(), - }, - expSuccess: true, - }, - "happy path: code ids can contain gaps": { - src: types.GenesisState{ - Codes: []types.Code{{ - CodeID: firstCodeID, - CodeInfo: myCodeInfo, - CodeBytes: wasmCode, - }, { - CodeID: 3, - CodeInfo: myCodeInfo, - CodeBytes: wasmCode, - }}, - Sequences: []types.Sequence{ - {IDKey: types.KeyLastCodeID, Value: 10}, - {IDKey: types.KeyLastInstanceID, Value: 1}, - }, - Params: types.DefaultParams(), - }, - expSuccess: true, - }, - "happy path: code order does not matter": { - src: types.GenesisState{ - Codes: []types.Code{{ - CodeID: 2, - CodeInfo: myCodeInfo, - CodeBytes: wasmCode, - }, { - CodeID: firstCodeID, - CodeInfo: myCodeInfo, - CodeBytes: wasmCode, - }}, - Contracts: nil, - Sequences: []types.Sequence{ - {IDKey: types.KeyLastCodeID, Value: 3}, - {IDKey: types.KeyLastInstanceID, Value: 1}, - }, - Params: types.DefaultParams(), - }, - expSuccess: true, - }, - "prevent code hash mismatch": {src: types.GenesisState{ - Codes: []types.Code{{ - CodeID: firstCodeID, - CodeInfo: types.CodeInfoFixture(func(i *types.CodeInfo) { i.CodeHash = make([]byte, sha256.Size) }), - CodeBytes: wasmCode, - }}, - Params: types.DefaultParams(), - }}, - "prevent duplicate codeIDs": {src: types.GenesisState{ - Codes: []types.Code{ - { - CodeID: firstCodeID, - CodeInfo: myCodeInfo, - CodeBytes: wasmCode, - }, - { - CodeID: firstCodeID, - CodeInfo: myCodeInfo, - CodeBytes: wasmCode, - }, - }, - Params: types.DefaultParams(), - }}, - "codes with same checksum can be pinned": { - src: types.GenesisState{ - Codes: []types.Code{ - { - CodeID: firstCodeID, - CodeInfo: myCodeInfo, - CodeBytes: wasmCode, - Pinned: true, - }, - { - CodeID: 2, - CodeInfo: myCodeInfo, - CodeBytes: wasmCode, - Pinned: true, - }, - }, - Params: types.DefaultParams(), - }, - }, - "happy path: code id in info and contract do match": { - src: types.GenesisState{ - Codes: []types.Code{{ - CodeID: firstCodeID, - CodeInfo: myCodeInfo, - CodeBytes: wasmCode, - }}, - Contracts: []types.Contract{ - { - ContractAddress: BuildContractAddressClassic(1, 1).String(), - ContractInfo: types.ContractInfoFixture(func(c *types.ContractInfo) { c.CodeID = 1 }, types.RandCreatedFields), - ContractCodeHistory: []types.ContractCodeHistoryEntry{ - { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 1, - Updated: &types.AbsoluteTxPosition{BlockHeight: rand.Uint64(), TxIndex: rand.Uint64()}, - Msg: []byte(`{}`), - }, - }, - }, - }, - Sequences: []types.Sequence{ - {IDKey: types.KeyLastCodeID, Value: 2}, - {IDKey: types.KeyLastInstanceID, Value: 2}, - }, - Params: types.DefaultParams(), - }, - expSuccess: true, - }, - "happy path: code info with two contracts": { - src: types.GenesisState{ - Codes: []types.Code{{ - CodeID: firstCodeID, - CodeInfo: myCodeInfo, - CodeBytes: wasmCode, - }}, - Contracts: []types.Contract{ - { - ContractAddress: BuildContractAddressClassic(1, 1).String(), - ContractInfo: types.ContractInfoFixture(func(c *types.ContractInfo) { c.CodeID = 1 }, types.RandCreatedFields), - ContractCodeHistory: []types.ContractCodeHistoryEntry{ - { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 1, - Updated: &types.AbsoluteTxPosition{BlockHeight: rand.Uint64(), TxIndex: rand.Uint64()}, - Msg: []byte(`{}`), - }, - }, - }, { - ContractAddress: BuildContractAddressClassic(1, 2).String(), - ContractInfo: types.ContractInfoFixture(func(c *types.ContractInfo) { c.CodeID = 1 }, types.RandCreatedFields), - ContractCodeHistory: []types.ContractCodeHistoryEntry{ - { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 1, - Updated: &types.AbsoluteTxPosition{BlockHeight: rand.Uint64(), TxIndex: rand.Uint64()}, - Msg: []byte(`{"foo":"bar"}`), - }, - }, - }, - }, - Sequences: []types.Sequence{ - {IDKey: types.KeyLastCodeID, Value: 2}, - {IDKey: types.KeyLastInstanceID, Value: 3}, - }, - Params: types.DefaultParams(), - }, - expSuccess: true, - }, - "prevent contracts that points to non existing codeID": { - src: types.GenesisState{ - Contracts: []types.Contract{ - { - ContractAddress: BuildContractAddressClassic(1, 1).String(), - ContractInfo: types.ContractInfoFixture(func(c *types.ContractInfo) { c.CodeID = 1 }, types.RandCreatedFields), - ContractCodeHistory: []types.ContractCodeHistoryEntry{ - { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 1, - Updated: &types.AbsoluteTxPosition{BlockHeight: rand.Uint64(), TxIndex: rand.Uint64()}, - Msg: []byte(`{"foo":"bar"}`), - }, - }, - }, - }, - Params: types.DefaultParams(), - }, - }, - "prevent duplicate contract address": { - src: types.GenesisState{ - Codes: []types.Code{{ - CodeID: firstCodeID, - CodeInfo: myCodeInfo, - CodeBytes: wasmCode, - }}, - Contracts: []types.Contract{ - { - ContractAddress: BuildContractAddressClassic(1, 1).String(), - ContractInfo: types.ContractInfoFixture(func(c *types.ContractInfo) { c.CodeID = 1 }, types.RandCreatedFields), - ContractCodeHistory: []types.ContractCodeHistoryEntry{ - { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 1, - Updated: &types.AbsoluteTxPosition{BlockHeight: rand.Uint64(), TxIndex: rand.Uint64()}, - Msg: []byte(`{"foo":"bar"}`), - }, - }, - }, { - ContractAddress: BuildContractAddressClassic(1, 1).String(), - ContractInfo: types.ContractInfoFixture(func(c *types.ContractInfo) { c.CodeID = 1 }, types.RandCreatedFields), - ContractCodeHistory: []types.ContractCodeHistoryEntry{ - { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 1, - Updated: &types.AbsoluteTxPosition{BlockHeight: rand.Uint64(), TxIndex: rand.Uint64()}, - Msg: []byte(`{"other":"value"}`), - }, - }, - }, - }, - Params: types.DefaultParams(), - }, - }, - "prevent duplicate contract model keys": { - src: types.GenesisState{ - Codes: []types.Code{{ - CodeID: firstCodeID, - CodeInfo: myCodeInfo, - CodeBytes: wasmCode, - }}, - Contracts: []types.Contract{ - { - ContractAddress: BuildContractAddressClassic(1, 1).String(), - ContractInfo: types.ContractInfoFixture(func(c *types.ContractInfo) { c.CodeID = 1 }, types.RandCreatedFields), - ContractState: []types.Model{ - { - Key: []byte{0x1}, - Value: []byte("foo"), - }, - { - Key: []byte{0x1}, - Value: []byte("bar"), - }, - }, - ContractCodeHistory: []types.ContractCodeHistoryEntry{ - { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 1, - Updated: &types.AbsoluteTxPosition{BlockHeight: rand.Uint64(), TxIndex: rand.Uint64()}, - Msg: []byte(`{"foo":"bar"}`), - }, - }, - }, - }, - Params: types.DefaultParams(), - }, - }, - "prevent duplicate sequences": { - src: types.GenesisState{ - Sequences: []types.Sequence{ - {IDKey: []byte("foo"), Value: 1}, - {IDKey: []byte("foo"), Value: 9999}, - }, - Params: types.DefaultParams(), - }, - }, - "prevent code id seq init value == max codeID used": { - src: types.GenesisState{ - Codes: []types.Code{{ - CodeID: 2, - CodeInfo: myCodeInfo, - CodeBytes: wasmCode, - }}, - Sequences: []types.Sequence{ - {IDKey: types.KeyLastCodeID, Value: 1}, - }, - Params: types.DefaultParams(), - }, - }, - "prevent contract id seq init value == count contracts": { - src: types.GenesisState{ - Codes: []types.Code{{ - CodeID: firstCodeID, - CodeInfo: myCodeInfo, - CodeBytes: wasmCode, - }}, - Contracts: []types.Contract{ - { - ContractAddress: BuildContractAddressClassic(1, 1).String(), - ContractInfo: types.ContractInfoFixture(func(c *types.ContractInfo) { c.CodeID = 1 }, types.RandCreatedFields), - ContractCodeHistory: []types.ContractCodeHistoryEntry{ - { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 1, - Updated: &types.AbsoluteTxPosition{BlockHeight: rand.Uint64(), TxIndex: rand.Uint64()}, - Msg: []byte(`{}`), - }, - }, - }, - }, - Sequences: []types.Sequence{ - {IDKey: types.KeyLastCodeID, Value: 2}, - {IDKey: types.KeyLastInstanceID, Value: 1}, - }, - Params: types.DefaultParams(), - }, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - keeper, ctx := setupKeeper(t) - - require.NoError(t, types.ValidateGenesis(spec.src)) - _, gotErr := InitGenesis(ctx, keeper, spec.src) - if !spec.expSuccess { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - - for _, c := range spec.src.Codes { - assert.Equal(t, c.Pinned, keeper.IsPinnedCode(ctx, c.CodeID)) - } - }) - } -} - -func TestImportContractWithCodeHistoryPreserved(t *testing.T) { - genesisTemplate := ` -{ - "params":{ - "code_upload_access": { - "permission": "Everybody" - }, - "instantiate_default_permission": "Everybody" - }, - "codes": [ - { - "code_id": "1", - "code_info": { - "code_hash": %q, - "creator": "cosmos1qtu5n0cnhfkjj6l2rq97hmky9fd89gwca9yarx", - "instantiate_config": { - "permission": "OnlyAddress", - "address": "cosmos1qtu5n0cnhfkjj6l2rq97hmky9fd89gwca9yarx" - } - }, - "code_bytes": %q - } - ], - "contracts": [ - { - "contract_address": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr", - "contract_info": { - "code_id": "1", - "creator": "cosmos13x849jzd03vne42ynpj25hn8npjecxqrjghd8x", - "admin": "cosmos1h5t8zxmjr30e9dqghtlpl40f2zz5cgey6esxtn", - "label": "ȀĴnZV芢毤", - "created": { - "block_height" : "100", - "tx_index" : "10" - } - }, - "contract_code_history": [ - { - "operation": "CONTRACT_CODE_HISTORY_OPERATION_TYPE_INIT", - "code_id": "1", - "updated": { - "block_height" : "100", - "tx_index" : "10" - }, - "msg": {"foo": "bar"} - }, - { - "operation": "CONTRACT_CODE_HISTORY_OPERATION_TYPE_MIGRATE", - "code_id": "1", - "updated": { - "block_height" : "200", - "tx_index" : "10" - }, - "msg": {"other": "msg"} - } - ] - } - ], - "sequences": [ - {"id_key": "BGxhc3RDb2RlSWQ=", "value": "2"}, - {"id_key": "BGxhc3RDb250cmFjdElk", "value": "3"} - ] -}` - keeper, ctx := setupKeeper(t) - - wasmCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - - wasmCodeHash := sha256.Sum256(wasmCode) - enc64 := base64.StdEncoding.EncodeToString - genesisStr := fmt.Sprintf(genesisTemplate, enc64(wasmCodeHash[:]), enc64(wasmCode)) - - var importState types.GenesisState - err = keeper.cdc.UnmarshalJSON([]byte(genesisStr), &importState) - require.NoError(t, err) - require.NoError(t, importState.ValidateBasic(), genesisStr) - - ctx = ctx.WithBlockHeight(0).WithGasMeter(sdk.NewInfiniteGasMeter()) - - // when - _, err = InitGenesis(ctx, keeper, importState) - require.NoError(t, err) - - // verify wasm code - gotWasmCode, err := keeper.GetByteCode(ctx, 1) - require.NoError(t, err) - assert.Equal(t, wasmCode, gotWasmCode, "byte code does not match") - - // verify code info - gotCodeInfo := keeper.GetCodeInfo(ctx, 1) - require.NotNil(t, gotCodeInfo) - codeCreatorAddr := "cosmos1qtu5n0cnhfkjj6l2rq97hmky9fd89gwca9yarx" - expCodeInfo := types.CodeInfo{ - CodeHash: wasmCodeHash[:], - Creator: codeCreatorAddr, - InstantiateConfig: types.AccessConfig{ - Permission: types.AccessTypeOnlyAddress, - Address: codeCreatorAddr, - }, - } - assert.Equal(t, expCodeInfo, *gotCodeInfo) - - // verify contract - contractAddr, _ := sdk.AccAddressFromBech32("cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr") - gotContractInfo := keeper.GetContractInfo(ctx, contractAddr) - require.NotNil(t, gotContractInfo) - contractCreatorAddr := "cosmos13x849jzd03vne42ynpj25hn8npjecxqrjghd8x" - adminAddr := "cosmos1h5t8zxmjr30e9dqghtlpl40f2zz5cgey6esxtn" - - expContractInfo := types.ContractInfo{ - CodeID: firstCodeID, - Creator: contractCreatorAddr, - Admin: adminAddr, - Label: "ȀĴnZV芢毤", - Created: &types.AbsoluteTxPosition{BlockHeight: 100, TxIndex: 10}, - } - assert.Equal(t, expContractInfo, *gotContractInfo) - - expHistory := []types.ContractCodeHistoryEntry{ - { - Operation: types.ContractCodeHistoryOperationTypeInit, - CodeID: firstCodeID, - Updated: &types.AbsoluteTxPosition{ - BlockHeight: 100, - TxIndex: 10, - }, - Msg: []byte(`{"foo": "bar"}`), - }, - { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: firstCodeID, - Updated: &types.AbsoluteTxPosition{ - BlockHeight: 200, - TxIndex: 10, - }, - Msg: []byte(`{"other": "msg"}`), - }, - } - assert.Equal(t, expHistory, keeper.GetContractHistory(ctx, contractAddr)) - assert.Equal(t, uint64(2), keeper.PeekAutoIncrementID(ctx, types.KeyLastCodeID)) - assert.Equal(t, uint64(3), keeper.PeekAutoIncrementID(ctx, types.KeyLastInstanceID)) -} - -func setupKeeper(t *testing.T) (*Keeper, sdk.Context) { - t.Helper() - tempDir, err := os.MkdirTemp("", "wasm") - require.NoError(t, err) - t.Cleanup(func() { os.RemoveAll(tempDir) }) - - keyWasm := sdk.NewKVStoreKey(types.StoreKey) - - db := dbm.NewMemDB() - ms := store.NewCommitMultiStore(db) - ms.MountStoreWithDB(keyWasm, storetypes.StoreTypeIAVL, db) - require.NoError(t, ms.LoadLatestVersion()) - - ctx := sdk.NewContext(ms, tmproto.Header{ - Height: 1234567, - Time: time.Date(2020, time.April, 22, 12, 0, 0, 0, time.UTC), - }, false, log.NewNopLogger()) - - encodingConfig := MakeEncodingConfig(t) - // register an example extension. must be protobuf - encodingConfig.InterfaceRegistry.RegisterImplementations( - (*types.ContractInfoExtension)(nil), - &v1beta1.Proposal{}, - ) - // also registering gov interfaces for nested Any type - v1beta1.RegisterInterfaces(encodingConfig.InterfaceRegistry) - - wasmConfig := types.DefaultWasmConfig() - - srcKeeper := NewKeeper( - encodingConfig.Marshaler, - keyWasm, - authkeeper.AccountKeeper{}, - &bankkeeper.BaseKeeper{}, - stakingkeeper.Keeper{}, - nil, - nil, - nil, - nil, - nil, - nil, - nil, - tempDir, - wasmConfig, - AvailableCapabilities, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), - ) - return &srcKeeper, ctx -} - -type StakingKeeperMock struct { - err error - validatorUpdate []abci.ValidatorUpdate - gotCalls int -} - -func (s *StakingKeeperMock) ApplyAndReturnValidatorSetUpdates(_ sdk.Context) ([]abci.ValidatorUpdate, error) { - s.gotCalls++ - return s.validatorUpdate, s.err -} - -var _ MessageRouter = &MockMsgHandler{} - -type MockMsgHandler struct { - result *sdk.Result - err error - expCalls int //nolint:unused - gotCalls int - expMsg sdk.Msg //nolint:unused - gotMsg sdk.Msg -} - -func (m *MockMsgHandler) Handler(msg sdk.Msg) baseapp.MsgServiceHandler { - return m.Handle -} - -func (m *MockMsgHandler) Handle(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { - m.gotCalls++ - m.gotMsg = msg - return m.result, m.err -} diff --git a/x/wasm/keeper/handler_plugin.go b/x/wasm/keeper/handler_plugin.go deleted file mode 100644 index beba71a..0000000 --- a/x/wasm/keeper/handler_plugin.go +++ /dev/null @@ -1,219 +0,0 @@ -package keeper - -import ( - "errors" - "fmt" - - errorsmod "cosmossdk.io/errors" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/cosmos/cosmos-sdk/baseapp" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - host "github.com/cosmos/ibc-go/v7/modules/core/24-host" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// msgEncoder is an extension point to customize encodings -type msgEncoder interface { - // Encode converts wasmvm message to n cosmos message types - Encode(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) ([]sdk.Msg, error) -} - -// MessageRouter ADR 031 request type routing -type MessageRouter interface { - Handler(msg sdk.Msg) baseapp.MsgServiceHandler -} - -// SDKMessageHandler can handles messages that can be encoded into sdk.Message types and routed. -type SDKMessageHandler struct { - router MessageRouter - encoders msgEncoder -} - -func NewDefaultMessageHandler( - router MessageRouter, - channelKeeper types.ChannelKeeper, - capabilityKeeper types.CapabilityKeeper, - bankKeeper types.Burner, - unpacker codectypes.AnyUnpacker, - portSource types.ICS20TransferPortSource, - customEncoders ...*MessageEncoders, -) Messenger { - encoders := DefaultEncoders(unpacker, portSource) - for _, e := range customEncoders { - encoders = encoders.Merge(e) - } - return NewMessageHandlerChain( - NewSDKMessageHandler(router, encoders), - NewIBCRawPacketHandler(channelKeeper, capabilityKeeper), - NewBurnCoinMessageHandler(bankKeeper), - ) -} - -func NewSDKMessageHandler(router MessageRouter, encoders msgEncoder) SDKMessageHandler { - return SDKMessageHandler{ - router: router, - encoders: encoders, - } -} - -func (h SDKMessageHandler) DispatchMsg(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - sdkMsgs, err := h.encoders.Encode(ctx, contractAddr, contractIBCPortID, msg) - if err != nil { - return nil, nil, err - } - for _, sdkMsg := range sdkMsgs { - res, err := h.handleSdkMessage(ctx, contractAddr, sdkMsg) - if err != nil { - return nil, nil, err - } - // append data - data = append(data, res.Data) - // append events - sdkEvents := make([]sdk.Event, len(res.Events)) - for i := range res.Events { - sdkEvents[i] = sdk.Event(res.Events[i]) - } - events = append(events, sdkEvents...) - } - return -} - -func (h SDKMessageHandler) handleSdkMessage(ctx sdk.Context, contractAddr sdk.Address, msg sdk.Msg) (*sdk.Result, error) { - if err := msg.ValidateBasic(); err != nil { - return nil, err - } - // make sure this account can send it - for _, acct := range msg.GetSigners() { - if !acct.Equals(contractAddr) { - return nil, errorsmod.Wrap(sdkerrors.ErrUnauthorized, "contract doesn't have permission") - } - } - - // find the handler and execute it - if handler := h.router.Handler(msg); handler != nil { - // ADR 031 request type routing - msgResult, err := handler(ctx, msg) - return msgResult, err - } - // legacy sdk.Msg routing - // Assuming that the app developer has migrated all their Msgs to - // proto messages and has registered all `Msg services`, then this - // path should never be called, because all those Msgs should be - // registered within the `msgServiceRouter` already. - return nil, errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "can't route message %+v", msg) -} - -// MessageHandlerChain defines a chain of handlers that are called one by one until it can be handled. -type MessageHandlerChain struct { - handlers []Messenger -} - -func NewMessageHandlerChain(first Messenger, others ...Messenger) *MessageHandlerChain { - r := &MessageHandlerChain{handlers: append([]Messenger{first}, others...)} - for i := range r.handlers { - if r.handlers[i] == nil { - panic(fmt.Sprintf("handler must not be nil at position : %d", i)) - } - } - return r -} - -// DispatchMsg dispatch message and calls chained handlers one after another in -// order to find the right one to process given message. If a handler cannot -// process given message (returns ErrUnknownMsg), its result is ignored and the -// next handler is executed. -func (m MessageHandlerChain) DispatchMsg(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) ([]sdk.Event, [][]byte, error) { - for _, h := range m.handlers { - events, data, err := h.DispatchMsg(ctx, contractAddr, contractIBCPortID, msg) - switch { - case err == nil: - return events, data, nil - case errors.Is(err, types.ErrUnknownMsg): - continue - default: - return events, data, err - } - } - return nil, nil, errorsmod.Wrap(types.ErrUnknownMsg, "no handler found") -} - -// IBCRawPacketHandler handels IBC.SendPacket messages which are published to an IBC channel. -type IBCRawPacketHandler struct { - channelKeeper types.ChannelKeeper - capabilityKeeper types.CapabilityKeeper -} - -func NewIBCRawPacketHandler(chk types.ChannelKeeper, cak types.CapabilityKeeper) IBCRawPacketHandler { - return IBCRawPacketHandler{channelKeeper: chk, capabilityKeeper: cak} -} - -// DispatchMsg publishes a raw IBC packet onto the channel. -func (h IBCRawPacketHandler) DispatchMsg(ctx sdk.Context, _ sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) ([]sdk.Event, [][]byte, error) { - if msg.IBC == nil || msg.IBC.SendPacket == nil { - return nil, nil, types.ErrUnknownMsg - } - if contractIBCPortID == "" { - return nil, nil, errorsmod.Wrapf(types.ErrUnsupportedForContract, "ibc not supported") - } - contractIBCChannelID := msg.IBC.SendPacket.ChannelID - if contractIBCChannelID == "" { - return nil, nil, errorsmod.Wrapf(types.ErrEmpty, "ibc channel") - } - - channelCap, ok := h.capabilityKeeper.GetCapability(ctx, host.ChannelCapabilityPath(contractIBCPortID, contractIBCChannelID)) - if !ok { - return nil, nil, errorsmod.Wrap(channeltypes.ErrChannelCapabilityNotFound, "module does not own channel capability") - } - seq, err := h.channelKeeper.SendPacket(ctx, channelCap, contractIBCPortID, contractIBCChannelID, ConvertWasmIBCTimeoutHeightToCosmosHeight(msg.IBC.SendPacket.Timeout.Block), msg.IBC.SendPacket.Timeout.Timestamp, msg.IBC.SendPacket.Data) - if err != nil { - return nil, nil, errorsmod.Wrap(err, "channel") - } - moduleLogger(ctx).Debug("ibc packet set", "seq", seq) - - resp := &types.MsgIBCSendResponse{Sequence: seq} - val, err := resp.Marshal() - if err != nil { - return nil, nil, errorsmod.Wrap(err, "failed to marshal IBC send response") - } - - return nil, [][]byte{val}, nil -} - -var _ Messenger = MessageHandlerFunc(nil) - -// MessageHandlerFunc is a helper to construct a function based message handler. -type MessageHandlerFunc func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) - -// DispatchMsg delegates dispatching of provided message into the MessageHandlerFunc. -func (m MessageHandlerFunc) DispatchMsg(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - return m(ctx, contractAddr, contractIBCPortID, msg) -} - -// NewBurnCoinMessageHandler handles wasmvm.BurnMsg messages -func NewBurnCoinMessageHandler(burner types.Burner) MessageHandlerFunc { - return func(ctx sdk.Context, contractAddr sdk.AccAddress, _ string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - if msg.Bank != nil && msg.Bank.Burn != nil { - coins, err := ConvertWasmCoinsToSdkCoins(msg.Bank.Burn.Amount) - if err != nil { - return nil, nil, err - } - if coins.IsZero() { - return nil, nil, types.ErrEmpty.Wrap("amount") - } - if err := burner.SendCoinsFromAccountToModule(ctx, contractAddr, types.ModuleName, coins); err != nil { - return nil, nil, errorsmod.Wrap(err, "transfer to module") - } - if err := burner.BurnCoins(ctx, types.ModuleName, coins); err != nil { - return nil, nil, errorsmod.Wrap(err, "burn coins") - } - moduleLogger(ctx).Info("Burned", "amount", coins) - return nil, nil, nil - } - return nil, nil, types.ErrUnknownMsg - } -} diff --git a/x/wasm/keeper/handler_plugin_encoders.go b/x/wasm/keeper/handler_plugin_encoders.go deleted file mode 100644 index e6883e1..0000000 --- a/x/wasm/keeper/handler_plugin_encoders.go +++ /dev/null @@ -1,395 +0,0 @@ -package keeper - -import ( - "encoding/json" - "fmt" - - errorsmod "cosmossdk.io/errors" - v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - ibctransfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" - ibcclienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -type ( - BankEncoder func(sender sdk.AccAddress, msg *wasmvmtypes.BankMsg) ([]sdk.Msg, error) - CustomEncoder func(sender sdk.AccAddress, msg json.RawMessage) ([]sdk.Msg, error) - DistributionEncoder func(sender sdk.AccAddress, msg *wasmvmtypes.DistributionMsg) ([]sdk.Msg, error) - StakingEncoder func(sender sdk.AccAddress, msg *wasmvmtypes.StakingMsg) ([]sdk.Msg, error) - StargateEncoder func(sender sdk.AccAddress, msg *wasmvmtypes.StargateMsg) ([]sdk.Msg, error) - WasmEncoder func(sender sdk.AccAddress, msg *wasmvmtypes.WasmMsg) ([]sdk.Msg, error) - IBCEncoder func(ctx sdk.Context, sender sdk.AccAddress, contractIBCPortID string, msg *wasmvmtypes.IBCMsg) ([]sdk.Msg, error) -) - -type MessageEncoders struct { - Bank func(sender sdk.AccAddress, msg *wasmvmtypes.BankMsg) ([]sdk.Msg, error) - Custom func(sender sdk.AccAddress, msg json.RawMessage) ([]sdk.Msg, error) - Distribution func(sender sdk.AccAddress, msg *wasmvmtypes.DistributionMsg) ([]sdk.Msg, error) - IBC func(ctx sdk.Context, sender sdk.AccAddress, contractIBCPortID string, msg *wasmvmtypes.IBCMsg) ([]sdk.Msg, error) - Staking func(sender sdk.AccAddress, msg *wasmvmtypes.StakingMsg) ([]sdk.Msg, error) - Stargate func(sender sdk.AccAddress, msg *wasmvmtypes.StargateMsg) ([]sdk.Msg, error) - Wasm func(sender sdk.AccAddress, msg *wasmvmtypes.WasmMsg) ([]sdk.Msg, error) - Gov func(sender sdk.AccAddress, msg *wasmvmtypes.GovMsg) ([]sdk.Msg, error) -} - -func DefaultEncoders(unpacker codectypes.AnyUnpacker, portSource types.ICS20TransferPortSource) MessageEncoders { - return MessageEncoders{ - Bank: EncodeBankMsg, - Custom: NoCustomMsg, - Distribution: EncodeDistributionMsg, - IBC: EncodeIBCMsg(portSource), - Staking: EncodeStakingMsg, - Stargate: EncodeStargateMsg(unpacker), - Wasm: EncodeWasmMsg, - Gov: EncodeGovMsg, - } -} - -func (e MessageEncoders) Merge(o *MessageEncoders) MessageEncoders { - if o == nil { - return e - } - if o.Bank != nil { - e.Bank = o.Bank - } - if o.Custom != nil { - e.Custom = o.Custom - } - if o.Distribution != nil { - e.Distribution = o.Distribution - } - if o.IBC != nil { - e.IBC = o.IBC - } - if o.Staking != nil { - e.Staking = o.Staking - } - if o.Stargate != nil { - e.Stargate = o.Stargate - } - if o.Wasm != nil { - e.Wasm = o.Wasm - } - if o.Gov != nil { - e.Gov = o.Gov - } - return e -} - -func (e MessageEncoders) Encode(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) ([]sdk.Msg, error) { - switch { - case msg.Bank != nil: - return e.Bank(contractAddr, msg.Bank) - case msg.Custom != nil: - return e.Custom(contractAddr, msg.Custom) - case msg.Distribution != nil: - return e.Distribution(contractAddr, msg.Distribution) - case msg.IBC != nil: - return e.IBC(ctx, contractAddr, contractIBCPortID, msg.IBC) - case msg.Staking != nil: - return e.Staking(contractAddr, msg.Staking) - case msg.Stargate != nil: - return e.Stargate(contractAddr, msg.Stargate) - case msg.Wasm != nil: - return e.Wasm(contractAddr, msg.Wasm) - case msg.Gov != nil: - return EncodeGovMsg(contractAddr, msg.Gov) - } - return nil, errorsmod.Wrap(types.ErrUnknownMsg, "unknown variant of Wasm") -} - -func EncodeBankMsg(sender sdk.AccAddress, msg *wasmvmtypes.BankMsg) ([]sdk.Msg, error) { - if msg.Send == nil { - return nil, errorsmod.Wrap(types.ErrUnknownMsg, "unknown variant of Bank") - } - if len(msg.Send.Amount) == 0 { - return nil, nil - } - toSend, err := ConvertWasmCoinsToSdkCoins(msg.Send.Amount) - if err != nil { - return nil, err - } - sdkMsg := banktypes.MsgSend{ - FromAddress: sender.String(), - ToAddress: msg.Send.ToAddress, - Amount: toSend, - } - return []sdk.Msg{&sdkMsg}, nil -} - -func NoCustomMsg(_ sdk.AccAddress, _ json.RawMessage) ([]sdk.Msg, error) { - return nil, errorsmod.Wrap(types.ErrUnknownMsg, "custom variant not supported") -} - -func EncodeDistributionMsg(sender sdk.AccAddress, msg *wasmvmtypes.DistributionMsg) ([]sdk.Msg, error) { - switch { - case msg.SetWithdrawAddress != nil: - setMsg := distributiontypes.MsgSetWithdrawAddress{ - DelegatorAddress: sender.String(), - WithdrawAddress: msg.SetWithdrawAddress.Address, - } - return []sdk.Msg{&setMsg}, nil - case msg.WithdrawDelegatorReward != nil: - withdrawMsg := distributiontypes.MsgWithdrawDelegatorReward{ - DelegatorAddress: sender.String(), - ValidatorAddress: msg.WithdrawDelegatorReward.Validator, - } - return []sdk.Msg{&withdrawMsg}, nil - default: - return nil, errorsmod.Wrap(types.ErrUnknownMsg, "unknown variant of Distribution") - } -} - -func EncodeStakingMsg(sender sdk.AccAddress, msg *wasmvmtypes.StakingMsg) ([]sdk.Msg, error) { - switch { - case msg.Delegate != nil: - coin, err := ConvertWasmCoinToSdkCoin(msg.Delegate.Amount) - if err != nil { - return nil, err - } - sdkMsg := stakingtypes.MsgDelegate{ - DelegatorAddress: sender.String(), - ValidatorAddress: msg.Delegate.Validator, - Amount: coin, - } - return []sdk.Msg{&sdkMsg}, nil - - case msg.Redelegate != nil: - coin, err := ConvertWasmCoinToSdkCoin(msg.Redelegate.Amount) - if err != nil { - return nil, err - } - sdkMsg := stakingtypes.MsgBeginRedelegate{ - DelegatorAddress: sender.String(), - ValidatorSrcAddress: msg.Redelegate.SrcValidator, - ValidatorDstAddress: msg.Redelegate.DstValidator, - Amount: coin, - } - return []sdk.Msg{&sdkMsg}, nil - case msg.Undelegate != nil: - coin, err := ConvertWasmCoinToSdkCoin(msg.Undelegate.Amount) - if err != nil { - return nil, err - } - sdkMsg := stakingtypes.MsgUndelegate{ - DelegatorAddress: sender.String(), - ValidatorAddress: msg.Undelegate.Validator, - Amount: coin, - } - return []sdk.Msg{&sdkMsg}, nil - default: - return nil, errorsmod.Wrap(types.ErrUnknownMsg, "unknown variant of Staking") - } -} - -func EncodeStargateMsg(unpacker codectypes.AnyUnpacker) StargateEncoder { - return func(sender sdk.AccAddress, msg *wasmvmtypes.StargateMsg) ([]sdk.Msg, error) { - codecAny := codectypes.Any{ - TypeUrl: msg.TypeURL, - Value: msg.Value, - } - var sdkMsg sdk.Msg - if err := unpacker.UnpackAny(&codecAny, &sdkMsg); err != nil { - return nil, errorsmod.Wrap(types.ErrInvalidMsg, fmt.Sprintf("Cannot unpack proto message with type URL: %s", msg.TypeURL)) - } - if err := codectypes.UnpackInterfaces(sdkMsg, unpacker); err != nil { - return nil, errorsmod.Wrap(types.ErrInvalidMsg, fmt.Sprintf("UnpackInterfaces inside msg: %s", err)) - } - return []sdk.Msg{sdkMsg}, nil - } -} - -func EncodeWasmMsg(sender sdk.AccAddress, msg *wasmvmtypes.WasmMsg) ([]sdk.Msg, error) { - switch { - case msg.Execute != nil: - coins, err := ConvertWasmCoinsToSdkCoins(msg.Execute.Funds) - if err != nil { - return nil, err - } - - sdkMsg := types.MsgExecuteContract{ - Sender: sender.String(), - Contract: msg.Execute.ContractAddr, - Msg: msg.Execute.Msg, - Funds: coins, - } - return []sdk.Msg{&sdkMsg}, nil - case msg.Instantiate != nil: - coins, err := ConvertWasmCoinsToSdkCoins(msg.Instantiate.Funds) - if err != nil { - return nil, err - } - - sdkMsg := types.MsgInstantiateContract{ - Sender: sender.String(), - CodeID: msg.Instantiate.CodeID, - Label: msg.Instantiate.Label, - Msg: msg.Instantiate.Msg, - Admin: msg.Instantiate.Admin, - Funds: coins, - } - return []sdk.Msg{&sdkMsg}, nil - case msg.Instantiate2 != nil: - coins, err := ConvertWasmCoinsToSdkCoins(msg.Instantiate2.Funds) - if err != nil { - return nil, err - } - - sdkMsg := types.MsgInstantiateContract2{ - Sender: sender.String(), - Admin: msg.Instantiate2.Admin, - CodeID: msg.Instantiate2.CodeID, - Label: msg.Instantiate2.Label, - Msg: msg.Instantiate2.Msg, - Funds: coins, - Salt: msg.Instantiate2.Salt, - // FixMsg is discouraged, see: https://medium.com/cosmwasm/dev-note-3-limitations-of-instantiate2-and-how-to-deal-with-them-a3f946874230 - FixMsg: false, - } - return []sdk.Msg{&sdkMsg}, nil - case msg.Migrate != nil: - sdkMsg := types.MsgMigrateContract{ - Sender: sender.String(), - Contract: msg.Migrate.ContractAddr, - CodeID: msg.Migrate.NewCodeID, - Msg: msg.Migrate.Msg, - } - return []sdk.Msg{&sdkMsg}, nil - case msg.ClearAdmin != nil: - sdkMsg := types.MsgClearAdmin{ - Sender: sender.String(), - Contract: msg.ClearAdmin.ContractAddr, - } - return []sdk.Msg{&sdkMsg}, nil - case msg.UpdateAdmin != nil: - sdkMsg := types.MsgUpdateAdmin{ - Sender: sender.String(), - Contract: msg.UpdateAdmin.ContractAddr, - NewAdmin: msg.UpdateAdmin.Admin, - } - return []sdk.Msg{&sdkMsg}, nil - default: - return nil, errorsmod.Wrap(types.ErrUnknownMsg, "unknown variant of Wasm") - } -} - -func EncodeIBCMsg(portSource types.ICS20TransferPortSource) func(ctx sdk.Context, sender sdk.AccAddress, contractIBCPortID string, msg *wasmvmtypes.IBCMsg) ([]sdk.Msg, error) { - return func(ctx sdk.Context, sender sdk.AccAddress, contractIBCPortID string, msg *wasmvmtypes.IBCMsg) ([]sdk.Msg, error) { - switch { - case msg.CloseChannel != nil: - return []sdk.Msg{&channeltypes.MsgChannelCloseInit{ - PortId: PortIDForContract(sender), - ChannelId: msg.CloseChannel.ChannelID, - Signer: sender.String(), - }}, nil - case msg.Transfer != nil: - amount, err := ConvertWasmCoinToSdkCoin(msg.Transfer.Amount) - if err != nil { - return nil, errorsmod.Wrap(err, "amount") - } - msg := &ibctransfertypes.MsgTransfer{ - SourcePort: portSource.GetPort(ctx), - SourceChannel: msg.Transfer.ChannelID, - Token: amount, - Sender: sender.String(), - Receiver: msg.Transfer.ToAddress, - TimeoutHeight: ConvertWasmIBCTimeoutHeightToCosmosHeight(msg.Transfer.Timeout.Block), - TimeoutTimestamp: msg.Transfer.Timeout.Timestamp, - } - return []sdk.Msg{msg}, nil - default: - return nil, errorsmod.Wrap(types.ErrUnknownMsg, "unknown variant of IBC") - } - } -} - -func EncodeGovMsg(sender sdk.AccAddress, msg *wasmvmtypes.GovMsg) ([]sdk.Msg, error) { - switch { - case msg.Vote != nil: - voteOption, err := convertVoteOption(msg.Vote.Vote) - if err != nil { - return nil, errorsmod.Wrap(err, "vote option") - } - m := v1.NewMsgVote(sender, msg.Vote.ProposalId, voteOption, "") - return []sdk.Msg{m}, nil - case msg.VoteWeighted != nil: - opts := make([]*v1.WeightedVoteOption, len(msg.VoteWeighted.Options)) - for i, v := range msg.VoteWeighted.Options { - weight, err := sdk.NewDecFromStr(v.Weight) - if err != nil { - return nil, errorsmod.Wrapf(err, "weight for vote %d", i+1) - } - voteOption, err := convertVoteOption(v.Option) - if err != nil { - return nil, errorsmod.Wrap(err, "vote option") - } - opts[i] = &v1.WeightedVoteOption{Option: voteOption, Weight: weight.String()} - } - m := v1.NewMsgVoteWeighted(sender, msg.VoteWeighted.ProposalId, opts, "") - return []sdk.Msg{m}, nil - - default: - return nil, types.ErrUnknownMsg.Wrap("unknown variant of gov") - } -} - -func convertVoteOption(s interface{}) (v1.VoteOption, error) { - var option v1.VoteOption - switch s { - case wasmvmtypes.Yes: - option = v1.OptionYes - case wasmvmtypes.No: - option = v1.OptionNo - case wasmvmtypes.NoWithVeto: - option = v1.OptionNoWithVeto - case wasmvmtypes.Abstain: - option = v1.OptionAbstain - default: - return v1.OptionEmpty, types.ErrInvalid - } - return option, nil -} - -// ConvertWasmIBCTimeoutHeightToCosmosHeight converts a wasmvm type ibc timeout height to ibc module type height -func ConvertWasmIBCTimeoutHeightToCosmosHeight(ibcTimeoutBlock *wasmvmtypes.IBCTimeoutBlock) ibcclienttypes.Height { - if ibcTimeoutBlock == nil { - return ibcclienttypes.NewHeight(0, 0) - } - return ibcclienttypes.NewHeight(ibcTimeoutBlock.Revision, ibcTimeoutBlock.Height) -} - -// ConvertWasmCoinsToSdkCoins converts the wasm vm type coins to sdk type coins -func ConvertWasmCoinsToSdkCoins(coins []wasmvmtypes.Coin) (sdk.Coins, error) { - var toSend sdk.Coins - for _, coin := range coins { - c, err := ConvertWasmCoinToSdkCoin(coin) - if err != nil { - return nil, err - } - toSend = toSend.Add(c) - } - return toSend.Sort(), nil -} - -// ConvertWasmCoinToSdkCoin converts a wasm vm type coin to sdk type coin -func ConvertWasmCoinToSdkCoin(coin wasmvmtypes.Coin) (sdk.Coin, error) { - amount, ok := sdk.NewIntFromString(coin.Amount) - if !ok { - return sdk.Coin{}, errorsmod.Wrap(sdkerrors.ErrInvalidCoins, coin.Amount+coin.Denom) - } - r := sdk.Coin{ - Denom: coin.Denom, - Amount: amount, - } - return r, r.Validate() -} diff --git a/x/wasm/keeper/handler_plugin_encoders_test.go b/x/wasm/keeper/handler_plugin_encoders_test.go deleted file mode 100644 index 9d19721..0000000 --- a/x/wasm/keeper/handler_plugin_encoders_test.go +++ /dev/null @@ -1,933 +0,0 @@ -package keeper - -import ( - "testing" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/cosmos/gogoproto/proto" - ibctransfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" - clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/keeper/wasmtesting" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestEncoding(t *testing.T) { - var ( - addr1 = RandomAccountAddress(t) - addr2 = RandomAccountAddress(t) - addr3 = RandomAccountAddress(t) - invalidAddr = "xrnd1d02kd90n38qvr3qb9qof83fn2d2" - ) - valAddr := make(sdk.ValAddress, types.SDKAddrLen) - valAddr[0] = 12 - valAddr2 := make(sdk.ValAddress, types.SDKAddrLen) - valAddr2[1] = 123 - - jsonMsg := types.RawContractMessage(`{"foo": 123}`) - - bankMsg := &banktypes.MsgSend{ - FromAddress: addr2.String(), - ToAddress: addr1.String(), - Amount: sdk.Coins{ - sdk.NewInt64Coin("uatom", 12345), - sdk.NewInt64Coin("utgd", 54321), - }, - } - bankMsgBin, err := proto.Marshal(bankMsg) - require.NoError(t, err) - - content, err := codectypes.NewAnyWithValue(types.StoreCodeProposalFixture()) - require.NoError(t, err) - - proposalMsg := &v1beta1.MsgSubmitProposal{ - Proposer: addr1.String(), - InitialDeposit: sdk.NewCoins(sdk.NewInt64Coin("uatom", 12345)), - Content: content, - } - proposalMsgBin, err := proto.Marshal(proposalMsg) - require.NoError(t, err) - - cases := map[string]struct { - sender sdk.AccAddress - srcMsg wasmvmtypes.CosmosMsg - srcContractIBCPort string - transferPortSource types.ICS20TransferPortSource - // set if valid - output []sdk.Msg - // set if expect mapping fails - expError bool - // set if sdk validate basic should fail - expInvalid bool - }{ - "simple send": { - sender: addr1, - srcMsg: wasmvmtypes.CosmosMsg{ - Bank: &wasmvmtypes.BankMsg{ - Send: &wasmvmtypes.SendMsg{ - ToAddress: addr2.String(), - Amount: []wasmvmtypes.Coin{ - { - Denom: "uatom", - Amount: "12345", - }, - { - Denom: "usdt", - Amount: "54321", - }, - }, - }, - }, - }, - output: []sdk.Msg{ - &banktypes.MsgSend{ - FromAddress: addr1.String(), - ToAddress: addr2.String(), - Amount: sdk.Coins{ - sdk.NewInt64Coin("uatom", 12345), - sdk.NewInt64Coin("usdt", 54321), - }, - }, - }, - }, - "invalid send amount": { - sender: addr1, - srcMsg: wasmvmtypes.CosmosMsg{ - Bank: &wasmvmtypes.BankMsg{ - Send: &wasmvmtypes.SendMsg{ - ToAddress: addr2.String(), - Amount: []wasmvmtypes.Coin{ - { - Denom: "uatom", - Amount: "123.456", - }, - }, - }, - }, - }, - expError: true, - }, - "invalid address": { - sender: addr1, - srcMsg: wasmvmtypes.CosmosMsg{ - Bank: &wasmvmtypes.BankMsg{ - Send: &wasmvmtypes.SendMsg{ - ToAddress: invalidAddr, - Amount: []wasmvmtypes.Coin{ - { - Denom: "uatom", - Amount: "7890", - }, - }, - }, - }, - }, - expError: false, // addresses are checked in the handler - expInvalid: true, - output: []sdk.Msg{ - &banktypes.MsgSend{ - FromAddress: addr1.String(), - ToAddress: invalidAddr, - Amount: sdk.Coins{ - sdk.NewInt64Coin("uatom", 7890), - }, - }, - }, - }, - "wasm execute": { - sender: addr1, - srcMsg: wasmvmtypes.CosmosMsg{ - Wasm: &wasmvmtypes.WasmMsg{ - Execute: &wasmvmtypes.ExecuteMsg{ - ContractAddr: addr2.String(), - Msg: jsonMsg, - Funds: []wasmvmtypes.Coin{ - wasmvmtypes.NewCoin(12, "eth"), - }, - }, - }, - }, - output: []sdk.Msg{ - &types.MsgExecuteContract{ - Sender: addr1.String(), - Contract: addr2.String(), - Msg: jsonMsg, - Funds: sdk.NewCoins(sdk.NewInt64Coin("eth", 12)), - }, - }, - }, - "wasm instantiate": { - sender: addr1, - srcMsg: wasmvmtypes.CosmosMsg{ - Wasm: &wasmvmtypes.WasmMsg{ - Instantiate: &wasmvmtypes.InstantiateMsg{ - CodeID: 7, - Msg: jsonMsg, - Funds: []wasmvmtypes.Coin{ - wasmvmtypes.NewCoin(123, "eth"), - }, - Label: "myLabel", - Admin: addr2.String(), - }, - }, - }, - output: []sdk.Msg{ - &types.MsgInstantiateContract{ - Sender: addr1.String(), - CodeID: 7, - Label: "myLabel", - Msg: jsonMsg, - Funds: sdk.NewCoins(sdk.NewInt64Coin("eth", 123)), - Admin: addr2.String(), - }, - }, - }, - "wasm instantiate2": { - sender: addr1, - srcMsg: wasmvmtypes.CosmosMsg{ - Wasm: &wasmvmtypes.WasmMsg{ - Instantiate2: &wasmvmtypes.Instantiate2Msg{ - CodeID: 7, - Msg: jsonMsg, - Funds: []wasmvmtypes.Coin{ - wasmvmtypes.NewCoin(123, "eth"), - }, - Label: "myLabel", - Admin: addr2.String(), - Salt: []byte("mySalt"), - }, - }, - }, - output: []sdk.Msg{ - &types.MsgInstantiateContract2{ - Sender: addr1.String(), - Admin: addr2.String(), - CodeID: 7, - Label: "myLabel", - Msg: jsonMsg, - Funds: sdk.NewCoins(sdk.NewInt64Coin("eth", 123)), - Salt: []byte("mySalt"), - FixMsg: false, - }, - }, - }, - "wasm migrate": { - sender: addr2, - srcMsg: wasmvmtypes.CosmosMsg{ - Wasm: &wasmvmtypes.WasmMsg{ - Migrate: &wasmvmtypes.MigrateMsg{ - ContractAddr: addr1.String(), - NewCodeID: 12, - Msg: jsonMsg, - }, - }, - }, - output: []sdk.Msg{ - &types.MsgMigrateContract{ - Sender: addr2.String(), - Contract: addr1.String(), - CodeID: 12, - Msg: jsonMsg, - }, - }, - }, - "wasm update admin": { - sender: addr2, - srcMsg: wasmvmtypes.CosmosMsg{ - Wasm: &wasmvmtypes.WasmMsg{ - UpdateAdmin: &wasmvmtypes.UpdateAdminMsg{ - ContractAddr: addr1.String(), - Admin: addr3.String(), - }, - }, - }, - output: []sdk.Msg{ - &types.MsgUpdateAdmin{ - Sender: addr2.String(), - Contract: addr1.String(), - NewAdmin: addr3.String(), - }, - }, - }, - "wasm clear admin": { - sender: addr2, - srcMsg: wasmvmtypes.CosmosMsg{ - Wasm: &wasmvmtypes.WasmMsg{ - ClearAdmin: &wasmvmtypes.ClearAdminMsg{ - ContractAddr: addr1.String(), - }, - }, - }, - output: []sdk.Msg{ - &types.MsgClearAdmin{ - Sender: addr2.String(), - Contract: addr1.String(), - }, - }, - }, - "staking delegate": { - sender: addr1, - srcMsg: wasmvmtypes.CosmosMsg{ - Staking: &wasmvmtypes.StakingMsg{ - Delegate: &wasmvmtypes.DelegateMsg{ - Validator: valAddr.String(), - Amount: wasmvmtypes.NewCoin(777, "stake"), - }, - }, - }, - output: []sdk.Msg{ - &stakingtypes.MsgDelegate{ - DelegatorAddress: addr1.String(), - ValidatorAddress: valAddr.String(), - Amount: sdk.NewInt64Coin("stake", 777), - }, - }, - }, - "staking delegate to non-validator": { - sender: addr1, - srcMsg: wasmvmtypes.CosmosMsg{ - Staking: &wasmvmtypes.StakingMsg{ - Delegate: &wasmvmtypes.DelegateMsg{ - Validator: addr2.String(), - Amount: wasmvmtypes.NewCoin(777, "stake"), - }, - }, - }, - expError: false, // fails in the handler - expInvalid: true, - output: []sdk.Msg{ - &stakingtypes.MsgDelegate{ - DelegatorAddress: addr1.String(), - ValidatorAddress: addr2.String(), - Amount: sdk.NewInt64Coin("stake", 777), - }, - }, - }, - "staking undelegate": { - sender: addr1, - srcMsg: wasmvmtypes.CosmosMsg{ - Staking: &wasmvmtypes.StakingMsg{ - Undelegate: &wasmvmtypes.UndelegateMsg{ - Validator: valAddr.String(), - Amount: wasmvmtypes.NewCoin(555, "stake"), - }, - }, - }, - output: []sdk.Msg{ - &stakingtypes.MsgUndelegate{ - DelegatorAddress: addr1.String(), - ValidatorAddress: valAddr.String(), - Amount: sdk.NewInt64Coin("stake", 555), - }, - }, - }, - "staking redelegate": { - sender: addr1, - srcMsg: wasmvmtypes.CosmosMsg{ - Staking: &wasmvmtypes.StakingMsg{ - Redelegate: &wasmvmtypes.RedelegateMsg{ - SrcValidator: valAddr.String(), - DstValidator: valAddr2.String(), - Amount: wasmvmtypes.NewCoin(222, "stake"), - }, - }, - }, - output: []sdk.Msg{ - &stakingtypes.MsgBeginRedelegate{ - DelegatorAddress: addr1.String(), - ValidatorSrcAddress: valAddr.String(), - ValidatorDstAddress: valAddr2.String(), - Amount: sdk.NewInt64Coin("stake", 222), - }, - }, - }, - "staking withdraw (explicit recipient)": { - sender: addr1, - srcMsg: wasmvmtypes.CosmosMsg{ - Distribution: &wasmvmtypes.DistributionMsg{ - WithdrawDelegatorReward: &wasmvmtypes.WithdrawDelegatorRewardMsg{ - Validator: valAddr2.String(), - }, - }, - }, - output: []sdk.Msg{ - &distributiontypes.MsgWithdrawDelegatorReward{ - DelegatorAddress: addr1.String(), - ValidatorAddress: valAddr2.String(), - }, - }, - }, - "staking set withdraw address": { - sender: addr1, - srcMsg: wasmvmtypes.CosmosMsg{ - Distribution: &wasmvmtypes.DistributionMsg{ - SetWithdrawAddress: &wasmvmtypes.SetWithdrawAddressMsg{ - Address: addr2.String(), - }, - }, - }, - output: []sdk.Msg{ - &distributiontypes.MsgSetWithdrawAddress{ - DelegatorAddress: addr1.String(), - WithdrawAddress: addr2.String(), - }, - }, - }, - "stargate encoded bank msg": { - sender: addr2, - srcMsg: wasmvmtypes.CosmosMsg{ - Stargate: &wasmvmtypes.StargateMsg{ - TypeURL: "/cosmos.bank.v1beta1.MsgSend", - Value: bankMsgBin, - }, - }, - output: []sdk.Msg{bankMsg}, - }, - "stargate encoded msg with any type": { - sender: addr2, - srcMsg: wasmvmtypes.CosmosMsg{ - Stargate: &wasmvmtypes.StargateMsg{ - TypeURL: "/cosmos.gov.v1beta1.MsgSubmitProposal", - Value: proposalMsgBin, - }, - }, - output: []sdk.Msg{proposalMsg}, - }, - "stargate encoded invalid typeUrl": { - sender: addr2, - srcMsg: wasmvmtypes.CosmosMsg{ - Stargate: &wasmvmtypes.StargateMsg{ - TypeURL: "/cosmos.bank.v2.MsgSend", - Value: bankMsgBin, - }, - }, - expError: true, - }, - "IBC transfer with block timeout": { - sender: addr1, - srcContractIBCPort: "myIBCPort", - srcMsg: wasmvmtypes.CosmosMsg{ - IBC: &wasmvmtypes.IBCMsg{ - Transfer: &wasmvmtypes.TransferMsg{ - ChannelID: "myChanID", - ToAddress: addr2.String(), - Amount: wasmvmtypes.Coin{ - Denom: "ALX", - Amount: "1", - }, - Timeout: wasmvmtypes.IBCTimeout{ - Block: &wasmvmtypes.IBCTimeoutBlock{Revision: 1, Height: 2}, - }, - }, - }, - }, - transferPortSource: wasmtesting.MockIBCTransferKeeper{GetPortFn: func(ctx sdk.Context) string { - return "myTransferPort" - }}, - output: []sdk.Msg{ - &ibctransfertypes.MsgTransfer{ - SourcePort: "myTransferPort", - SourceChannel: "myChanID", - Token: sdk.Coin{ - Denom: "ALX", - Amount: sdk.NewInt(1), - }, - Sender: addr1.String(), - Receiver: addr2.String(), - TimeoutHeight: clienttypes.Height{RevisionNumber: 1, RevisionHeight: 2}, - }, - }, - }, - "IBC transfer with time timeout": { - sender: addr1, - srcContractIBCPort: "myIBCPort", - srcMsg: wasmvmtypes.CosmosMsg{ - IBC: &wasmvmtypes.IBCMsg{ - Transfer: &wasmvmtypes.TransferMsg{ - ChannelID: "myChanID", - ToAddress: addr2.String(), - Amount: wasmvmtypes.Coin{ - Denom: "ALX", - Amount: "1", - }, - Timeout: wasmvmtypes.IBCTimeout{Timestamp: 100}, - }, - }, - }, - transferPortSource: wasmtesting.MockIBCTransferKeeper{GetPortFn: func(ctx sdk.Context) string { - return "transfer" - }}, - output: []sdk.Msg{ - &ibctransfertypes.MsgTransfer{ - SourcePort: "transfer", - SourceChannel: "myChanID", - Token: sdk.Coin{ - Denom: "ALX", - Amount: sdk.NewInt(1), - }, - Sender: addr1.String(), - Receiver: addr2.String(), - TimeoutTimestamp: 100, - }, - }, - }, - "IBC transfer with time and height timeout": { - sender: addr1, - srcContractIBCPort: "myIBCPort", - srcMsg: wasmvmtypes.CosmosMsg{ - IBC: &wasmvmtypes.IBCMsg{ - Transfer: &wasmvmtypes.TransferMsg{ - ChannelID: "myChanID", - ToAddress: addr2.String(), - Amount: wasmvmtypes.Coin{ - Denom: "ALX", - Amount: "1", - }, - Timeout: wasmvmtypes.IBCTimeout{Timestamp: 100, Block: &wasmvmtypes.IBCTimeoutBlock{Height: 1, Revision: 2}}, - }, - }, - }, - transferPortSource: wasmtesting.MockIBCTransferKeeper{GetPortFn: func(ctx sdk.Context) string { - return "transfer" - }}, - output: []sdk.Msg{ - &ibctransfertypes.MsgTransfer{ - SourcePort: "transfer", - SourceChannel: "myChanID", - Token: sdk.Coin{ - Denom: "ALX", - Amount: sdk.NewInt(1), - }, - Sender: addr1.String(), - Receiver: addr2.String(), - TimeoutTimestamp: 100, - TimeoutHeight: clienttypes.NewHeight(2, 1), - }, - }, - }, - "IBC close channel": { - sender: addr1, - srcContractIBCPort: "myIBCPort", - srcMsg: wasmvmtypes.CosmosMsg{ - IBC: &wasmvmtypes.IBCMsg{ - CloseChannel: &wasmvmtypes.CloseChannelMsg{ - ChannelID: "channel-1", - }, - }, - }, - output: []sdk.Msg{ - &channeltypes.MsgChannelCloseInit{ - PortId: "wasm." + addr1.String(), - ChannelId: "channel-1", - Signer: addr1.String(), - }, - }, - }, - } - encodingConfig := MakeEncodingConfig(t) - for name, tc := range cases { - t.Run(name, func(t *testing.T) { - var ctx sdk.Context - encoder := DefaultEncoders(encodingConfig.Marshaler, tc.transferPortSource) - res, err := encoder.Encode(ctx, tc.sender, tc.srcContractIBCPort, tc.srcMsg) - if tc.expError { - assert.Error(t, err) - return - } - require.NoError(t, err) - assert.Equal(t, tc.output, res) - - // and valid sdk message - for _, v := range res { - gotErr := v.ValidateBasic() - if tc.expInvalid { - assert.Error(t, gotErr) - } else { - assert.NoError(t, gotErr) - } - } - }) - } -} - -func TestEncodeGovMsg(t *testing.T) { - myAddr := RandomAccountAddress(t) - - cases := map[string]struct { - sender sdk.AccAddress - srcMsg wasmvmtypes.CosmosMsg - transferPortSource types.ICS20TransferPortSource - // set if valid - output []sdk.Msg - // set if expect mapping fails - expError bool - // set if sdk validate basic should fail - expInvalid bool - }{ - "Gov vote: yes": { - sender: myAddr, - srcMsg: wasmvmtypes.CosmosMsg{ - Gov: &wasmvmtypes.GovMsg{ - Vote: &wasmvmtypes.VoteMsg{ProposalId: 1, Vote: wasmvmtypes.Yes}, - }, - }, - output: []sdk.Msg{ - &v1.MsgVote{ - ProposalId: 1, - Voter: myAddr.String(), - Option: v1.OptionYes, - }, - }, - }, - "Gov vote: No": { - sender: myAddr, - srcMsg: wasmvmtypes.CosmosMsg{ - Gov: &wasmvmtypes.GovMsg{ - Vote: &wasmvmtypes.VoteMsg{ProposalId: 1, Vote: wasmvmtypes.No}, - }, - }, - output: []sdk.Msg{ - &v1.MsgVote{ - ProposalId: 1, - Voter: myAddr.String(), - Option: v1.OptionNo, - }, - }, - }, - "Gov vote: Abstain": { - sender: myAddr, - srcMsg: wasmvmtypes.CosmosMsg{ - Gov: &wasmvmtypes.GovMsg{ - Vote: &wasmvmtypes.VoteMsg{ProposalId: 10, Vote: wasmvmtypes.Abstain}, - }, - }, - output: []sdk.Msg{ - &v1.MsgVote{ - ProposalId: 10, - Voter: myAddr.String(), - Option: v1.OptionAbstain, - }, - }, - }, - "Gov vote: No with veto": { - sender: myAddr, - srcMsg: wasmvmtypes.CosmosMsg{ - Gov: &wasmvmtypes.GovMsg{ - Vote: &wasmvmtypes.VoteMsg{ProposalId: 1, Vote: wasmvmtypes.NoWithVeto}, - }, - }, - output: []sdk.Msg{ - &v1.MsgVote{ - ProposalId: 1, - Voter: myAddr.String(), - Option: v1.OptionNoWithVeto, - }, - }, - }, - "Gov vote: unset option": { - sender: myAddr, - srcMsg: wasmvmtypes.CosmosMsg{ - Gov: &wasmvmtypes.GovMsg{ - Vote: &wasmvmtypes.VoteMsg{ProposalId: 1}, - }, - }, - expError: true, - }, - "Gov weighted vote: single vote": { - sender: myAddr, - srcMsg: wasmvmtypes.CosmosMsg{ - Gov: &wasmvmtypes.GovMsg{ - VoteWeighted: &wasmvmtypes.VoteWeightedMsg{ - ProposalId: 1, - Options: []wasmvmtypes.WeightedVoteOption{ - {Option: wasmvmtypes.Yes, Weight: "1"}, - }, - }, - }, - }, - output: []sdk.Msg{ - &v1.MsgVoteWeighted{ - ProposalId: 1, - Voter: myAddr.String(), - Options: []*v1.WeightedVoteOption{ - {Option: v1.OptionYes, Weight: sdk.NewDec(1).String()}, - }, - }, - }, - }, - "Gov weighted vote: splitted": { - sender: myAddr, - srcMsg: wasmvmtypes.CosmosMsg{ - Gov: &wasmvmtypes.GovMsg{ - VoteWeighted: &wasmvmtypes.VoteWeightedMsg{ - ProposalId: 1, - Options: []wasmvmtypes.WeightedVoteOption{ - {Option: wasmvmtypes.Yes, Weight: "0.23"}, - {Option: wasmvmtypes.No, Weight: "0.24"}, - {Option: wasmvmtypes.Abstain, Weight: "0.26"}, - {Option: wasmvmtypes.NoWithVeto, Weight: "0.27"}, - }, - }, - }, - }, - output: []sdk.Msg{ - &v1.MsgVoteWeighted{ - ProposalId: 1, - Voter: myAddr.String(), - Options: []*v1.WeightedVoteOption{ - {Option: v1.OptionYes, Weight: sdk.NewDecWithPrec(23, 2).String()}, - {Option: v1.OptionNo, Weight: sdk.NewDecWithPrec(24, 2).String()}, - {Option: v1.OptionAbstain, Weight: sdk.NewDecWithPrec(26, 2).String()}, - {Option: v1.OptionNoWithVeto, Weight: sdk.NewDecWithPrec(27, 2).String()}, - }, - }, - }, - }, - "Gov weighted vote: duplicate option": { - sender: myAddr, - srcMsg: wasmvmtypes.CosmosMsg{ - Gov: &wasmvmtypes.GovMsg{ - VoteWeighted: &wasmvmtypes.VoteWeightedMsg{ - ProposalId: 1, - Options: []wasmvmtypes.WeightedVoteOption{ - {Option: wasmvmtypes.Yes, Weight: "0.5"}, - {Option: wasmvmtypes.Yes, Weight: "0.5"}, - }, - }, - }, - }, - output: []sdk.Msg{ - &v1.MsgVoteWeighted{ - ProposalId: 1, - Voter: myAddr.String(), - Options: []*v1.WeightedVoteOption{ - {Option: v1.OptionYes, Weight: sdk.NewDecWithPrec(5, 1).String()}, - {Option: v1.OptionYes, Weight: sdk.NewDecWithPrec(5, 1).String()}, - }, - }, - }, - expInvalid: true, - }, - "Gov weighted vote: weight sum exceeds 1": { - sender: myAddr, - srcMsg: wasmvmtypes.CosmosMsg{ - Gov: &wasmvmtypes.GovMsg{ - VoteWeighted: &wasmvmtypes.VoteWeightedMsg{ - ProposalId: 1, - Options: []wasmvmtypes.WeightedVoteOption{ - {Option: wasmvmtypes.Yes, Weight: "0.51"}, - {Option: wasmvmtypes.No, Weight: "0.5"}, - }, - }, - }, - }, - output: []sdk.Msg{ - &v1.MsgVoteWeighted{ - ProposalId: 1, - Voter: myAddr.String(), - Options: []*v1.WeightedVoteOption{ - {Option: v1.OptionYes, Weight: sdk.NewDecWithPrec(51, 2).String()}, - {Option: v1.OptionNo, Weight: sdk.NewDecWithPrec(5, 1).String()}, - }, - }, - }, - expInvalid: true, - }, - "Gov weighted vote: weight sum less than 1": { - sender: myAddr, - srcMsg: wasmvmtypes.CosmosMsg{ - Gov: &wasmvmtypes.GovMsg{ - VoteWeighted: &wasmvmtypes.VoteWeightedMsg{ - ProposalId: 1, - Options: []wasmvmtypes.WeightedVoteOption{ - {Option: wasmvmtypes.Yes, Weight: "0.49"}, - {Option: wasmvmtypes.No, Weight: "0.5"}, - }, - }, - }, - }, - output: []sdk.Msg{ - &v1.MsgVoteWeighted{ - ProposalId: 1, - Voter: myAddr.String(), - Options: []*v1.WeightedVoteOption{ - {Option: v1.OptionYes, Weight: sdk.NewDecWithPrec(49, 2).String()}, - {Option: v1.OptionNo, Weight: sdk.NewDecWithPrec(5, 1).String()}, - }, - }, - }, - expInvalid: true, - }, - } - encodingConfig := MakeEncodingConfig(t) - for name, tc := range cases { - t.Run(name, func(t *testing.T) { - var ctx sdk.Context - encoder := DefaultEncoders(encodingConfig.Marshaler, tc.transferPortSource) - res, gotEncErr := encoder.Encode(ctx, tc.sender, "myIBCPort", tc.srcMsg) - if tc.expError { - assert.Error(t, gotEncErr) - return - } - require.NoError(t, gotEncErr) - assert.Equal(t, tc.output, res) - - // and valid sdk message - for _, v := range res { - gotErr := v.ValidateBasic() - if tc.expInvalid { - assert.Error(t, gotErr) - } else { - assert.NoError(t, gotErr) - } - } - }) - } -} - -func TestConvertWasmCoinToSdkCoin(t *testing.T) { - specs := map[string]struct { - src wasmvmtypes.Coin - expErr bool - expVal sdk.Coin - }{ - "all good": { - src: wasmvmtypes.Coin{ - Denom: "foo", - Amount: "1", - }, - expVal: sdk.NewCoin("foo", sdk.NewIntFromUint64(1)), - }, - "negative amount": { - src: wasmvmtypes.Coin{ - Denom: "foo", - Amount: "-1", - }, - expErr: true, - }, - "denom to short": { - src: wasmvmtypes.Coin{ - Denom: "f", - Amount: "1", - }, - expErr: true, - }, - "invalid demum char": { - src: wasmvmtypes.Coin{ - Denom: "&fff", - Amount: "1", - }, - expErr: true, - }, - "not a number amount": { - src: wasmvmtypes.Coin{ - Denom: "foo", - Amount: "bar", - }, - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - gotVal, gotErr := ConvertWasmCoinToSdkCoin(spec.src) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - assert.Equal(t, spec.expVal, gotVal) - }) - } -} - -func TestConvertWasmCoinsToSdkCoins(t *testing.T) { - specs := map[string]struct { - src []wasmvmtypes.Coin - exp sdk.Coins - expErr bool - }{ - "empty": { - src: []wasmvmtypes.Coin{}, - exp: nil, - }, - "single coin": { - src: []wasmvmtypes.Coin{{Denom: "foo", Amount: "1"}}, - exp: sdk.NewCoins(sdk.NewCoin("foo", sdk.NewInt(1))), - }, - "multiple coins": { - src: []wasmvmtypes.Coin{ - {Denom: "foo", Amount: "1"}, - {Denom: "bar", Amount: "2"}, - }, - exp: sdk.NewCoins( - sdk.NewCoin("bar", sdk.NewInt(2)), - sdk.NewCoin("foo", sdk.NewInt(1)), - ), - }, - "sorted": { - src: []wasmvmtypes.Coin{ - {Denom: "foo", Amount: "1"}, - {Denom: "other", Amount: "1"}, - {Denom: "bar", Amount: "1"}, - }, - exp: []sdk.Coin{ - sdk.NewCoin("bar", sdk.NewInt(1)), - sdk.NewCoin("foo", sdk.NewInt(1)), - sdk.NewCoin("other", sdk.NewInt(1)), - }, - }, - "zero amounts dropped": { - src: []wasmvmtypes.Coin{ - {Denom: "foo", Amount: "1"}, - {Denom: "bar", Amount: "0"}, - }, - exp: sdk.NewCoins( - sdk.NewCoin("foo", sdk.NewInt(1)), - ), - }, - "duplicate denoms merged": { - src: []wasmvmtypes.Coin{ - {Denom: "foo", Amount: "1"}, - {Denom: "foo", Amount: "1"}, - }, - exp: []sdk.Coin{sdk.NewCoin("foo", sdk.NewInt(2))}, - }, - "duplicate denoms with one 0 amount does not fail": { - src: []wasmvmtypes.Coin{ - {Denom: "foo", Amount: "0"}, - {Denom: "foo", Amount: "1"}, - }, - exp: []sdk.Coin{sdk.NewCoin("foo", sdk.NewInt(1))}, - }, - "empty denom rejected": { - src: []wasmvmtypes.Coin{{Denom: "", Amount: "1"}}, - expErr: true, - }, - "invalid denom rejected": { - src: []wasmvmtypes.Coin{{Denom: "!%&", Amount: "1"}}, - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - gotCoins, gotErr := ConvertWasmCoinsToSdkCoins(spec.src) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - assert.Equal(t, spec.exp, gotCoins) - assert.NoError(t, gotCoins.Validate()) - }) - } -} diff --git a/x/wasm/keeper/handler_plugin_test.go b/x/wasm/keeper/handler_plugin_test.go deleted file mode 100644 index 42cc810..0000000 --- a/x/wasm/keeper/handler_plugin_test.go +++ /dev/null @@ -1,415 +0,0 @@ -package keeper - -import ( - "encoding/json" - "testing" - - errorsmod "cosmossdk.io/errors" - "github.com/cometbft/cometbft/libs/log" - - wasmvm "github.com/CosmWasm/wasmvm" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/cosmos/cosmos-sdk/baseapp" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" - clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/keeper/wasmtesting" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestMessageHandlerChainDispatch(t *testing.T) { - capturingHandler, gotMsgs := wasmtesting.NewCapturingMessageHandler() - - alwaysUnknownMsgHandler := &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - return nil, nil, types.ErrUnknownMsg - }, - } - - assertNotCalledHandler := &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - t.Fatal("not expected to be called") - return - }, - } - - myMsg := wasmvmtypes.CosmosMsg{Custom: []byte(`{}`)} - specs := map[string]struct { - handlers []Messenger - expErr *errorsmod.Error - expEvents []sdk.Event - }{ - "single handler": { - handlers: []Messenger{capturingHandler}, - }, - "passed to next handler": { - handlers: []Messenger{alwaysUnknownMsgHandler, capturingHandler}, - }, - "stops iteration when handled": { - handlers: []Messenger{capturingHandler, assertNotCalledHandler}, - }, - "stops iteration on handler error": { - handlers: []Messenger{&wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - return nil, nil, types.ErrInvalidMsg - }, - }, assertNotCalledHandler}, - expErr: types.ErrInvalidMsg, - }, - "return events when handle": { - handlers: []Messenger{ - &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - _, data, _ = capturingHandler.DispatchMsg(ctx, contractAddr, contractIBCPortID, msg) - return []sdk.Event{sdk.NewEvent("myEvent", sdk.NewAttribute("foo", "bar"))}, data, nil - }, - }, - }, - expEvents: []sdk.Event{sdk.NewEvent("myEvent", sdk.NewAttribute("foo", "bar"))}, - }, - "return error when none can handle": { - handlers: []Messenger{alwaysUnknownMsgHandler}, - expErr: types.ErrUnknownMsg, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - *gotMsgs = make([]wasmvmtypes.CosmosMsg, 0) - - // when - h := MessageHandlerChain{spec.handlers} - gotEvents, gotData, gotErr := h.DispatchMsg(sdk.Context{}, RandomAccountAddress(t), "anyPort", myMsg) - - // then - require.True(t, spec.expErr.Is(gotErr), "exp %v but got %#+v", spec.expErr, gotErr) - if spec.expErr != nil { - return - } - assert.Equal(t, []wasmvmtypes.CosmosMsg{myMsg}, *gotMsgs) - assert.Equal(t, [][]byte{{1}}, gotData) // {1} is default in capturing handler - assert.Equal(t, spec.expEvents, gotEvents) - }) - } -} - -func TestSDKMessageHandlerDispatch(t *testing.T) { - myEvent := sdk.NewEvent("myEvent", sdk.NewAttribute("foo", "bar")) - const myData = "myData" - myRouterResult := sdk.Result{ - Data: []byte(myData), - Events: sdk.Events{myEvent}.ToABCIEvents(), - } - - var gotMsg []sdk.Msg - capturingMessageRouter := wasmtesting.MessageRouterFunc(func(msg sdk.Msg) baseapp.MsgServiceHandler { - return func(ctx sdk.Context, req sdk.Msg) (*sdk.Result, error) { - gotMsg = append(gotMsg, msg) - return &myRouterResult, nil - } - }) - noRouteMessageRouter := wasmtesting.MessageRouterFunc(func(msg sdk.Msg) baseapp.MsgServiceHandler { - return nil - }) - myContractAddr := RandomAccountAddress(t) - myContractMessage := wasmvmtypes.CosmosMsg{Custom: []byte("{}")} - - specs := map[string]struct { - srcRoute MessageRouter - srcEncoder CustomEncoder - expErr *errorsmod.Error - expMsgDispatched int - }{ - "all good": { - srcRoute: capturingMessageRouter, - srcEncoder: func(sender sdk.AccAddress, msg json.RawMessage) ([]sdk.Msg, error) { - myMsg := types.MsgExecuteContract{ - Sender: myContractAddr.String(), - Contract: RandomBech32AccountAddress(t), - Msg: []byte("{}"), - } - return []sdk.Msg{&myMsg}, nil - }, - expMsgDispatched: 1, - }, - "multiple output msgs": { - srcRoute: capturingMessageRouter, - srcEncoder: func(sender sdk.AccAddress, msg json.RawMessage) ([]sdk.Msg, error) { - first := &types.MsgExecuteContract{ - Sender: myContractAddr.String(), - Contract: RandomBech32AccountAddress(t), - Msg: []byte("{}"), - } - second := &types.MsgExecuteContract{ - Sender: myContractAddr.String(), - Contract: RandomBech32AccountAddress(t), - Msg: []byte("{}"), - } - return []sdk.Msg{first, second}, nil - }, - expMsgDispatched: 2, - }, - "invalid sdk message rejected": { - srcRoute: capturingMessageRouter, - srcEncoder: func(sender sdk.AccAddress, msg json.RawMessage) ([]sdk.Msg, error) { - invalidMsg := types.MsgExecuteContract{ - Sender: myContractAddr.String(), - Contract: RandomBech32AccountAddress(t), - Msg: []byte("INVALID_JSON"), - } - return []sdk.Msg{&invalidMsg}, nil - }, - expErr: types.ErrInvalid, - }, - "invalid sender rejected": { - srcRoute: capturingMessageRouter, - srcEncoder: func(sender sdk.AccAddress, msg json.RawMessage) ([]sdk.Msg, error) { - invalidMsg := types.MsgExecuteContract{ - Sender: RandomBech32AccountAddress(t), - Contract: RandomBech32AccountAddress(t), - Msg: []byte("{}"), - } - return []sdk.Msg{&invalidMsg}, nil - }, - expErr: sdkerrors.ErrUnauthorized, - }, - "unroutable message rejected": { - srcRoute: noRouteMessageRouter, - srcEncoder: func(sender sdk.AccAddress, msg json.RawMessage) ([]sdk.Msg, error) { - myMsg := types.MsgExecuteContract{ - Sender: myContractAddr.String(), - Contract: RandomBech32AccountAddress(t), - Msg: []byte("{}"), - } - return []sdk.Msg{&myMsg}, nil - }, - expErr: sdkerrors.ErrUnknownRequest, - }, - "encoding error passed": { - srcRoute: capturingMessageRouter, - srcEncoder: func(sender sdk.AccAddress, msg json.RawMessage) ([]sdk.Msg, error) { - myErr := types.ErrUnpinContractFailed // any error that is not used - return nil, myErr - }, - expErr: types.ErrUnpinContractFailed, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - gotMsg = make([]sdk.Msg, 0) - - // when - ctx := sdk.Context{} - h := NewSDKMessageHandler(spec.srcRoute, MessageEncoders{Custom: spec.srcEncoder}) - gotEvents, gotData, gotErr := h.DispatchMsg(ctx, myContractAddr, "myPort", myContractMessage) - - // then - require.True(t, spec.expErr.Is(gotErr), "exp %v but got %#+v", spec.expErr, gotErr) - if spec.expErr != nil { - require.Len(t, gotMsg, 0) - return - } - assert.Len(t, gotMsg, spec.expMsgDispatched) - for i := 0; i < spec.expMsgDispatched; i++ { - assert.Equal(t, myEvent, gotEvents[i]) - assert.Equal(t, []byte(myData), gotData[i]) - } - }) - } -} - -func TestIBCRawPacketHandler(t *testing.T) { - ibcPort := "contractsIBCPort" - ctx := sdk.Context{}.WithLogger(log.TestingLogger()) - - type CapturedPacket struct { - sourcePort string - sourceChannel string - timeoutHeight clienttypes.Height - timeoutTimestamp uint64 - data []byte - } - var capturedPacket *CapturedPacket - - chanKeeper := &wasmtesting.MockChannelKeeper{ - GetChannelFn: func(ctx sdk.Context, srcPort, srcChan string) (channeltypes.Channel, bool) { - return channeltypes.Channel{ - Counterparty: channeltypes.NewCounterparty( - "other-port", - "other-channel-1", - ), - }, true - }, - SendPacketFn: func(ctx sdk.Context, channelCap *capabilitytypes.Capability, sourcePort string, sourceChannel string, timeoutHeight clienttypes.Height, timeoutTimestamp uint64, data []byte) (uint64, error) { - capturedPacket = &CapturedPacket{ - sourcePort: sourcePort, - sourceChannel: sourceChannel, - timeoutHeight: timeoutHeight, - timeoutTimestamp: timeoutTimestamp, - data: data, - } - return 1, nil - }, - } - capKeeper := &wasmtesting.MockCapabilityKeeper{ - GetCapabilityFn: func(ctx sdk.Context, name string) (*capabilitytypes.Capability, bool) { - return &capabilitytypes.Capability{}, true - }, - } - - specs := map[string]struct { - srcMsg wasmvmtypes.SendPacketMsg - chanKeeper types.ChannelKeeper - capKeeper types.CapabilityKeeper - expPacketSent *CapturedPacket - expErr *errorsmod.Error - }{ - "all good": { - srcMsg: wasmvmtypes.SendPacketMsg{ - ChannelID: "channel-1", - Data: []byte("myData"), - Timeout: wasmvmtypes.IBCTimeout{Block: &wasmvmtypes.IBCTimeoutBlock{Revision: 1, Height: 2}}, - }, - chanKeeper: chanKeeper, - capKeeper: capKeeper, - expPacketSent: &CapturedPacket{ - sourcePort: ibcPort, - sourceChannel: "channel-1", - timeoutHeight: clienttypes.Height{RevisionNumber: 1, RevisionHeight: 2}, - data: []byte("myData"), - }, - }, - "capability not found returns error": { - srcMsg: wasmvmtypes.SendPacketMsg{ - ChannelID: "channel-1", - Data: []byte("myData"), - Timeout: wasmvmtypes.IBCTimeout{Block: &wasmvmtypes.IBCTimeoutBlock{Revision: 1, Height: 2}}, - }, - chanKeeper: chanKeeper, - capKeeper: wasmtesting.MockCapabilityKeeper{ - GetCapabilityFn: func(ctx sdk.Context, name string) (*capabilitytypes.Capability, bool) { - return nil, false - }, - }, - expErr: channeltypes.ErrChannelCapabilityNotFound, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - capturedPacket = nil - // when - h := NewIBCRawPacketHandler(spec.chanKeeper, spec.capKeeper) - evts, data, gotErr := h.DispatchMsg(ctx, RandomAccountAddress(t), ibcPort, wasmvmtypes.CosmosMsg{IBC: &wasmvmtypes.IBCMsg{SendPacket: &spec.srcMsg}}) - // then - require.True(t, spec.expErr.Is(gotErr), "exp %v but got %#+v", spec.expErr, gotErr) - if spec.expErr != nil { - return - } - - assert.Nil(t, evts) - require.NotNil(t, data) - - expMsg := types.MsgIBCSendResponse{Sequence: 1} - - actualMsg := types.MsgIBCSendResponse{} - err := actualMsg.Unmarshal(data[0]) - require.NoError(t, err) - - assert.Equal(t, expMsg, actualMsg) - assert.Equal(t, spec.expPacketSent, capturedPacket) - }) - } -} - -func TestBurnCoinMessageHandlerIntegration(t *testing.T) { - // testing via full keeper setup so that we are confident the - // module permissions are set correct and no other handler - // picks the message in the default handler chain - ctx, keepers := CreateDefaultTestInput(t) - // set some supply - keepers.Faucet.NewFundedRandomAccount(ctx, sdk.NewCoin("denom", sdk.NewInt(10_000_000))) - k := keepers.WasmKeeper - - example := InstantiateHackatomExampleContract(t, ctx, keepers) // with deposit of 100 stake - - before, err := keepers.BankKeeper.TotalSupply(sdk.WrapSDKContext(ctx), &banktypes.QueryTotalSupplyRequest{}) - require.NoError(t, err) - - specs := map[string]struct { - msg wasmvmtypes.BurnMsg - expErr bool - }{ - "all good": { - msg: wasmvmtypes.BurnMsg{ - Amount: wasmvmtypes.Coins{{ - Denom: "denom", - Amount: "100", - }}, - }, - }, - "not enough funds in contract": { - msg: wasmvmtypes.BurnMsg{ - Amount: wasmvmtypes.Coins{{ - Denom: "denom", - Amount: "101", - }}, - }, - expErr: true, - }, - "zero amount rejected": { - msg: wasmvmtypes.BurnMsg{ - Amount: wasmvmtypes.Coins{{ - Denom: "denom", - Amount: "0", - }}, - }, - expErr: true, - }, - "unknown denom - insufficient funds": { - msg: wasmvmtypes.BurnMsg{ - Amount: wasmvmtypes.Coins{{ - Denom: "unknown", - Amount: "1", - }}, - }, - expErr: true, - }, - } - parentCtx := ctx - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - ctx, _ = parentCtx.CacheContext() - k.wasmVM = &wasmtesting.MockWasmer{ExecuteFn: func(codeID wasmvm.Checksum, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, executeMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - return &wasmvmtypes.Response{ - Messages: []wasmvmtypes.SubMsg{ - {Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{Burn: &spec.msg}}, ReplyOn: wasmvmtypes.ReplyNever}, - }, - }, 0, nil - }} - - // when - _, err = k.execute(ctx, example.Contract, example.CreatorAddr, nil, nil) - - // then - if spec.expErr { - require.Error(t, err) - return - } - require.NoError(t, err) - - // and total supply reduced by burned amount - after, err := keepers.BankKeeper.TotalSupply(sdk.WrapSDKContext(ctx), &banktypes.QueryTotalSupplyRequest{}) - require.NoError(t, err) - diff := before.Supply.Sub(after.Supply...) - assert.Equal(t, sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(100))), diff) - }) - } - - // test cases: - // not enough money to burn -} diff --git a/x/wasm/keeper/ibc.go b/x/wasm/keeper/ibc.go deleted file mode 100644 index ff94048..0000000 --- a/x/wasm/keeper/ibc.go +++ /dev/null @@ -1,56 +0,0 @@ -package keeper - -import ( - "strings" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" - host "github.com/cosmos/ibc-go/v7/modules/core/24-host" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// bindIbcPort will reserve the port. -// returns a string name of the port or error if we cannot bind it. -// this will fail if call twice. -func (k Keeper) bindIbcPort(ctx sdk.Context, portID string) error { - portCap := k.portKeeper.BindPort(ctx, portID) - return k.ClaimCapability(ctx, portCap, host.PortPath(portID)) -} - -// ensureIbcPort is like registerIbcPort, but it checks if we already hold the port -// before calling register, so this is safe to call multiple times. -// Returns success if we already registered or just registered and error if we cannot -// (lack of permissions or someone else has it) -func (k Keeper) ensureIbcPort(ctx sdk.Context, contractAddr sdk.AccAddress) (string, error) { - portID := PortIDForContract(contractAddr) - if _, ok := k.capabilityKeeper.GetCapability(ctx, host.PortPath(portID)); ok { - return portID, nil - } - return portID, k.bindIbcPort(ctx, portID) -} - -const portIDPrefix = "wasm." - -func PortIDForContract(addr sdk.AccAddress) string { - return portIDPrefix + addr.String() -} - -func ContractFromPortID(portID string) (sdk.AccAddress, error) { - if !strings.HasPrefix(portID, portIDPrefix) { - return nil, errorsmod.Wrapf(types.ErrInvalid, "without prefix") - } - return sdk.AccAddressFromBech32(portID[len(portIDPrefix):]) -} - -// AuthenticateCapability wraps the scopedKeeper's AuthenticateCapability function -func (k Keeper) AuthenticateCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) bool { - return k.capabilityKeeper.AuthenticateCapability(ctx, cap, name) -} - -// ClaimCapability allows the transfer module to claim a capability -// that IBC module passes to it -func (k Keeper) ClaimCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) error { - return k.capabilityKeeper.ClaimCapability(ctx, cap, name) -} diff --git a/x/wasm/keeper/ibc_test.go b/x/wasm/keeper/ibc_test.go deleted file mode 100644 index 063dfb7..0000000 --- a/x/wasm/keeper/ibc_test.go +++ /dev/null @@ -1,82 +0,0 @@ -package keeper - -import ( - "fmt" - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - - "github.com/stretchr/testify/require" -) - -func TestDontBindPortNonIBCContract(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - example := InstantiateHackatomExampleContract(t, ctx, keepers) // ensure we bound the port - _, _, err := keepers.IBCKeeper.PortKeeper.LookupModuleByPort(ctx, keepers.WasmKeeper.GetContractInfo(ctx, example.Contract).IBCPortID) - require.Error(t, err) -} - -func TestBindingPortForIBCContractOnInstantiate(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - example := InstantiateIBCReflectContract(t, ctx, keepers) // ensure we bound the port - owner, _, err := keepers.IBCKeeper.PortKeeper.LookupModuleByPort(ctx, keepers.WasmKeeper.GetContractInfo(ctx, example.Contract).IBCPortID) - require.NoError(t, err) - require.Equal(t, "wasm", owner) - - initMsgBz := IBCReflectInitMsg{ - ReflectCodeID: example.ReflectCodeID, - }.GetBytes(t) - - // create a second contract should give yet another portID (and different address) - creator := RandomAccountAddress(t) - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, example.CodeID, creator, nil, initMsgBz, "ibc-reflect-2", nil) - require.NoError(t, err) - require.NotEqual(t, example.Contract, addr) - - portID2 := PortIDForContract(addr) - owner, _, err = keepers.IBCKeeper.PortKeeper.LookupModuleByPort(ctx, portID2) - require.NoError(t, err) - require.Equal(t, "wasm", owner) -} - -func TestContractFromPortID(t *testing.T) { - contractAddr := BuildContractAddressClassic(1, 100) - specs := map[string]struct { - srcPort string - expAddr sdk.AccAddress - expErr bool - }{ - "all good": { - srcPort: fmt.Sprintf("wasm.%s", contractAddr.String()), - expAddr: contractAddr, - }, - "without prefix": { - srcPort: contractAddr.String(), - expErr: true, - }, - "invalid prefix": { - srcPort: fmt.Sprintf("wasmx.%s", contractAddr.String()), - expErr: true, - }, - "without separator char": { - srcPort: fmt.Sprintf("wasm%s", contractAddr.String()), - expErr: true, - }, - "invalid account": { - srcPort: "wasm.foobar", - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - gotAddr, gotErr := ContractFromPortID(spec.srcPort) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - assert.Equal(t, spec.expAddr, gotAddr) - }) - } -} diff --git a/x/wasm/keeper/keeper.go b/x/wasm/keeper/keeper.go deleted file mode 100644 index f5d5c4d..0000000 --- a/x/wasm/keeper/keeper.go +++ /dev/null @@ -1,1211 +0,0 @@ -package keeper - -import ( - "bytes" - "context" - "encoding/binary" - "encoding/hex" - "fmt" - "math" - "reflect" - "strconv" - "strings" - "time" - - errorsmod "cosmossdk.io/errors" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - - wasmvm "github.com/CosmWasm/wasmvm" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/cometbft/cometbft/libs/log" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store/prefix" - "github.com/cosmos/cosmos-sdk/telemetry" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - vestingexported "github.com/cosmos/cosmos-sdk/x/auth/vesting/exported" - - "github.com/terpnetwork/terp-core/x/wasm/ioutils" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// contractMemoryLimit is the memory limit of each contract execution (in MiB) -// constant value so all nodes run with the same limit. -const contractMemoryLimit = 32 - -type contextKey int - -const ( - // private type creates an interface key for Context that cannot be accessed by any other package - contextKeyQueryStackSize contextKey = iota -) - -// Option is an extension point to instantiate keeper with non default values -type Option interface { - apply(*Keeper) -} - -// WasmVMQueryHandler is an extension point for custom query handler implementations -type WasmVMQueryHandler interface { - // HandleQuery executes the requested query - HandleQuery(ctx sdk.Context, caller sdk.AccAddress, request wasmvmtypes.QueryRequest) ([]byte, error) -} - -type CoinTransferrer interface { - // TransferCoins sends the coin amounts from the source to the destination with rules applied. - TransferCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) error -} - -// AccountPruner handles the balances and data cleanup for accounts that are pruned on contract instantiate. -// This is an extension point to attach custom logic -type AccountPruner interface { - // CleanupExistingAccount handles the cleanup process for balances and data of the given account. The persisted account - // type is already reset to base account at this stage. - // The method returns true when the account address can be reused. Unsupported account types are rejected by returning false - CleanupExistingAccount(ctx sdk.Context, existingAccount authtypes.AccountI) (handled bool, err error) -} - -// WasmVMResponseHandler is an extension point to handles the response data returned by a contract call. -type WasmVMResponseHandler interface { - // Handle processes the data returned by a contract invocation. - Handle( - ctx sdk.Context, - contractAddr sdk.AccAddress, - ibcPort string, - messages []wasmvmtypes.SubMsg, - origRspData []byte, - ) ([]byte, error) -} - -// list of account types that are accepted for wasm contracts. Chains importing wasmd -// can overwrite this list with the WithAcceptedAccountTypesOnContractInstantiation option. -var defaultAcceptedAccountTypes = map[reflect.Type]struct{}{ - reflect.TypeOf(&authtypes.BaseAccount{}): {}, -} - -// Keeper will have a reference to Wasmer with it's own data directory. -type Keeper struct { - storeKey storetypes.StoreKey - cdc codec.Codec - accountKeeper types.AccountKeeper - bank CoinTransferrer - portKeeper types.PortKeeper - capabilityKeeper types.CapabilityKeeper - wasmVM types.WasmerEngine - wasmVMQueryHandler WasmVMQueryHandler - wasmVMResponseHandler WasmVMResponseHandler - messenger Messenger - // queryGasLimit is the max wasmvm gas that can be spent on executing a query with a contract - queryGasLimit uint64 - gasRegister GasRegister - maxQueryStackSize uint32 - acceptedAccountTypes map[reflect.Type]struct{} - accountPruner AccountPruner - // the address capable of executing a MsgUpdateParams message. Typically, this - // should be the x/gov module account. - authority string -} - -func (k Keeper) getUploadAccessConfig(ctx sdk.Context) types.AccessConfig { - return k.GetParams(ctx).CodeUploadAccess -} - -func (k Keeper) getInstantiateAccessConfig(ctx sdk.Context) types.AccessType { - return k.GetParams(ctx).InstantiateDefaultPermission -} - -// GetParams returns the total set of wasm parameters. -func (k Keeper) GetParams(ctx sdk.Context) types.Params { - var params types.Params - store := ctx.KVStore(k.storeKey) - bz := store.Get(types.ParamsKey) - if bz == nil { - return params - } - - k.cdc.MustUnmarshal(bz, ¶ms) - return params -} - -// SetParams sets all wasm parameters. -func (k Keeper) SetParams(ctx sdk.Context, ps types.Params) error { - if err := ps.ValidateBasic(); err != nil { - return err - } - - store := ctx.KVStore(k.storeKey) - bz, err := k.cdc.Marshal(&ps) - if err != nil { - return err - } - store.Set(types.ParamsKey, bz) - - return nil -} - -// GetAuthority returns the x/wasm module's authority. -func (k Keeper) GetAuthority() string { - return k.authority -} - -func (k Keeper) create(ctx sdk.Context, creator sdk.AccAddress, wasmCode []byte, instantiateAccess *types.AccessConfig, authZ AuthorizationPolicy) (codeID uint64, checksum []byte, err error) { - if creator == nil { - return 0, checksum, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "cannot be nil") - } - - // figure out proper instantiate access - defaultAccessConfig := k.getInstantiateAccessConfig(ctx).With(creator) - if instantiateAccess == nil { - instantiateAccess = &defaultAccessConfig - } - chainConfigs := ChainAccessConfigs{ - Instantiate: defaultAccessConfig, - Upload: k.getUploadAccessConfig(ctx), - } - - if !authZ.CanCreateCode(chainConfigs, creator, *instantiateAccess) { - return 0, checksum, errorsmod.Wrap(sdkerrors.ErrUnauthorized, "can not create code") - } - - if ioutils.IsGzip(wasmCode) { - ctx.GasMeter().ConsumeGas(k.gasRegister.UncompressCosts(len(wasmCode)), "Uncompress gzip bytecode") - wasmCode, err = ioutils.Uncompress(wasmCode, uint64(types.MaxWasmSize)) - if err != nil { - return 0, checksum, errorsmod.Wrap(types.ErrCreateFailed, err.Error()) - } - } - - ctx.GasMeter().ConsumeGas(k.gasRegister.CompileCosts(len(wasmCode)), "Compiling wasm bytecode") - checksum, err = k.wasmVM.Create(wasmCode) - if err != nil { - return 0, checksum, errorsmod.Wrap(types.ErrCreateFailed, err.Error()) - } - report, err := k.wasmVM.AnalyzeCode(checksum) - if err != nil { - return 0, checksum, errorsmod.Wrap(types.ErrCreateFailed, err.Error()) - } - codeID = k.autoIncrementID(ctx, types.KeyLastCodeID) - k.Logger(ctx).Debug("storing new contract", "capabilities", report.RequiredCapabilities, "code_id", codeID) - codeInfo := types.NewCodeInfo(checksum, creator, *instantiateAccess) - k.storeCodeInfo(ctx, codeID, codeInfo) - - evt := sdk.NewEvent( - types.EventTypeStoreCode, - sdk.NewAttribute(types.AttributeKeyChecksum, hex.EncodeToString(checksum)), - sdk.NewAttribute(types.AttributeKeyCodeID, strconv.FormatUint(codeID, 10)), // last element to be compatible with scripts - ) - for _, f := range strings.Split(report.RequiredCapabilities, ",") { - evt.AppendAttributes(sdk.NewAttribute(types.AttributeKeyRequiredCapability, strings.TrimSpace(f))) - } - ctx.EventManager().EmitEvent(evt) - - return codeID, checksum, nil -} - -func (k Keeper) storeCodeInfo(ctx sdk.Context, codeID uint64, codeInfo types.CodeInfo) { - store := ctx.KVStore(k.storeKey) - // 0x01 | codeID (uint64) -> ContractInfo - store.Set(types.GetCodeKey(codeID), k.cdc.MustMarshal(&codeInfo)) -} - -func (k Keeper) importCode(ctx sdk.Context, codeID uint64, codeInfo types.CodeInfo, wasmCode []byte) error { - if ioutils.IsGzip(wasmCode) { - var err error - wasmCode, err = ioutils.Uncompress(wasmCode, uint64(types.MaxWasmSize)) - if err != nil { - return errorsmod.Wrap(types.ErrCreateFailed, err.Error()) - } - } - newCodeHash, err := k.wasmVM.Create(wasmCode) - if err != nil { - return errorsmod.Wrap(types.ErrCreateFailed, err.Error()) - } - if !bytes.Equal(codeInfo.CodeHash, newCodeHash) { - return errorsmod.Wrap(types.ErrInvalid, "code hashes not same") - } - - store := ctx.KVStore(k.storeKey) - key := types.GetCodeKey(codeID) - if store.Has(key) { - return errorsmod.Wrapf(types.ErrDuplicate, "duplicate code: %d", codeID) - } - // 0x01 | codeID (uint64) -> ContractInfo - store.Set(key, k.cdc.MustMarshal(&codeInfo)) - return nil -} - -func (k Keeper) instantiate( - ctx sdk.Context, - codeID uint64, - creator, admin sdk.AccAddress, - initMsg []byte, - label string, - deposit sdk.Coins, - addressGenerator AddressGenerator, - authPolicy AuthorizationPolicy, -) (sdk.AccAddress, []byte, error) { - defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "instantiate") - - if creator == nil { - return nil, nil, types.ErrEmpty.Wrap("creator") - } - instanceCosts := k.gasRegister.NewContractInstanceCosts(k.IsPinnedCode(ctx, codeID), len(initMsg)) - ctx.GasMeter().ConsumeGas(instanceCosts, "Loading CosmWasm module: instantiate") - - codeInfo := k.GetCodeInfo(ctx, codeID) - if codeInfo == nil { - return nil, nil, errorsmod.Wrap(types.ErrNotFound, "code") - } - if !authPolicy.CanInstantiateContract(codeInfo.InstantiateConfig, creator) { - return nil, nil, errorsmod.Wrap(sdkerrors.ErrUnauthorized, "can not instantiate") - } - - contractAddress := addressGenerator(ctx, codeID, codeInfo.CodeHash) - if k.HasContractInfo(ctx, contractAddress) { - return nil, nil, types.ErrDuplicate.Wrap("instance with this code id, sender and label exists: try a different label") - } - - // check account - // every cosmos module can define custom account types when needed. The cosmos-sdk comes with extension points - // to support this and a set of base and vesting account types that we integrated in our default lists. - // But not all account types of other modules are known or may make sense for contracts, therefore we kept this - // decision logic also very flexible and extendable. We provide new options to overwrite the default settings via WithAcceptedAccountTypesOnContractInstantiation and - // WithPruneAccountTypesOnContractInstantiation as constructor arguments - existingAcct := k.accountKeeper.GetAccount(ctx, contractAddress) - if existingAcct != nil { - if existingAcct.GetSequence() != 0 || existingAcct.GetPubKey() != nil { - return nil, nil, types.ErrAccountExists.Wrap("address is claimed by external account") - } - if _, accept := k.acceptedAccountTypes[reflect.TypeOf(existingAcct)]; accept { - // keep account and balance as it is - k.Logger(ctx).Info("instantiate contract with existing account", "address", contractAddress.String()) - } else { - // consider an account in the wasmd namespace spam and overwrite it. - k.Logger(ctx).Info("pruning existing account for contract instantiation", "address", contractAddress.String()) - contractAccount := k.accountKeeper.NewAccountWithAddress(ctx, contractAddress) - k.accountKeeper.SetAccount(ctx, contractAccount) - // also handle balance to not open cases where these accounts are abused and become liquid - switch handled, err := k.accountPruner.CleanupExistingAccount(ctx, existingAcct); { - case err != nil: - return nil, nil, errorsmod.Wrap(err, "prune balance") - case !handled: - return nil, nil, types.ErrAccountExists.Wrap("address is claimed by external account") - } - } - } else { - // create an empty account (so we don't have issues later) - contractAccount := k.accountKeeper.NewAccountWithAddress(ctx, contractAddress) - k.accountKeeper.SetAccount(ctx, contractAccount) - } - // deposit initial contract funds - if !deposit.IsZero() { - if err := k.bank.TransferCoins(ctx, creator, contractAddress, deposit); err != nil { - return nil, nil, err - } - } - - // prepare params for contract instantiate call - env := types.NewEnv(ctx, contractAddress) - info := types.NewInfo(creator, deposit) - - // create prefixed data store - // 0x03 | BuildContractAddressClassic (sdk.AccAddress) - prefixStoreKey := types.GetContractStorePrefix(contractAddress) - vmStore := types.NewStoreAdapter(prefix.NewStore(ctx.KVStore(k.storeKey), prefixStoreKey)) - - // prepare querier - querier := k.newQueryHandler(ctx, contractAddress) - - // instantiate wasm contract - gas := k.runtimeGasForContract(ctx) - res, gasUsed, err := k.wasmVM.Instantiate(codeInfo.CodeHash, env, info, initMsg, vmStore, cosmwasmAPI, querier, k.gasMeter(ctx), gas, costJSONDeserialization) - k.consumeRuntimeGas(ctx, gasUsed) - if err != nil { - return nil, nil, errorsmod.Wrap(types.ErrInstantiateFailed, err.Error()) - } - - // persist instance first - createdAt := types.NewAbsoluteTxPosition(ctx) - contractInfo := types.NewContractInfo(codeID, creator, admin, label, createdAt) - - // check for IBC flag - report, err := k.wasmVM.AnalyzeCode(codeInfo.CodeHash) - if err != nil { - return nil, nil, errorsmod.Wrap(types.ErrInstantiateFailed, err.Error()) - } - if report.HasIBCEntryPoints { - // register IBC port - ibcPort, err := k.ensureIbcPort(ctx, contractAddress) - if err != nil { - return nil, nil, err - } - contractInfo.IBCPortID = ibcPort - } - - // store contract before dispatch so that contract could be called back - historyEntry := contractInfo.InitialHistory(initMsg) - k.addToContractCodeSecondaryIndex(ctx, contractAddress, historyEntry) - k.addToContractCreatorSecondaryIndex(ctx, creator, historyEntry.Updated, contractAddress) - k.appendToContractHistory(ctx, contractAddress, historyEntry) - k.storeContractInfo(ctx, contractAddress, &contractInfo) - - ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypeInstantiate, - sdk.NewAttribute(types.AttributeKeyContractAddr, contractAddress.String()), - sdk.NewAttribute(types.AttributeKeyCodeID, strconv.FormatUint(codeID, 10)), - )) - - data, err := k.handleContractResponse(ctx, contractAddress, contractInfo.IBCPortID, res.Messages, res.Attributes, res.Data, res.Events) - if err != nil { - return nil, nil, errorsmod.Wrap(err, "dispatch") - } - - return contractAddress, data, nil -} - -// Execute executes the contract instance -func (k Keeper) execute(ctx sdk.Context, contractAddress sdk.AccAddress, caller sdk.AccAddress, msg []byte, coins sdk.Coins) ([]byte, error) { - defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "execute") - contractInfo, codeInfo, prefixStore, err := k.contractInstance(ctx, contractAddress) - if err != nil { - return nil, err - } - - executeCosts := k.gasRegister.InstantiateContractCosts(k.IsPinnedCode(ctx, contractInfo.CodeID), len(msg)) - ctx.GasMeter().ConsumeGas(executeCosts, "Loading CosmWasm module: execute") - - // add more funds - if !coins.IsZero() { - if err := k.bank.TransferCoins(ctx, caller, contractAddress, coins); err != nil { - return nil, err - } - } - - env := types.NewEnv(ctx, contractAddress) - info := types.NewInfo(caller, coins) - - // prepare querier - querier := k.newQueryHandler(ctx, contractAddress) - gas := k.runtimeGasForContract(ctx) - res, gasUsed, execErr := k.wasmVM.Execute(codeInfo.CodeHash, env, info, msg, prefixStore, cosmwasmAPI, querier, k.gasMeter(ctx), gas, costJSONDeserialization) - k.consumeRuntimeGas(ctx, gasUsed) - if execErr != nil { - return nil, errorsmod.Wrap(types.ErrExecuteFailed, execErr.Error()) - } - - ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypeExecute, - sdk.NewAttribute(types.AttributeKeyContractAddr, contractAddress.String()), - )) - - data, err := k.handleContractResponse(ctx, contractAddress, contractInfo.IBCPortID, res.Messages, res.Attributes, res.Data, res.Events) - if err != nil { - return nil, errorsmod.Wrap(err, "dispatch") - } - - return data, nil -} - -func (k Keeper) migrate(ctx sdk.Context, contractAddress sdk.AccAddress, caller sdk.AccAddress, newCodeID uint64, msg []byte, authZ AuthorizationPolicy) ([]byte, error) { - defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "migrate") - migrateSetupCosts := k.gasRegister.InstantiateContractCosts(k.IsPinnedCode(ctx, newCodeID), len(msg)) - ctx.GasMeter().ConsumeGas(migrateSetupCosts, "Loading CosmWasm module: migrate") - - contractInfo := k.GetContractInfo(ctx, contractAddress) - if contractInfo == nil { - return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "unknown contract") - } - if !authZ.CanModifyContract(contractInfo.AdminAddr(), caller) { - return nil, errorsmod.Wrap(sdkerrors.ErrUnauthorized, "can not migrate") - } - - newCodeInfo := k.GetCodeInfo(ctx, newCodeID) - if newCodeInfo == nil { - return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "unknown code") - } - - if !authZ.CanInstantiateContract(newCodeInfo.InstantiateConfig, caller) { - return nil, errorsmod.Wrap(sdkerrors.ErrUnauthorized, "to use new code") - } - - // check for IBC flag - switch report, err := k.wasmVM.AnalyzeCode(newCodeInfo.CodeHash); { - case err != nil: - return nil, errorsmod.Wrap(types.ErrMigrationFailed, err.Error()) - case !report.HasIBCEntryPoints && contractInfo.IBCPortID != "": - // prevent update to non ibc contract - return nil, errorsmod.Wrap(types.ErrMigrationFailed, "requires ibc callbacks") - case report.HasIBCEntryPoints && contractInfo.IBCPortID == "": - // add ibc port - ibcPort, err := k.ensureIbcPort(ctx, contractAddress) - if err != nil { - return nil, err - } - contractInfo.IBCPortID = ibcPort - } - - env := types.NewEnv(ctx, contractAddress) - - // prepare querier - querier := k.newQueryHandler(ctx, contractAddress) - - prefixStoreKey := types.GetContractStorePrefix(contractAddress) - vmStore := types.NewStoreAdapter(prefix.NewStore(ctx.KVStore(k.storeKey), prefixStoreKey)) - gas := k.runtimeGasForContract(ctx) - res, gasUsed, err := k.wasmVM.Migrate(newCodeInfo.CodeHash, env, msg, vmStore, cosmwasmAPI, &querier, k.gasMeter(ctx), gas, costJSONDeserialization) - k.consumeRuntimeGas(ctx, gasUsed) - if err != nil { - return nil, errorsmod.Wrap(types.ErrMigrationFailed, err.Error()) - } - // delete old secondary index entry - k.removeFromContractCodeSecondaryIndex(ctx, contractAddress, k.getLastContractHistoryEntry(ctx, contractAddress)) - // persist migration updates - historyEntry := contractInfo.AddMigration(ctx, newCodeID, msg) - k.appendToContractHistory(ctx, contractAddress, historyEntry) - k.addToContractCodeSecondaryIndex(ctx, contractAddress, historyEntry) - k.storeContractInfo(ctx, contractAddress, contractInfo) - - ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypeMigrate, - sdk.NewAttribute(types.AttributeKeyCodeID, strconv.FormatUint(newCodeID, 10)), - sdk.NewAttribute(types.AttributeKeyContractAddr, contractAddress.String()), - )) - - data, err := k.handleContractResponse(ctx, contractAddress, contractInfo.IBCPortID, res.Messages, res.Attributes, res.Data, res.Events) - if err != nil { - return nil, errorsmod.Wrap(err, "dispatch") - } - - return data, nil -} - -// Sudo allows priviledged access to a contract. This can never be called by an external tx, but only by -// another native Go module directly, or on-chain governance (if sudo proposals are enabled). Thus, the keeper doesn't -// place any access controls on it, that is the responsibility or the app developer (who passes the wasm.Keeper in app.go) -func (k Keeper) Sudo(ctx sdk.Context, contractAddress sdk.AccAddress, msg []byte) ([]byte, error) { - defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "sudo") - contractInfo, codeInfo, prefixStore, err := k.contractInstance(ctx, contractAddress) - if err != nil { - return nil, err - } - - sudoSetupCosts := k.gasRegister.InstantiateContractCosts(k.IsPinnedCode(ctx, contractInfo.CodeID), len(msg)) - ctx.GasMeter().ConsumeGas(sudoSetupCosts, "Loading CosmWasm module: sudo") - - env := types.NewEnv(ctx, contractAddress) - - // prepare querier - querier := k.newQueryHandler(ctx, contractAddress) - gas := k.runtimeGasForContract(ctx) - res, gasUsed, execErr := k.wasmVM.Sudo(codeInfo.CodeHash, env, msg, prefixStore, cosmwasmAPI, querier, k.gasMeter(ctx), gas, costJSONDeserialization) - k.consumeRuntimeGas(ctx, gasUsed) - if execErr != nil { - return nil, errorsmod.Wrap(types.ErrExecuteFailed, execErr.Error()) - } - - ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypeSudo, - sdk.NewAttribute(types.AttributeKeyContractAddr, contractAddress.String()), - )) - - data, err := k.handleContractResponse(ctx, contractAddress, contractInfo.IBCPortID, res.Messages, res.Attributes, res.Data, res.Events) - if err != nil { - return nil, errorsmod.Wrap(err, "dispatch") - } - - return data, nil -} - -// reply is only called from keeper internal functions (dispatchSubmessages) after processing the submessage -func (k Keeper) reply(ctx sdk.Context, contractAddress sdk.AccAddress, reply wasmvmtypes.Reply) ([]byte, error) { - contractInfo, codeInfo, prefixStore, err := k.contractInstance(ctx, contractAddress) - if err != nil { - return nil, err - } - - // always consider this pinned - replyCosts := k.gasRegister.ReplyCosts(true, reply) - ctx.GasMeter().ConsumeGas(replyCosts, "Loading CosmWasm module: reply") - - env := types.NewEnv(ctx, contractAddress) - - // prepare querier - querier := k.newQueryHandler(ctx, contractAddress) - gas := k.runtimeGasForContract(ctx) - - res, gasUsed, execErr := k.wasmVM.Reply(codeInfo.CodeHash, env, reply, prefixStore, cosmwasmAPI, querier, k.gasMeter(ctx), gas, costJSONDeserialization) - k.consumeRuntimeGas(ctx, gasUsed) - if execErr != nil { - return nil, errorsmod.Wrap(types.ErrExecuteFailed, execErr.Error()) - } - - ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypeReply, - sdk.NewAttribute(types.AttributeKeyContractAddr, contractAddress.String()), - )) - - data, err := k.handleContractResponse(ctx, contractAddress, contractInfo.IBCPortID, res.Messages, res.Attributes, res.Data, res.Events) - if err != nil { - return nil, errorsmod.Wrap(err, "dispatch") - } - - return data, nil -} - -// addToContractCodeSecondaryIndex adds element to the index for contracts-by-codeid queries -func (k Keeper) addToContractCodeSecondaryIndex(ctx sdk.Context, contractAddress sdk.AccAddress, entry types.ContractCodeHistoryEntry) { - store := ctx.KVStore(k.storeKey) - store.Set(types.GetContractByCreatedSecondaryIndexKey(contractAddress, entry), []byte{}) -} - -// removeFromContractCodeSecondaryIndex removes element to the index for contracts-by-codeid queries -func (k Keeper) removeFromContractCodeSecondaryIndex(ctx sdk.Context, contractAddress sdk.AccAddress, entry types.ContractCodeHistoryEntry) { - ctx.KVStore(k.storeKey).Delete(types.GetContractByCreatedSecondaryIndexKey(contractAddress, entry)) -} - -// addToContractCreatorSecondaryIndex adds element to the index for contracts-by-creator queries -func (k Keeper) addToContractCreatorSecondaryIndex(ctx sdk.Context, creatorAddress sdk.AccAddress, position *types.AbsoluteTxPosition, contractAddress sdk.AccAddress) { - store := ctx.KVStore(k.storeKey) - store.Set(types.GetContractByCreatorSecondaryIndexKey(creatorAddress, position.Bytes(), contractAddress), []byte{}) -} - -// IterateContractsByCreator iterates over all contracts with given creator address in order of creation time asc. -func (k Keeper) IterateContractsByCreator(ctx sdk.Context, creator sdk.AccAddress, cb func(address sdk.AccAddress) bool) { - prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), types.GetContractsByCreatorPrefix(creator)) - for iter := prefixStore.Iterator(nil, nil); iter.Valid(); iter.Next() { - key := iter.Key() - if cb(key[types.AbsoluteTxPositionLen:]) { - return - } - } -} - -// IterateContractsByCode iterates over all contracts with given codeID ASC on code update time. -func (k Keeper) IterateContractsByCode(ctx sdk.Context, codeID uint64, cb func(address sdk.AccAddress) bool) { - prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), types.GetContractByCodeIDSecondaryIndexPrefix(codeID)) - iter := prefixStore.Iterator(nil, nil) - defer iter.Close() - - for ; iter.Valid(); iter.Next() { - key := iter.Key() - if cb(key[types.AbsoluteTxPositionLen:]) { - return - } - } -} - -func (k Keeper) setContractAdmin(ctx sdk.Context, contractAddress, caller, newAdmin sdk.AccAddress, authZ AuthorizationPolicy) error { - contractInfo := k.GetContractInfo(ctx, contractAddress) - if contractInfo == nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "unknown contract") - } - if !authZ.CanModifyContract(contractInfo.AdminAddr(), caller) { - return errorsmod.Wrap(sdkerrors.ErrUnauthorized, "can not modify contract") - } - newAdminStr := newAdmin.String() - contractInfo.Admin = newAdminStr - k.storeContractInfo(ctx, contractAddress, contractInfo) - ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypeUpdateContractAdmin, - sdk.NewAttribute(types.AttributeKeyContractAddr, contractAddress.String()), - sdk.NewAttribute(types.AttributeKeyNewAdmin, newAdminStr), - )) - - return nil -} - -func (k Keeper) appendToContractHistory(ctx sdk.Context, contractAddr sdk.AccAddress, newEntries ...types.ContractCodeHistoryEntry) { - store := ctx.KVStore(k.storeKey) - // find last element position - var pos uint64 - prefixStore := prefix.NewStore(store, types.GetContractCodeHistoryElementPrefix(contractAddr)) - iter := prefixStore.ReverseIterator(nil, nil) - defer iter.Close() - - if iter.Valid() { - pos = sdk.BigEndianToUint64(iter.Key()) - } - // then store with incrementing position - for _, e := range newEntries { - pos++ - key := types.GetContractCodeHistoryElementKey(contractAddr, pos) - store.Set(key, k.cdc.MustMarshal(&e)) //nolint:gosec - } -} - -func (k Keeper) GetContractHistory(ctx sdk.Context, contractAddr sdk.AccAddress) []types.ContractCodeHistoryEntry { - prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), types.GetContractCodeHistoryElementPrefix(contractAddr)) - r := make([]types.ContractCodeHistoryEntry, 0) - iter := prefixStore.Iterator(nil, nil) - defer iter.Close() - - for ; iter.Valid(); iter.Next() { - var e types.ContractCodeHistoryEntry - k.cdc.MustUnmarshal(iter.Value(), &e) - r = append(r, e) - } - return r -} - -// getLastContractHistoryEntry returns the last element from history. To be used internally only as it panics when none exists -func (k Keeper) getLastContractHistoryEntry(ctx sdk.Context, contractAddr sdk.AccAddress) types.ContractCodeHistoryEntry { - prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), types.GetContractCodeHistoryElementPrefix(contractAddr)) - iter := prefixStore.ReverseIterator(nil, nil) - defer iter.Close() - - var r types.ContractCodeHistoryEntry - if !iter.Valid() { - // all contracts have a history - panic(fmt.Sprintf("no history for %s", contractAddr.String())) - } - k.cdc.MustUnmarshal(iter.Value(), &r) - return r -} - -// QuerySmart queries the smart contract itself. -func (k Keeper) QuerySmart(ctx sdk.Context, contractAddr sdk.AccAddress, req []byte) ([]byte, error) { - defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "query-smart") - - // checks and increase query stack size - ctx, err := checkAndIncreaseQueryStackSize(ctx, k.maxQueryStackSize) - if err != nil { - return nil, err - } - - contractInfo, codeInfo, prefixStore, err := k.contractInstance(ctx, contractAddr) - if err != nil { - return nil, err - } - - smartQuerySetupCosts := k.gasRegister.InstantiateContractCosts(k.IsPinnedCode(ctx, contractInfo.CodeID), len(req)) - ctx.GasMeter().ConsumeGas(smartQuerySetupCosts, "Loading CosmWasm module: query") - - // prepare querier - querier := k.newQueryHandler(ctx, contractAddr) - - env := types.NewEnv(ctx, contractAddr) - queryResult, gasUsed, qErr := k.wasmVM.Query(codeInfo.CodeHash, env, req, prefixStore, cosmwasmAPI, querier, k.gasMeter(ctx), k.runtimeGasForContract(ctx), costJSONDeserialization) - k.consumeRuntimeGas(ctx, gasUsed) - if qErr != nil { - return nil, errorsmod.Wrap(types.ErrQueryFailed, qErr.Error()) - } - return queryResult, nil -} - -func checkAndIncreaseQueryStackSize(ctx sdk.Context, maxQueryStackSize uint32) (sdk.Context, error) { - var queryStackSize uint32 - - // read current value - if size := ctx.Context().Value(contextKeyQueryStackSize); size != nil { - queryStackSize = size.(uint32) - } else { - queryStackSize = 0 - } - - // increase - queryStackSize++ - - // did we go too far? - if queryStackSize > maxQueryStackSize { - return ctx, types.ErrExceedMaxQueryStackSize - } - - // set updated stack size - ctx = ctx.WithContext(context.WithValue(ctx.Context(), contextKeyQueryStackSize, queryStackSize)) - - return ctx, nil -} - -// QueryRaw returns the contract's state for give key. Returns `nil` when key is `nil`. -func (k Keeper) QueryRaw(ctx sdk.Context, contractAddress sdk.AccAddress, key []byte) []byte { - defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "query-raw") - if key == nil { - return nil - } - prefixStoreKey := types.GetContractStorePrefix(contractAddress) - prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), prefixStoreKey) - return prefixStore.Get(key) -} - -// internal helper function -func (k Keeper) contractInstance(ctx sdk.Context, contractAddress sdk.AccAddress) (types.ContractInfo, types.CodeInfo, wasmvm.KVStore, error) { - store := ctx.KVStore(k.storeKey) - - contractBz := store.Get(types.GetContractAddressKey(contractAddress)) - if contractBz == nil { - return types.ContractInfo{}, types.CodeInfo{}, nil, errorsmod.Wrap(types.ErrNotFound, "contract") - } - var contractInfo types.ContractInfo - k.cdc.MustUnmarshal(contractBz, &contractInfo) - - codeInfoBz := store.Get(types.GetCodeKey(contractInfo.CodeID)) - if codeInfoBz == nil { - return contractInfo, types.CodeInfo{}, nil, errorsmod.Wrap(types.ErrNotFound, "code info") - } - var codeInfo types.CodeInfo - k.cdc.MustUnmarshal(codeInfoBz, &codeInfo) - prefixStoreKey := types.GetContractStorePrefix(contractAddress) - prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), prefixStoreKey) - return contractInfo, codeInfo, types.NewStoreAdapter(prefixStore), nil -} - -func (k Keeper) GetContractInfo(ctx sdk.Context, contractAddress sdk.AccAddress) *types.ContractInfo { - store := ctx.KVStore(k.storeKey) - var contract types.ContractInfo - contractBz := store.Get(types.GetContractAddressKey(contractAddress)) - if contractBz == nil { - return nil - } - k.cdc.MustUnmarshal(contractBz, &contract) - return &contract -} - -func (k Keeper) HasContractInfo(ctx sdk.Context, contractAddress sdk.AccAddress) bool { - store := ctx.KVStore(k.storeKey) - return store.Has(types.GetContractAddressKey(contractAddress)) -} - -// storeContractInfo persists the ContractInfo. No secondary index updated here. -func (k Keeper) storeContractInfo(ctx sdk.Context, contractAddress sdk.AccAddress, contract *types.ContractInfo) { - store := ctx.KVStore(k.storeKey) - store.Set(types.GetContractAddressKey(contractAddress), k.cdc.MustMarshal(contract)) -} - -func (k Keeper) IterateContractInfo(ctx sdk.Context, cb func(sdk.AccAddress, types.ContractInfo) bool) { - prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), types.ContractKeyPrefix) - iter := prefixStore.Iterator(nil, nil) - defer iter.Close() - - for ; iter.Valid(); iter.Next() { - var contract types.ContractInfo - k.cdc.MustUnmarshal(iter.Value(), &contract) - // cb returns true to stop early - if cb(iter.Key(), contract) { - break - } - } -} - -// IterateContractState iterates through all elements of the key value store for the given contract address and passes -// them to the provided callback function. The callback method can return true to abort early. -func (k Keeper) IterateContractState(ctx sdk.Context, contractAddress sdk.AccAddress, cb func(key, value []byte) bool) { - prefixStoreKey := types.GetContractStorePrefix(contractAddress) - prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), prefixStoreKey) - iter := prefixStore.Iterator(nil, nil) - defer iter.Close() - - for ; iter.Valid(); iter.Next() { - if cb(iter.Key(), iter.Value()) { - break - } - } -} - -func (k Keeper) importContractState(ctx sdk.Context, contractAddress sdk.AccAddress, models []types.Model) error { - prefixStoreKey := types.GetContractStorePrefix(contractAddress) - prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), prefixStoreKey) - for _, model := range models { - if model.Value == nil { - model.Value = []byte{} - } - if prefixStore.Has(model.Key) { - return errorsmod.Wrapf(types.ErrDuplicate, "duplicate key: %x", model.Key) - } - prefixStore.Set(model.Key, model.Value) - } - return nil -} - -func (k Keeper) GetCodeInfo(ctx sdk.Context, codeID uint64) *types.CodeInfo { - store := ctx.KVStore(k.storeKey) - var codeInfo types.CodeInfo - codeInfoBz := store.Get(types.GetCodeKey(codeID)) - if codeInfoBz == nil { - return nil - } - k.cdc.MustUnmarshal(codeInfoBz, &codeInfo) - return &codeInfo -} - -func (k Keeper) containsCodeInfo(ctx sdk.Context, codeID uint64) bool { - store := ctx.KVStore(k.storeKey) - return store.Has(types.GetCodeKey(codeID)) -} - -func (k Keeper) IterateCodeInfos(ctx sdk.Context, cb func(uint64, types.CodeInfo) bool) { - prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), types.CodeKeyPrefix) - iter := prefixStore.Iterator(nil, nil) - defer iter.Close() - - for ; iter.Valid(); iter.Next() { - var c types.CodeInfo - k.cdc.MustUnmarshal(iter.Value(), &c) - // cb returns true to stop early - if cb(binary.BigEndian.Uint64(iter.Key()), c) { - return - } - } -} - -func (k Keeper) GetByteCode(ctx sdk.Context, codeID uint64) ([]byte, error) { - store := ctx.KVStore(k.storeKey) - var codeInfo types.CodeInfo - codeInfoBz := store.Get(types.GetCodeKey(codeID)) - if codeInfoBz == nil { - return nil, nil - } - k.cdc.MustUnmarshal(codeInfoBz, &codeInfo) - return k.wasmVM.GetCode(codeInfo.CodeHash) -} - -// PinCode pins the wasm contract in wasmvm cache -func (k Keeper) pinCode(ctx sdk.Context, codeID uint64) error { - codeInfo := k.GetCodeInfo(ctx, codeID) - if codeInfo == nil { - return errorsmod.Wrap(types.ErrNotFound, "code info") - } - - if err := k.wasmVM.Pin(codeInfo.CodeHash); err != nil { - return errorsmod.Wrap(types.ErrPinContractFailed, err.Error()) - } - store := ctx.KVStore(k.storeKey) - // store 1 byte to not run into `nil` debugging issues - store.Set(types.GetPinnedCodeIndexPrefix(codeID), []byte{1}) - - ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypePinCode, - sdk.NewAttribute(types.AttributeKeyCodeID, strconv.FormatUint(codeID, 10)), - )) - return nil -} - -// UnpinCode removes the wasm contract from wasmvm cache -func (k Keeper) unpinCode(ctx sdk.Context, codeID uint64) error { - codeInfo := k.GetCodeInfo(ctx, codeID) - if codeInfo == nil { - return errorsmod.Wrap(types.ErrNotFound, "code info") - } - if err := k.wasmVM.Unpin(codeInfo.CodeHash); err != nil { - return errorsmod.Wrap(types.ErrUnpinContractFailed, err.Error()) - } - - store := ctx.KVStore(k.storeKey) - store.Delete(types.GetPinnedCodeIndexPrefix(codeID)) - - ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypeUnpinCode, - sdk.NewAttribute(types.AttributeKeyCodeID, strconv.FormatUint(codeID, 10)), - )) - return nil -} - -// IsPinnedCode returns true when codeID is pinned in wasmvm cache -func (k Keeper) IsPinnedCode(ctx sdk.Context, codeID uint64) bool { - store := ctx.KVStore(k.storeKey) - return store.Has(types.GetPinnedCodeIndexPrefix(codeID)) -} - -// InitializePinnedCodes updates wasmvm to pin to cache all contracts marked as pinned -func (k Keeper) InitializePinnedCodes(ctx sdk.Context) error { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.PinnedCodeIndexPrefix) - iter := store.Iterator(nil, nil) - defer iter.Close() - - for ; iter.Valid(); iter.Next() { - codeInfo := k.GetCodeInfo(ctx, types.ParsePinnedCodeIndex(iter.Key())) - if codeInfo == nil { - return errorsmod.Wrap(types.ErrNotFound, "code info") - } - if err := k.wasmVM.Pin(codeInfo.CodeHash); err != nil { - return errorsmod.Wrap(types.ErrPinContractFailed, err.Error()) - } - } - return nil -} - -// setContractInfoExtension updates the extension point data that is stored with the contract info -func (k Keeper) setContractInfoExtension(ctx sdk.Context, contractAddr sdk.AccAddress, ext types.ContractInfoExtension) error { - info := k.GetContractInfo(ctx, contractAddr) - if info == nil { - return errorsmod.Wrap(types.ErrNotFound, "contract info") - } - if err := info.SetExtension(ext); err != nil { - return err - } - k.storeContractInfo(ctx, contractAddr, info) - return nil -} - -// setAccessConfig updates the access config of a code id. -func (k Keeper) setAccessConfig(ctx sdk.Context, codeID uint64, caller sdk.AccAddress, newConfig types.AccessConfig, authz AuthorizationPolicy) error { - info := k.GetCodeInfo(ctx, codeID) - if info == nil { - return errorsmod.Wrap(types.ErrNotFound, "code info") - } - isSubset := newConfig.Permission.IsSubset(k.getInstantiateAccessConfig(ctx)) - if !authz.CanModifyCodeAccessConfig(sdk.MustAccAddressFromBech32(info.Creator), caller, isSubset) { - return errorsmod.Wrap(sdkerrors.ErrUnauthorized, "can not modify code access config") - } - - info.InstantiateConfig = newConfig - k.storeCodeInfo(ctx, codeID, *info) - evt := sdk.NewEvent( - types.EventTypeUpdateCodeAccessConfig, - sdk.NewAttribute(types.AttributeKeyCodePermission, newConfig.Permission.String()), - sdk.NewAttribute(types.AttributeKeyCodeID, strconv.FormatUint(codeID, 10)), - ) - if addrs := newConfig.AllAuthorizedAddresses(); len(addrs) != 0 { - attr := sdk.NewAttribute(types.AttributeKeyAuthorizedAddresses, strings.Join(addrs, ",")) - evt.Attributes = append(evt.Attributes, attr.ToKVPair()) - } - ctx.EventManager().EmitEvent(evt) - return nil -} - -// handleContractResponse processes the contract response data by emitting events and sending sub-/messages. -func (k *Keeper) handleContractResponse( - ctx sdk.Context, - contractAddr sdk.AccAddress, - ibcPort string, - msgs []wasmvmtypes.SubMsg, - attrs []wasmvmtypes.EventAttribute, - data []byte, - evts wasmvmtypes.Events, -) ([]byte, error) { - attributeGasCost := k.gasRegister.EventCosts(attrs, evts) - ctx.GasMeter().ConsumeGas(attributeGasCost, "Custom contract event attributes") - // emit all events from this contract itself - if len(attrs) != 0 { - wasmEvents, err := newWasmModuleEvent(attrs, contractAddr) - if err != nil { - return nil, err - } - ctx.EventManager().EmitEvents(wasmEvents) - } - if len(evts) > 0 { - customEvents, err := newCustomEvents(evts, contractAddr) - if err != nil { - return nil, err - } - ctx.EventManager().EmitEvents(customEvents) - } - return k.wasmVMResponseHandler.Handle(ctx, contractAddr, ibcPort, msgs, data) -} - -func (k Keeper) runtimeGasForContract(ctx sdk.Context) uint64 { - meter := ctx.GasMeter() - if meter.IsOutOfGas() { - return 0 - } - if meter.Limit() == math.MaxUint64 { // infinite gas meter and not out of gas - return math.MaxUint64 - } - return k.gasRegister.ToWasmVMGas(meter.Limit() - meter.GasConsumedToLimit()) -} - -func (k Keeper) consumeRuntimeGas(ctx sdk.Context, gas uint64) { - consumed := k.gasRegister.FromWasmVMGas(gas) - ctx.GasMeter().ConsumeGas(consumed, "wasm contract") - // throw OutOfGas error if we ran out (got exactly to zero due to better limit enforcing) - if ctx.GasMeter().IsOutOfGas() { - panic(sdk.ErrorOutOfGas{Descriptor: "Wasmer function execution"}) - } -} - -func (k Keeper) autoIncrementID(ctx sdk.Context, lastIDKey []byte) uint64 { - store := ctx.KVStore(k.storeKey) - bz := store.Get(lastIDKey) - id := uint64(1) - if bz != nil { - id = binary.BigEndian.Uint64(bz) - } - bz = sdk.Uint64ToBigEndian(id + 1) - store.Set(lastIDKey, bz) - return id -} - -// PeekAutoIncrementID reads the current value without incrementing it. -func (k Keeper) PeekAutoIncrementID(ctx sdk.Context, lastIDKey []byte) uint64 { - store := ctx.KVStore(k.storeKey) - bz := store.Get(lastIDKey) - id := uint64(1) - if bz != nil { - id = binary.BigEndian.Uint64(bz) - } - return id -} - -func (k Keeper) importAutoIncrementID(ctx sdk.Context, lastIDKey []byte, val uint64) error { - store := ctx.KVStore(k.storeKey) - if store.Has(lastIDKey) { - return errorsmod.Wrapf(types.ErrDuplicate, "autoincrement id: %s", string(lastIDKey)) - } - bz := sdk.Uint64ToBigEndian(val) - store.Set(lastIDKey, bz) - return nil -} - -func (k Keeper) importContract(ctx sdk.Context, contractAddr sdk.AccAddress, c *types.ContractInfo, state []types.Model, entries []types.ContractCodeHistoryEntry) error { - if !k.containsCodeInfo(ctx, c.CodeID) { - return errorsmod.Wrapf(types.ErrNotFound, "code id: %d", c.CodeID) - } - if k.HasContractInfo(ctx, contractAddr) { - return errorsmod.Wrapf(types.ErrDuplicate, "contract: %s", contractAddr) - } - - creatorAddress, err := sdk.AccAddressFromBech32(c.Creator) - if err != nil { - return err - } - - k.appendToContractHistory(ctx, contractAddr, entries...) - k.storeContractInfo(ctx, contractAddr, c) - k.addToContractCodeSecondaryIndex(ctx, contractAddr, entries[len(entries)-1]) - k.addToContractCreatorSecondaryIndex(ctx, creatorAddress, entries[0].Updated, contractAddr) - return k.importContractState(ctx, contractAddr, state) -} - -func (k Keeper) newQueryHandler(ctx sdk.Context, contractAddress sdk.AccAddress) QueryHandler { - return NewQueryHandler(ctx, k.wasmVMQueryHandler, contractAddress, k.gasRegister) -} - -// MultipliedGasMeter wraps the GasMeter from context and multiplies all reads by out defined multiplier -type MultipliedGasMeter struct { - originalMeter sdk.GasMeter - GasRegister GasRegister -} - -func NewMultipliedGasMeter(originalMeter sdk.GasMeter, gr GasRegister) MultipliedGasMeter { - return MultipliedGasMeter{originalMeter: originalMeter, GasRegister: gr} -} - -var _ wasmvm.GasMeter = MultipliedGasMeter{} - -func (m MultipliedGasMeter) GasConsumed() sdk.Gas { - return m.GasRegister.ToWasmVMGas(m.originalMeter.GasConsumed()) -} - -func (k Keeper) gasMeter(ctx sdk.Context) MultipliedGasMeter { - return NewMultipliedGasMeter(ctx.GasMeter(), k.gasRegister) -} - -// Logger returns a module-specific logger. -func (k Keeper) Logger(ctx sdk.Context) log.Logger { - return moduleLogger(ctx) -} - -func moduleLogger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) -} - -// Querier creates a new grpc querier instance -func Querier(k *Keeper) *GrpcQuerier { - return NewGrpcQuerier(k.cdc, k.storeKey, k, k.queryGasLimit) -} - -// QueryGasLimit returns the gas limit for smart queries. -func (k Keeper) QueryGasLimit() sdk.Gas { - return k.queryGasLimit -} - -// BankCoinTransferrer replicates the cosmos-sdk behaviour as in -// https://github.com/cosmos/cosmos-sdk/blob/v0.41.4/x/bank/keeper/msg_server.go#L26 -type BankCoinTransferrer struct { - keeper types.BankKeeper -} - -func NewBankCoinTransferrer(keeper types.BankKeeper) BankCoinTransferrer { - return BankCoinTransferrer{ - keeper: keeper, - } -} - -// TransferCoins transfers coins from source to destination account when coin send was enabled for them and the recipient -// is not in the blocked address list. -func (c BankCoinTransferrer) TransferCoins(parentCtx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amount sdk.Coins) error { - em := sdk.NewEventManager() - ctx := parentCtx.WithEventManager(em) - if err := c.keeper.IsSendEnabledCoins(ctx, amount...); err != nil { - return err - } - if c.keeper.BlockedAddr(toAddr) { - return errorsmod.Wrapf(sdkerrors.ErrUnauthorized, "%s is not allowed to receive funds", toAddr.String()) - } - - sdkerr := c.keeper.SendCoins(ctx, fromAddr, toAddr, amount) - if sdkerr != nil { - return sdkerr - } - for _, e := range em.Events() { - if e.Type == sdk.EventTypeMessage { // skip messages as we talk to the keeper directly - continue - } - parentCtx.EventManager().EmitEvent(e) - } - return nil -} - -var _ AccountPruner = VestingCoinBurner{} - -// VestingCoinBurner default implementation for AccountPruner to burn the coins -type VestingCoinBurner struct { - bank types.BankKeeper -} - -// NewVestingCoinBurner constructor -func NewVestingCoinBurner(bank types.BankKeeper) VestingCoinBurner { - if bank == nil { - panic("bank keeper must not be nil") - } - return VestingCoinBurner{bank: bank} -} - -// CleanupExistingAccount accepts only vesting account types to burns all their original vesting coin balances. -// Other account types will be rejected and returned as unhandled. -func (b VestingCoinBurner) CleanupExistingAccount(ctx sdk.Context, existingAcc authtypes.AccountI) (handled bool, err error) { - v, ok := existingAcc.(vestingexported.VestingAccount) - if !ok { - return false, nil - } - - ctx = ctx.WithGasMeter(sdk.NewInfiniteGasMeter()) - coinsToBurn := sdk.NewCoins() - for _, orig := range v.GetOriginalVesting() { // focus on the coin denoms that were setup originally; getAllBalances has some issues - coinsToBurn = append(coinsToBurn, b.bank.GetBalance(ctx, existingAcc.GetAddress(), orig.Denom)) - } - if err := b.bank.SendCoinsFromAccountToModule(ctx, existingAcc.GetAddress(), types.ModuleName, coinsToBurn); err != nil { - return false, errorsmod.Wrap(err, "prune account balance") - } - if err := b.bank.BurnCoins(ctx, types.ModuleName, coinsToBurn); err != nil { - return false, errorsmod.Wrap(err, "burn account balance") - } - return true, nil -} - -type msgDispatcher interface { - DispatchSubmessages(ctx sdk.Context, contractAddr sdk.AccAddress, ibcPort string, msgs []wasmvmtypes.SubMsg) ([]byte, error) -} - -// DefaultWasmVMContractResponseHandler default implementation that first dispatches submessage then normal messages. -// The Submessage execution may include an success/failure response handling by the contract that can overwrite the -// original -type DefaultWasmVMContractResponseHandler struct { - md msgDispatcher -} - -func NewDefaultWasmVMContractResponseHandler(md msgDispatcher) *DefaultWasmVMContractResponseHandler { - return &DefaultWasmVMContractResponseHandler{md: md} -} - -// Handle processes the data returned by a contract invocation. -func (h DefaultWasmVMContractResponseHandler) Handle(ctx sdk.Context, contractAddr sdk.AccAddress, ibcPort string, messages []wasmvmtypes.SubMsg, origRspData []byte) ([]byte, error) { - result := origRspData - switch rsp, err := h.md.DispatchSubmessages(ctx, contractAddr, ibcPort, messages); { - case err != nil: - return nil, errorsmod.Wrap(err, "submessages") - case rsp != nil: - result = rsp - } - return result, nil -} diff --git a/x/wasm/keeper/keeper_cgo.go b/x/wasm/keeper/keeper_cgo.go deleted file mode 100644 index 64c94f3..0000000 --- a/x/wasm/keeper/keeper_cgo.go +++ /dev/null @@ -1,65 +0,0 @@ -//go:build cgo - -package keeper - -import ( - "path/filepath" - - storetypes "github.com/cosmos/cosmos-sdk/store/types" - - wasmvm "github.com/CosmWasm/wasmvm" - "github.com/cosmos/cosmos-sdk/codec" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// NewKeeper creates a new contract Keeper instance -// If customEncoders is non-nil, we can use this to override some of the message handler, especially custom -func NewKeeper( - cdc codec.Codec, - storeKey storetypes.StoreKey, - accountKeeper types.AccountKeeper, - bankKeeper types.BankKeeper, - stakingKeeper types.StakingKeeper, - distrKeeper types.DistributionKeeper, - channelKeeper types.ChannelKeeper, - portKeeper types.PortKeeper, - capabilityKeeper types.CapabilityKeeper, - portSource types.ICS20TransferPortSource, - router MessageRouter, - _ GRPCQueryRouter, - homeDir string, - wasmConfig types.WasmConfig, - availableCapabilities string, - authority string, - opts ...Option, -) Keeper { - wasmer, err := wasmvm.NewVM(filepath.Join(homeDir, "wasm"), availableCapabilities, contractMemoryLimit, wasmConfig.ContractDebugMode, wasmConfig.MemoryCacheSize) - if err != nil { - panic(err) - } - - keeper := &Keeper{ - storeKey: storeKey, - cdc: cdc, - wasmVM: wasmer, - accountKeeper: accountKeeper, - bank: NewBankCoinTransferrer(bankKeeper), - accountPruner: NewVestingCoinBurner(bankKeeper), - portKeeper: portKeeper, - capabilityKeeper: capabilityKeeper, - messenger: NewDefaultMessageHandler(router, channelKeeper, capabilityKeeper, bankKeeper, cdc, portSource), - queryGasLimit: wasmConfig.SmartQueryGasLimit, - gasRegister: NewDefaultWasmGasRegister(), - maxQueryStackSize: types.DefaultMaxQueryStackSize, - acceptedAccountTypes: defaultAcceptedAccountTypes, - authority: authority, - } - keeper.wasmVMQueryHandler = DefaultQueryPlugins(bankKeeper, stakingKeeper, distrKeeper, channelKeeper, keeper) - for _, o := range opts { - o.apply(keeper) - } - // not updateable, yet - keeper.wasmVMResponseHandler = NewDefaultWasmVMContractResponseHandler(NewMessageDispatcher(keeper.messenger, keeper)) - return *keeper -} diff --git a/x/wasm/keeper/keeper_no_cgo.go b/x/wasm/keeper/keeper_no_cgo.go deleted file mode 100644 index 2c45dbc..0000000 --- a/x/wasm/keeper/keeper_no_cgo.go +++ /dev/null @@ -1,34 +0,0 @@ -//go:build !cgo - -package keeper - -import ( - "github.com/cosmos/cosmos-sdk/codec" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// NewKeeper creates a new contract Keeper instance -// If customEncoders is non-nil, we can use this to override some of the message handler, especially custom -func NewKeeper( - cdc codec.Codec, - storeKey storetypes.StoreKey, - accountKeeper types.AccountKeeper, - bankKeeper types.BankKeeper, - stakingKeeper types.StakingKeeper, - distrKeeper types.DistributionKeeper, - channelKeeper types.ChannelKeeper, - portKeeper types.PortKeeper, - capabilityKeeper types.CapabilityKeeper, - portSource types.ICS20TransferPortSource, - router MessageRouter, - _ GRPCQueryRouter, - homeDir string, - wasmConfig types.WasmConfig, - availableCapabilities string, - authority string, - opts ...Option, -) Keeper { - panic("not implemented, please build with cgo enabled") -} diff --git a/x/wasm/keeper/keeper_test.go b/x/wasm/keeper/keeper_test.go deleted file mode 100644 index 6d97ae6..0000000 --- a/x/wasm/keeper/keeper_test.go +++ /dev/null @@ -1,2418 +0,0 @@ -package keeper - -import ( - "bytes" - _ "embed" - "encoding/json" - "errors" - "fmt" - "os" - "strings" - "testing" - "time" - - errorsmod "cosmossdk.io/errors" - abci "github.com/cometbft/cometbft/abci/types" - - wasmvm "github.com/CosmWasm/wasmvm" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/cometbft/cometbft/libs/rand" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - stypes "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - fuzz "github.com/google/gofuzz" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/keeper/wasmtesting" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -//go:embed testdata/hackatom.wasm -var hackatomWasm []byte - -const AvailableCapabilities = "iterator,staking,stargate,cosmwasm_1_1" - -func TestNewKeeper(t *testing.T) { - _, keepers := CreateTestInput(t, false, AvailableCapabilities) - require.NotNil(t, keepers.ContractKeeper) -} - -func TestCreateSuccess(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.ContractKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - - em := sdk.NewEventManager() - contractID, _, err := keeper.Create(ctx.WithEventManager(em), creator, hackatomWasm, nil) - require.NoError(t, err) - require.Equal(t, uint64(1), contractID) - // and verify content - storedCode, err := keepers.WasmKeeper.GetByteCode(ctx, contractID) - require.NoError(t, err) - require.Equal(t, hackatomWasm, storedCode) - // and events emitted - codeHash := strings.ToLower("beb3de5e9b93b52e514c74ce87ccddb594b9bcd33b7f1af1bb6da63fc883917b") - exp := sdk.Events{sdk.NewEvent("store_code", sdk.NewAttribute("code_checksum", codeHash), sdk.NewAttribute("code_id", "1"))} - assert.Equal(t, exp, em.Events()) -} - -func TestCreateNilCreatorAddress(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - - _, _, err := keepers.ContractKeeper.Create(ctx, nil, hackatomWasm, nil) - require.Error(t, err, "nil creator is not allowed") -} - -func TestCreateNilWasmCode(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - - _, _, err := keepers.ContractKeeper.Create(ctx, creator, nil, nil) - require.Error(t, err, "nil WASM code is not allowed") -} - -func TestCreateInvalidWasmCode(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - - _, _, err := keepers.ContractKeeper.Create(ctx, creator, []byte("potatoes"), nil) - require.Error(t, err, "potatoes are not valid WASM code") -} - -func TestCreateStoresInstantiatePermission(t *testing.T) { - var ( - deposit = sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - myAddr sdk.AccAddress = bytes.Repeat([]byte{1}, types.SDKAddrLen) - ) - - specs := map[string]struct { - srcPermission types.AccessType - expInstConf types.AccessConfig - }{ - "default": { - srcPermission: types.DefaultParams().InstantiateDefaultPermission, - expInstConf: types.AllowEverybody, - }, - "everybody": { - srcPermission: types.AccessTypeEverybody, - expInstConf: types.AllowEverybody, - }, - "nobody": { - srcPermission: types.AccessTypeNobody, - expInstConf: types.AllowNobody, - }, - "onlyAddress with matching address": { - srcPermission: types.AccessTypeOnlyAddress, - expInstConf: types.AccessConfig{Permission: types.AccessTypeOnlyAddress, Address: myAddr.String()}, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.ContractKeeper, keepers.BankKeeper - err := keepers.WasmKeeper.SetParams(ctx, types.Params{ - CodeUploadAccess: types.AllowEverybody, - InstantiateDefaultPermission: spec.srcPermission, - }) - require.NoError(t, err) - fundAccounts(t, ctx, accKeeper, bankKeeper, myAddr, deposit) - - codeID, _, err := keeper.Create(ctx, myAddr, hackatomWasm, nil) - require.NoError(t, err) - - codeInfo := keepers.WasmKeeper.GetCodeInfo(ctx, codeID) - require.NotNil(t, codeInfo) - assert.True(t, spec.expInstConf.Equals(codeInfo.InstantiateConfig), "got %#v", codeInfo.InstantiateConfig) - }) - } -} - -func TestCreateWithParamPermissions(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - otherAddr := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - - specs := map[string]struct { - policy AuthorizationPolicy - chainUpload types.AccessConfig - expError *errorsmod.Error - }{ - "default": { - policy: DefaultAuthorizationPolicy{}, - chainUpload: types.DefaultUploadAccess, - }, - "everybody": { - policy: DefaultAuthorizationPolicy{}, - chainUpload: types.AllowEverybody, - }, - "nobody": { - policy: DefaultAuthorizationPolicy{}, - chainUpload: types.AllowNobody, - expError: sdkerrors.ErrUnauthorized, - }, - "onlyAddress with matching address": { - policy: DefaultAuthorizationPolicy{}, - chainUpload: types.AccessTypeOnlyAddress.With(creator), - }, - "onlyAddress with non matching address": { - policy: DefaultAuthorizationPolicy{}, - chainUpload: types.AccessTypeOnlyAddress.With(otherAddr), - expError: sdkerrors.ErrUnauthorized, - }, - "gov: always allowed": { - policy: GovAuthorizationPolicy{}, - chainUpload: types.AllowNobody, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - params := types.DefaultParams() - params.CodeUploadAccess = spec.chainUpload - err := keepers.WasmKeeper.SetParams(ctx, params) - require.NoError(t, err) - keeper := NewPermissionedKeeper(keepers.WasmKeeper, spec.policy) - _, _, err = keeper.Create(ctx, creator, hackatomWasm, nil) - require.True(t, spec.expError.Is(err), err) - if spec.expError != nil { - return - } - }) - } -} - -// ensure that the user cannot set the code instantiate permission to something more permissive -// than the default -func TestEnforceValidPermissionsOnCreate(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.WasmKeeper - contractKeeper := keepers.ContractKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - other := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - - onlyCreator := types.AccessTypeOnlyAddress.With(creator) - onlyOther := types.AccessTypeOnlyAddress.With(other) - - specs := map[string]struct { - defaultPermssion types.AccessType - requestedPermission *types.AccessConfig - // grantedPermission is set iff no error - grantedPermission types.AccessConfig - // expError is nil iff the request is allowed - expError *errorsmod.Error - }{ - "override everybody": { - defaultPermssion: types.AccessTypeEverybody, - requestedPermission: &onlyCreator, - grantedPermission: onlyCreator, - }, - "default to everybody": { - defaultPermssion: types.AccessTypeEverybody, - requestedPermission: nil, - grantedPermission: types.AccessConfig{Permission: types.AccessTypeEverybody}, - }, - "explicitly set everybody": { - defaultPermssion: types.AccessTypeEverybody, - requestedPermission: &types.AccessConfig{Permission: types.AccessTypeEverybody}, - grantedPermission: types.AccessConfig{Permission: types.AccessTypeEverybody}, - }, - "cannot override nobody": { - defaultPermssion: types.AccessTypeNobody, - requestedPermission: &onlyCreator, - expError: sdkerrors.ErrUnauthorized, - }, - "default to nobody": { - defaultPermssion: types.AccessTypeNobody, - requestedPermission: nil, - grantedPermission: types.AccessConfig{Permission: types.AccessTypeNobody}, - }, - "only defaults to code creator": { - defaultPermssion: types.AccessTypeOnlyAddress, - requestedPermission: nil, - grantedPermission: onlyCreator, - }, - "can explicitly set to code creator": { - defaultPermssion: types.AccessTypeOnlyAddress, - requestedPermission: &onlyCreator, - grantedPermission: onlyCreator, - }, - "cannot override which address in only": { - defaultPermssion: types.AccessTypeOnlyAddress, - requestedPermission: &onlyOther, - expError: sdkerrors.ErrUnauthorized, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - params := types.DefaultParams() - params.InstantiateDefaultPermission = spec.defaultPermssion - err := keeper.SetParams(ctx, params) - require.NoError(t, err) - codeID, _, err := contractKeeper.Create(ctx, creator, hackatomWasm, spec.requestedPermission) - require.True(t, spec.expError.Is(err), err) - if spec.expError == nil { - codeInfo := keeper.GetCodeInfo(ctx, codeID) - require.Equal(t, codeInfo.InstantiateConfig, spec.grantedPermission) - } - }) - } -} - -func TestCreateDuplicate(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.ContractKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - - // create one copy - contractID, _, err := keeper.Create(ctx, creator, hackatomWasm, nil) - require.NoError(t, err) - require.Equal(t, uint64(1), contractID) - - // create second copy - duplicateID, _, err := keeper.Create(ctx, creator, hackatomWasm, nil) - require.NoError(t, err) - require.Equal(t, uint64(2), duplicateID) - - // and verify both content is proper - storedCode, err := keepers.WasmKeeper.GetByteCode(ctx, contractID) - require.NoError(t, err) - require.Equal(t, hackatomWasm, storedCode) - storedCode, err = keepers.WasmKeeper.GetByteCode(ctx, duplicateID) - require.NoError(t, err) - require.Equal(t, hackatomWasm, storedCode) -} - -func TestCreateWithSimulation(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - - ctx = ctx.WithBlockHeader(tmproto.Header{Height: 1}). - WithGasMeter(stypes.NewInfiniteGasMeter()) - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - - // create this once in simulation mode - contractID, _, err := keepers.ContractKeeper.Create(ctx, creator, hackatomWasm, nil) - require.NoError(t, err) - require.Equal(t, uint64(1), contractID) - - // then try to create it in non-simulation mode (should not fail) - ctx, keepers = CreateTestInput(t, false, AvailableCapabilities) - ctx = ctx.WithGasMeter(sdk.NewGasMeter(10_000_000)) - creator = keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - contractID, _, err = keepers.ContractKeeper.Create(ctx, creator, hackatomWasm, nil) - - require.NoError(t, err) - require.Equal(t, uint64(1), contractID) - - // and verify content - code, err := keepers.WasmKeeper.GetByteCode(ctx, contractID) - require.NoError(t, err) - require.Equal(t, code, hackatomWasm) -} - -func TestIsSimulationMode(t *testing.T) { - specs := map[string]struct { - ctx sdk.Context - exp bool - }{ - "genesis block": { - ctx: sdk.Context{}.WithBlockHeader(tmproto.Header{}).WithGasMeter(stypes.NewInfiniteGasMeter()), - exp: false, - }, - "any regular block": { - ctx: sdk.Context{}.WithBlockHeader(tmproto.Header{Height: 1}).WithGasMeter(stypes.NewGasMeter(10000000)), - exp: false, - }, - "simulation": { - ctx: sdk.Context{}.WithBlockHeader(tmproto.Header{Height: 1}).WithGasMeter(stypes.NewInfiniteGasMeter()), - exp: true, - }, - } - for msg := range specs { - t.Run(msg, func(t *testing.T) { - // assert.Equal(t, spec.exp, isSimulationMode(spec.ctx)) - }) - } -} - -func TestCreateWithGzippedPayload(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.ContractKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - - wasmCode, err := os.ReadFile("./testdata/hackatom.wasm.gzip") - require.NoError(t, err, "reading gzipped WASM code") - - contractID, _, err := keeper.Create(ctx, creator, wasmCode, nil) - require.NoError(t, err) - require.Equal(t, uint64(1), contractID) - // and verify content - storedCode, err := keepers.WasmKeeper.GetByteCode(ctx, contractID) - require.NoError(t, err) - require.Equal(t, hackatomWasm, storedCode) -} - -func TestCreateWithBrokenGzippedPayload(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.ContractKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - - wasmCode, err := os.ReadFile("./testdata/broken_crc.gzip") - require.NoError(t, err, "reading gzipped WASM code") - - gm := sdk.NewInfiniteGasMeter() - codeID, checksum, err := keeper.Create(ctx.WithGasMeter(gm), creator, wasmCode, nil) - require.Error(t, err) - assert.Empty(t, codeID) - assert.Empty(t, checksum) - assert.GreaterOrEqual(t, gm.GasConsumed(), sdk.Gas(121384)) // 809232 * 0.15 (default uncompress costs) = 121384 -} - -func TestInstantiate(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := sdk.AccAddress(bytes.Repeat([]byte{1}, address.Len)) - keepers.Faucet.Fund(ctx, creator, deposit...) - example := StoreHackatomExampleContract(t, ctx, keepers) - - initMsg := HackatomExampleInitMsg{ - Verifier: RandomAccountAddress(t), - Beneficiary: RandomAccountAddress(t), - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - - gasBefore := ctx.GasMeter().GasConsumed() - - em := sdk.NewEventManager() - // create with no balance is also legal - gotContractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx.WithEventManager(em), example.CodeID, creator, nil, initMsgBz, "demo contract 1", nil) - require.NoError(t, err) - require.Equal(t, "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr", gotContractAddr.String()) - - gasAfter := ctx.GasMeter().GasConsumed() - if types.EnableGasVerification { - require.Equal(t, uint64(0x1b5bc), gasAfter-gasBefore) - } - - // ensure it is stored properly - info := keepers.WasmKeeper.GetContractInfo(ctx, gotContractAddr) - require.NotNil(t, info) - assert.Equal(t, creator.String(), info.Creator) - assert.Equal(t, example.CodeID, info.CodeID) - assert.Equal(t, "demo contract 1", info.Label) - - exp := []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeInit, - CodeID: example.CodeID, - Updated: types.NewAbsoluteTxPosition(ctx), - Msg: initMsgBz, - }} - assert.Equal(t, exp, keepers.WasmKeeper.GetContractHistory(ctx, gotContractAddr)) - - // and events emitted - expEvt := sdk.Events{ - sdk.NewEvent("instantiate", - sdk.NewAttribute("_contract_address", gotContractAddr.String()), sdk.NewAttribute("code_id", "1")), - sdk.NewEvent("wasm", - sdk.NewAttribute("_contract_address", gotContractAddr.String()), sdk.NewAttribute("Let the", "hacking begin")), - } - assert.Equal(t, expEvt, em.Events()) -} - -func TestInstantiateWithDeposit(t *testing.T) { - var ( - bob = bytes.Repeat([]byte{1}, types.SDKAddrLen) - fred = bytes.Repeat([]byte{2}, types.SDKAddrLen) - - deposit = sdk.NewCoins(sdk.NewInt64Coin("denom", 100)) - initMsg = mustMarshal(t, HackatomExampleInitMsg{Verifier: fred, Beneficiary: bob}) - ) - - specs := map[string]struct { - srcActor sdk.AccAddress - expError bool - fundAddr bool - }{ - "address with funds": { - srcActor: bob, - fundAddr: true, - }, - "address without funds": { - srcActor: bob, - expError: true, - }, - "blocked address": { - srcActor: authtypes.NewModuleAddress(authtypes.FeeCollectorName), - fundAddr: true, - expError: false, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - accKeeper, bankKeeper, keeper := keepers.AccountKeeper, keepers.BankKeeper, keepers.ContractKeeper - - if spec.fundAddr { - fundAccounts(t, ctx, accKeeper, bankKeeper, spec.srcActor, sdk.NewCoins(sdk.NewInt64Coin("denom", 200))) - } - contractID, _, err := keeper.Create(ctx, spec.srcActor, hackatomWasm, nil) - require.NoError(t, err) - - // when - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, spec.srcActor, nil, initMsg, "my label", deposit) - // then - if spec.expError { - require.Error(t, err) - return - } - require.NoError(t, err) - balances := bankKeeper.GetAllBalances(ctx, addr) - assert.Equal(t, deposit, balances) - }) - } -} - -func TestInstantiateWithPermissions(t *testing.T) { - var ( - deposit = sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - myAddr = bytes.Repeat([]byte{1}, types.SDKAddrLen) - otherAddr = bytes.Repeat([]byte{2}, types.SDKAddrLen) - anyAddr = bytes.Repeat([]byte{3}, types.SDKAddrLen) - ) - - initMsg := HackatomExampleInitMsg{ - Verifier: anyAddr, - Beneficiary: anyAddr, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - - specs := map[string]struct { - srcPermission types.AccessConfig - srcActor sdk.AccAddress - expError *errorsmod.Error - }{ - "default": { - srcPermission: types.DefaultUploadAccess, - srcActor: anyAddr, - }, - "everybody": { - srcPermission: types.AllowEverybody, - srcActor: anyAddr, - }, - "nobody": { - srcPermission: types.AllowNobody, - srcActor: myAddr, - expError: sdkerrors.ErrUnauthorized, - }, - "onlyAddress with matching address": { - srcPermission: types.AccessTypeOnlyAddress.With(myAddr), - srcActor: myAddr, - }, - "onlyAddress with non matching address": { - srcActor: myAddr, - srcPermission: types.AccessTypeOnlyAddress.With(otherAddr), - expError: sdkerrors.ErrUnauthorized, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - accKeeper, bankKeeper, keeper := keepers.AccountKeeper, keepers.BankKeeper, keepers.ContractKeeper - fundAccounts(t, ctx, accKeeper, bankKeeper, spec.srcActor, deposit) - - contractID, _, err := keeper.Create(ctx, myAddr, hackatomWasm, &spec.srcPermission) - require.NoError(t, err) - - _, _, err = keepers.ContractKeeper.Instantiate(ctx, contractID, spec.srcActor, nil, initMsgBz, "demo contract 1", nil) - assert.True(t, spec.expError.Is(err), "got %+v", err) - }) - } -} - -func TestInstantiateWithAccounts(t *testing.T) { - parentCtx, keepers := CreateTestInput(t, false, AvailableCapabilities) - example := StoreHackatomExampleContract(t, parentCtx, keepers) - require.Equal(t, uint64(1), example.CodeID) - initMsg := mustMarshal(t, HackatomExampleInitMsg{Verifier: RandomAccountAddress(t), Beneficiary: RandomAccountAddress(t)}) - - senderAddr := DeterministicAccountAddress(t, 1) - keepers.Faucet.Fund(parentCtx, senderAddr, sdk.NewInt64Coin("denom", 100000000)) - mySalt := []byte(`my salt`) - contractAddr := BuildContractAddressPredictable(example.Checksum, senderAddr, mySalt, []byte{}) - - lastAccountNumber := keepers.AccountKeeper.GetAccount(parentCtx, senderAddr).GetAccountNumber() - - specs := map[string]struct { - option Option - account authtypes.AccountI - initBalance sdk.Coin - deposit sdk.Coins - expErr error - expAccount authtypes.AccountI - expBalance sdk.Coins - }{ - "unused BaseAccount exists": { - account: authtypes.NewBaseAccount(contractAddr, nil, 0, 0), - initBalance: sdk.NewInt64Coin("denom", 100000000), - expAccount: authtypes.NewBaseAccount(contractAddr, nil, lastAccountNumber+1, 0), // +1 for next seq - expBalance: sdk.NewCoins(sdk.NewInt64Coin("denom", 100000000)), - }, - "BaseAccount with sequence exists": { - account: authtypes.NewBaseAccount(contractAddr, nil, 0, 1), - expErr: types.ErrAccountExists, - }, - "BaseAccount with pubkey exists": { - account: authtypes.NewBaseAccount(contractAddr, &ed25519.PubKey{}, 0, 0), - expErr: types.ErrAccountExists, - }, - "no account existed": { - expAccount: authtypes.NewBaseAccount(contractAddr, nil, lastAccountNumber+1, 0), // +1 for next seq, - expBalance: sdk.NewCoins(), - }, - "no account existed before create with deposit": { - expAccount: authtypes.NewBaseAccount(contractAddr, nil, lastAccountNumber+1, 0), // +1 for next seq - deposit: sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(1_000))), - expBalance: sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(1_000))), - }, - "prunable DelayedVestingAccount gets overwritten": { - account: vestingtypes.NewDelayedVestingAccount( - authtypes.NewBaseAccount(contractAddr, nil, 0, 0), - sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(1_000))), time.Now().Add(30*time.Hour).Unix()), - initBalance: sdk.NewCoin("denom", sdk.NewInt(1_000)), - deposit: sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(1))), - expAccount: authtypes.NewBaseAccount(contractAddr, nil, lastAccountNumber+2, 0), // +1 for next seq, +1 for spec.account created - expBalance: sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(1))), - }, - "prunable ContinuousVestingAccount gets overwritten": { - account: vestingtypes.NewContinuousVestingAccount( - authtypes.NewBaseAccount(contractAddr, nil, 0, 0), - sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(1_000))), time.Now().Add(time.Hour).Unix(), time.Now().Add(2*time.Hour).Unix()), - initBalance: sdk.NewCoin("denom", sdk.NewInt(1_000)), - deposit: sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(1))), - expAccount: authtypes.NewBaseAccount(contractAddr, nil, lastAccountNumber+2, 0), // +1 for next seq, +1 for spec.account created - expBalance: sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(1))), - }, - "prunable account without balance gets overwritten": { - account: vestingtypes.NewContinuousVestingAccount( - authtypes.NewBaseAccount(contractAddr, nil, 0, 0), - sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(0))), time.Now().Add(time.Hour).Unix(), time.Now().Add(2*time.Hour).Unix()), - expAccount: authtypes.NewBaseAccount(contractAddr, nil, lastAccountNumber+2, 0), // +1 for next seq, +1 for spec.account created - expBalance: sdk.NewCoins(), - }, - "unknown account type is rejected with error": { - account: authtypes.NewModuleAccount( - authtypes.NewBaseAccount(contractAddr, nil, 0, 0), - "testing", - ), - initBalance: sdk.NewCoin("denom", sdk.NewInt(1_000)), - expErr: types.ErrAccountExists, - }, - "with option used to set non default type to accept list": { - option: WithAcceptedAccountTypesOnContractInstantiation(&vestingtypes.DelayedVestingAccount{}), - account: vestingtypes.NewDelayedVestingAccount( - authtypes.NewBaseAccount(contractAddr, nil, 0, 0), - sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(1_000))), time.Now().Add(30*time.Hour).Unix()), - initBalance: sdk.NewCoin("denom", sdk.NewInt(1_000)), - deposit: sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(1))), - expAccount: vestingtypes.NewDelayedVestingAccount(authtypes.NewBaseAccount(contractAddr, nil, lastAccountNumber+1, 0), - sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(1_000))), time.Now().Add(30*time.Hour).Unix()), - expBalance: sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(1_001))), - }, - "pruning account fails": { - option: WithAccountPruner(wasmtesting.AccountPrunerMock{CleanupExistingAccountFn: func(ctx sdk.Context, existingAccount authtypes.AccountI) (handled bool, err error) { - return false, types.ErrUnsupportedForContract.Wrap("testing") - }}), - account: vestingtypes.NewDelayedVestingAccount( - authtypes.NewBaseAccount(contractAddr, nil, 0, 0), - sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(1_000))), time.Now().Add(30*time.Hour).Unix()), - expErr: types.ErrUnsupportedForContract, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - ctx, _ := parentCtx.CacheContext() - if spec.account != nil { - keepers.AccountKeeper.SetAccount(ctx, keepers.AccountKeeper.NewAccount(ctx, spec.account)) - } - if !spec.initBalance.IsNil() { - keepers.Faucet.Fund(ctx, spec.account.GetAddress(), spec.initBalance) - } - if spec.option != nil { - spec.option.apply(keepers.WasmKeeper) - } - defer func() { - if spec.option != nil { // reset - WithAcceptedAccountTypesOnContractInstantiation(&authtypes.BaseAccount{}).apply(keepers.WasmKeeper) - WithAccountPruner(NewVestingCoinBurner(keepers.BankKeeper)).apply(keepers.WasmKeeper) - } - }() - // when - gotAddr, _, gotErr := keepers.ContractKeeper.Instantiate2(ctx, 1, senderAddr, nil, initMsg, myTestLabel, spec.deposit, mySalt, false) - if spec.expErr != nil { - assert.ErrorIs(t, gotErr, spec.expErr) - return - } - require.NoError(t, gotErr) - assert.Equal(t, contractAddr, gotAddr) - // and - gotAcc := keepers.AccountKeeper.GetAccount(ctx, contractAddr) - assert.Equal(t, spec.expAccount, gotAcc) - // and - gotBalance := keepers.BankKeeper.GetAllBalances(ctx, contractAddr) - assert.Equal(t, spec.expBalance, gotBalance) - }) - } -} - -func TestInstantiateWithNonExistingCodeID(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - - initMsg := HackatomExampleInitMsg{} - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - - const nonExistingCodeID = 9999 - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, nonExistingCodeID, creator, nil, initMsgBz, "demo contract 2", nil) - require.True(t, types.ErrNotFound.Is(err), err) - require.Nil(t, addr) -} - -func TestInstantiateWithContractDataResponse(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - - wasmerMock := &wasmtesting.MockWasmer{ - InstantiateFn: func(codeID wasmvm.Checksum, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, initMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - return &wasmvmtypes.Response{Data: []byte("my-response-data")}, 0, nil - }, - AnalyzeCodeFn: wasmtesting.WithoutIBCAnalyzeFn, - CreateFn: wasmtesting.NoOpCreateFn, - } - - example := StoreRandomContract(t, ctx, keepers, wasmerMock) - _, data, err := keepers.ContractKeeper.Instantiate(ctx, example.CodeID, example.CreatorAddr, nil, nil, "test", nil) - require.NoError(t, err) - assert.Equal(t, []byte("my-response-data"), data) -} - -func TestInstantiateWithContractFactoryChildQueriesParent(t *testing.T) { - // Scenario: - // given a factory contract stored - // when instantiated, the contract creates a new child contract instance - // and the child contracts queries the senders ContractInfo on instantiation - // then the factory contract's ContractInfo should be returned to the child contract - // - // see also: https://github.com/terpnetwork/terp-core/issues/896 - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.WasmKeeper - - var instantiationCount int - callbacks := make([]func(codeID wasmvm.Checksum, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, initMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error), 2) - wasmerMock := &wasmtesting.MockWasmer{ - // dispatch instantiation calls to callbacks - InstantiateFn: func(codeID wasmvm.Checksum, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, initMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - require.Greater(t, len(callbacks), instantiationCount, "unexpected call to instantiation") - do := callbacks[instantiationCount] - instantiationCount++ - return do(codeID, env, info, initMsg, store, goapi, querier, gasMeter, gasLimit, deserCost) - }, - AnalyzeCodeFn: wasmtesting.WithoutIBCAnalyzeFn, - CreateFn: wasmtesting.NoOpCreateFn, - } - - // overwrite wasmvm in router - router := baseapp.NewMsgServiceRouter() - router.SetInterfaceRegistry(keepers.EncodingConfig.InterfaceRegistry) - types.RegisterMsgServer(router, NewMsgServerImpl(keeper)) - keeper.messenger = NewDefaultMessageHandler(router, nil, nil, nil, keepers.EncodingConfig.Marshaler, nil) - // overwrite wasmvm in response handler - keeper.wasmVMResponseHandler = NewDefaultWasmVMContractResponseHandler(NewMessageDispatcher(keeper.messenger, keeper)) - - example := StoreRandomContract(t, ctx, keepers, wasmerMock) - // factory contract - callbacks[0] = func(codeID wasmvm.Checksum, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, initMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - t.Log("called factory") - return &wasmvmtypes.Response{Data: []byte("parent"), Messages: []wasmvmtypes.SubMsg{ - { - ID: 1, ReplyOn: wasmvmtypes.ReplyNever, - Msg: wasmvmtypes.CosmosMsg{ - Wasm: &wasmvmtypes.WasmMsg{ - Instantiate: &wasmvmtypes.InstantiateMsg{CodeID: example.CodeID, Msg: []byte(`{}`), Label: "child"}, - }, - }, - }, - }}, 0, nil - } - - // child contract - var capturedSenderAddr string - var capturedCodeInfo []byte - callbacks[1] = func(codeID wasmvm.Checksum, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, initMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - t.Log("called child") - capturedSenderAddr = info.Sender - var err error - capturedCodeInfo, err = querier.Query(wasmvmtypes.QueryRequest{ - Wasm: &wasmvmtypes.WasmQuery{ - ContractInfo: &wasmvmtypes.ContractInfoQuery{ContractAddr: info.Sender}, - }, - }, gasLimit) - require.NoError(t, err) - return &wasmvmtypes.Response{Data: []byte("child")}, 0, nil - } - - // when - parentAddr, data, err := keepers.ContractKeeper.Instantiate(ctx, example.CodeID, example.CreatorAddr, nil, nil, "test", nil) - - // then - require.NoError(t, err) - assert.Equal(t, []byte("parent"), data) - require.Equal(t, parentAddr.String(), capturedSenderAddr) - expCodeInfo := fmt.Sprintf(`{"code_id":%d,"creator":%q,"pinned":false}`, example.CodeID, example.CreatorAddr.String()) - assert.JSONEq(t, expCodeInfo, string(capturedCodeInfo)) -} - -func TestExecute(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.ContractKeeper, keepers.BankKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) - creator := DeterministicAccountAddress(t, 1) - keepers.Faucet.Fund(ctx, creator, deposit.Add(deposit...)...) - fred := keepers.Faucet.NewFundedRandomAccount(ctx, topUp...) - bob := RandomAccountAddress(t) - - contractID, _, err := keeper.Create(ctx, creator, hackatomWasm, nil) - require.NoError(t, err) - - initMsg := HackatomExampleInitMsg{ - Verifier: fred, - Beneficiary: bob, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, nil, initMsgBz, "demo contract 3", deposit) - require.NoError(t, err) - require.Equal(t, "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr", addr.String()) - - // ensure bob doesn't exist - bobAcct := accKeeper.GetAccount(ctx, bob) - require.Nil(t, bobAcct) - - // ensure funder has reduced balance - creatorAcct := accKeeper.GetAccount(ctx, creator) - require.NotNil(t, creatorAcct) - // we started at 2*deposit, should have spent one above - assert.Equal(t, deposit, bankKeeper.GetAllBalances(ctx, creatorAcct.GetAddress())) - - // ensure contract has updated balance - contractAcct := accKeeper.GetAccount(ctx, addr) - require.NotNil(t, contractAcct) - assert.Equal(t, deposit, bankKeeper.GetAllBalances(ctx, contractAcct.GetAddress())) - - // unauthorized - trialCtx so we don't change state - trialCtx := ctx.WithMultiStore(ctx.MultiStore().CacheWrap().(sdk.MultiStore)) - _, err = keepers.ContractKeeper.Execute(trialCtx, addr, creator, []byte(`{"release":{}}`), nil) - require.Error(t, err) - require.True(t, errors.Is(err, types.ErrExecuteFailed)) - require.Equal(t, "Unauthorized: execute wasm contract failed", err.Error()) - - // verifier can execute, and get proper gas amount - start := time.Now() - gasBefore := ctx.GasMeter().GasConsumed() - em := sdk.NewEventManager() - // when - res, err := keepers.ContractKeeper.Execute(ctx.WithEventManager(em), addr, fred, []byte(`{"release":{}}`), topUp) - diff := time.Since(start) - require.NoError(t, err) - require.NotNil(t, res) - - // make sure gas is properly deducted from ctx - gasAfter := ctx.GasMeter().GasConsumed() - if types.EnableGasVerification { - require.Equal(t, uint64(0x1a154), gasAfter-gasBefore) - } - // ensure bob now exists and got both payments released - bobAcct = accKeeper.GetAccount(ctx, bob) - require.NotNil(t, bobAcct) - balance := bankKeeper.GetAllBalances(ctx, bobAcct.GetAddress()) - assert.Equal(t, deposit.Add(topUp...), balance) - - // ensure contract has updated balance - contractAcct = accKeeper.GetAccount(ctx, addr) - require.NotNil(t, contractAcct) - assert.Equal(t, sdk.Coins{}, bankKeeper.GetAllBalances(ctx, contractAcct.GetAddress())) - - // and events emitted - require.Len(t, em.Events(), 9) - expEvt := sdk.NewEvent("execute", - sdk.NewAttribute("_contract_address", addr.String())) - assert.Equal(t, expEvt, em.Events()[3], prettyEvents(t, em.Events())) - - t.Logf("Duration: %v (%d gas)\n", diff, gasAfter-gasBefore) -} - -func TestExecuteWithDeposit(t *testing.T) { - var ( - bob = bytes.Repeat([]byte{1}, types.SDKAddrLen) - fred = bytes.Repeat([]byte{2}, types.SDKAddrLen) - blockedAddr = authtypes.NewModuleAddress(distributiontypes.ModuleName) - deposit = sdk.NewCoins(sdk.NewInt64Coin("denom", 100)) - ) - - specs := map[string]struct { - srcActor sdk.AccAddress - beneficiary sdk.AccAddress - newBankParams *banktypes.Params - expError bool - fundAddr bool - }{ - "actor with funds": { - srcActor: bob, - fundAddr: true, - beneficiary: fred, - }, - "actor without funds": { - srcActor: bob, - beneficiary: fred, - expError: true, - }, - "blocked address as actor": { - srcActor: blockedAddr, - fundAddr: true, - beneficiary: fred, - expError: false, - }, - "coin transfer with all transfers disabled": { - srcActor: bob, - fundAddr: true, - beneficiary: fred, - newBankParams: &banktypes.Params{DefaultSendEnabled: false}, - expError: true, - }, - "coin transfer with transfer denom disabled": { - srcActor: bob, - fundAddr: true, - beneficiary: fred, - newBankParams: &banktypes.Params{ - DefaultSendEnabled: true, - SendEnabled: []*banktypes.SendEnabled{{Denom: "denom", Enabled: false}}, - }, - expError: true, - }, - "blocked address as beneficiary": { - srcActor: bob, - fundAddr: true, - beneficiary: blockedAddr, - expError: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - accKeeper, bankKeeper, keeper := keepers.AccountKeeper, keepers.BankKeeper, keepers.ContractKeeper - if spec.newBankParams != nil { - err := bankKeeper.SetParams(ctx, *spec.newBankParams) - require.NoError(t, err) - } - if spec.fundAddr { - fundAccounts(t, ctx, accKeeper, bankKeeper, spec.srcActor, sdk.NewCoins(sdk.NewInt64Coin("denom", 200))) - } - codeID, _, err := keeper.Create(ctx, spec.srcActor, hackatomWasm, nil) - require.NoError(t, err) - - initMsg := HackatomExampleInitMsg{Verifier: spec.srcActor, Beneficiary: spec.beneficiary} - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, spec.srcActor, nil, initMsgBz, "my label", nil) - require.NoError(t, err) - - // when - _, err = keepers.ContractKeeper.Execute(ctx, contractAddr, spec.srcActor, []byte(`{"release":{}}`), deposit) - - // then - if spec.expError { - require.Error(t, err) - return - } - require.NoError(t, err) - balances := bankKeeper.GetAllBalances(ctx, spec.beneficiary) - assert.Equal(t, deposit, balances) - }) - } -} - -func TestExecuteWithNonExistingAddress(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.ContractKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := DeterministicAccountAddress(t, 1) - keepers.Faucet.Fund(ctx, creator, deposit.Add(deposit...)...) - - // unauthorized - trialCtx so we don't change state - nonExistingAddress := RandomAccountAddress(t) - _, err := keeper.Execute(ctx, nonExistingAddress, creator, []byte(`{}`), nil) - require.True(t, types.ErrNotFound.Is(err), err) -} - -func TestExecuteWithPanic(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.ContractKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) - creator := DeterministicAccountAddress(t, 1) - keepers.Faucet.Fund(ctx, creator, deposit.Add(deposit...)...) - fred := keepers.Faucet.NewFundedRandomAccount(ctx, topUp...) - - contractID, _, err := keeper.Create(ctx, creator, hackatomWasm, nil) - require.NoError(t, err) - - _, bob := keyPubAddr() - initMsg := HackatomExampleInitMsg{ - Verifier: fred, - Beneficiary: bob, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, nil, initMsgBz, "demo contract 4", deposit) - require.NoError(t, err) - - // let's make sure we get a reasonable error, no panic/crash - _, err = keepers.ContractKeeper.Execute(ctx, addr, fred, []byte(`{"panic":{}}`), topUp) - require.Error(t, err) - require.True(t, errors.Is(err, types.ErrExecuteFailed)) - // test with contains as "Display" implementation of the Wasmer "RuntimeError" is different for Mac and Linux - assert.Contains(t, err.Error(), "Error calling the VM: Error executing Wasm: Wasmer runtime error: RuntimeError: Aborted: panicked at 'This page intentionally faulted', src/contract.rs:169:5: execute wasm contract failed") -} - -func TestExecuteWithCpuLoop(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.ContractKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) - creator := DeterministicAccountAddress(t, 1) - keepers.Faucet.Fund(ctx, creator, deposit.Add(deposit...)...) - fred := keepers.Faucet.NewFundedRandomAccount(ctx, topUp...) - - contractID, _, err := keeper.Create(ctx, creator, hackatomWasm, nil) - require.NoError(t, err) - - _, bob := keyPubAddr() - initMsg := HackatomExampleInitMsg{ - Verifier: fred, - Beneficiary: bob, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, nil, initMsgBz, "demo contract 5", deposit) - require.NoError(t, err) - - // make sure we set a limit before calling - var gasLimit uint64 = 400_000 - ctx = ctx.WithGasMeter(sdk.NewGasMeter(gasLimit)) - require.Equal(t, uint64(0), ctx.GasMeter().GasConsumed()) - - // ensure we get an out of gas panic - defer func() { - r := recover() - require.NotNil(t, r) - _, ok := r.(sdk.ErrorOutOfGas) - require.True(t, ok, "%v", r) - }() - - // this should throw out of gas exception (panic) - _, _ = keepers.ContractKeeper.Execute(ctx, addr, fred, []byte(`{"cpu_loop":{}}`), nil) - require.True(t, false, "We must panic before this line") -} - -func TestExecuteWithStorageLoop(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - - keeper := keepers.ContractKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) - creator := DeterministicAccountAddress(t, 1) - keepers.Faucet.Fund(ctx, creator, deposit.Add(deposit...)...) - fred := keepers.Faucet.NewFundedRandomAccount(ctx, topUp...) - - contractID, _, err := keeper.Create(ctx, creator, hackatomWasm, nil) - require.NoError(t, err) - - _, bob := keyPubAddr() - initMsg := HackatomExampleInitMsg{ - Verifier: fred, - Beneficiary: bob, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, nil, initMsgBz, "demo contract 6", deposit) - require.NoError(t, err) - - // make sure we set a limit before calling - var gasLimit uint64 = 400_002 - ctx = ctx.WithGasMeter(sdk.NewGasMeter(gasLimit)) - require.Equal(t, uint64(0), ctx.GasMeter().GasConsumed()) - - // ensure we get an out of gas panic - defer func() { - r := recover() - require.NotNil(t, r) - _, ok := r.(sdk.ErrorOutOfGas) - require.True(t, ok, "%v", r) - }() - - // this should throw out of gas exception (panic) - _, _ = keepers.ContractKeeper.Execute(ctx, addr, fred, []byte(`{"storage_loop":{}}`), nil) - require.True(t, false, "We must panic before this line") -} - -func TestMigrate(t *testing.T) { - parentCtx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.ContractKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) - creator := DeterministicAccountAddress(t, 1) - keepers.Faucet.Fund(parentCtx, creator, deposit.Add(deposit...)...) - fred := DeterministicAccountAddress(t, 2) - keepers.Faucet.Fund(parentCtx, fred, topUp...) - - originalCodeID := StoreHackatomExampleContract(t, parentCtx, keepers).CodeID - newCodeID := StoreHackatomExampleContract(t, parentCtx, keepers).CodeID - ibcCodeID := StoreIBCReflectContract(t, parentCtx, keepers).CodeID - require.NotEqual(t, originalCodeID, newCodeID) - - restrictedCodeExample := StoreHackatomExampleContract(t, parentCtx, keepers) - require.NoError(t, keeper.SetAccessConfig(parentCtx, restrictedCodeExample.CodeID, restrictedCodeExample.CreatorAddr, types.AllowNobody)) - require.NotEqual(t, originalCodeID, restrictedCodeExample.CodeID) - - anyAddr := RandomAccountAddress(t) - newVerifierAddr := RandomAccountAddress(t) - initMsgBz := HackatomExampleInitMsg{ - Verifier: fred, - Beneficiary: anyAddr, - }.GetBytes(t) - - migMsg := struct { - Verifier sdk.AccAddress `json:"verifier"` - }{Verifier: newVerifierAddr} - migMsgBz, err := json.Marshal(migMsg) - require.NoError(t, err) - - specs := map[string]struct { - admin sdk.AccAddress - overrideContractAddr sdk.AccAddress - caller sdk.AccAddress - fromCodeID uint64 - toCodeID uint64 - migrateMsg []byte - expErr *errorsmod.Error - expVerifier sdk.AccAddress - expIBCPort bool - initMsg []byte - }{ - "all good with same code id": { - admin: creator, - caller: creator, - initMsg: initMsgBz, - fromCodeID: originalCodeID, - toCodeID: originalCodeID, - migrateMsg: migMsgBz, - expVerifier: newVerifierAddr, - }, - "all good with different code id": { - admin: creator, - caller: creator, - initMsg: initMsgBz, - fromCodeID: originalCodeID, - toCodeID: newCodeID, - migrateMsg: migMsgBz, - expVerifier: newVerifierAddr, - }, - "all good with admin set": { - admin: fred, - caller: fred, - initMsg: initMsgBz, - fromCodeID: originalCodeID, - toCodeID: newCodeID, - migrateMsg: migMsgBz, - expVerifier: newVerifierAddr, - }, - "adds IBC port for IBC enabled contracts": { - admin: fred, - caller: fred, - initMsg: initMsgBz, - fromCodeID: originalCodeID, - toCodeID: ibcCodeID, - migrateMsg: []byte(`{}`), - expIBCPort: true, - expVerifier: fred, // not updated - }, - "prevent migration when admin was not set on instantiate": { - caller: creator, - initMsg: initMsgBz, - fromCodeID: originalCodeID, - toCodeID: originalCodeID, - expErr: sdkerrors.ErrUnauthorized, - }, - "prevent migration when not sent by admin": { - caller: creator, - admin: fred, - initMsg: initMsgBz, - fromCodeID: originalCodeID, - toCodeID: originalCodeID, - expErr: sdkerrors.ErrUnauthorized, - }, - "prevent migration when new code is restricted": { - admin: creator, - caller: creator, - initMsg: initMsgBz, - fromCodeID: originalCodeID, - toCodeID: restrictedCodeExample.CodeID, - migrateMsg: migMsgBz, - expErr: sdkerrors.ErrUnauthorized, - }, - "fail with non existing code id": { - admin: creator, - caller: creator, - initMsg: initMsgBz, - fromCodeID: originalCodeID, - toCodeID: 99999, - expErr: sdkerrors.ErrInvalidRequest, - }, - "fail with non existing contract addr": { - admin: creator, - caller: creator, - initMsg: initMsgBz, - overrideContractAddr: anyAddr, - fromCodeID: originalCodeID, - toCodeID: originalCodeID, - expErr: sdkerrors.ErrInvalidRequest, - }, - "fail in contract with invalid migrate msg": { - admin: creator, - caller: creator, - initMsg: initMsgBz, - fromCodeID: originalCodeID, - toCodeID: originalCodeID, - migrateMsg: bytes.Repeat([]byte{0x1}, 7), - expErr: types.ErrMigrationFailed, - }, - "fail in contract without migrate msg": { - admin: creator, - caller: creator, - initMsg: initMsgBz, - fromCodeID: originalCodeID, - toCodeID: originalCodeID, - expErr: types.ErrMigrationFailed, - }, - "fail when no IBC callbacks": { - admin: fred, - caller: fred, - initMsg: IBCReflectInitMsg{ReflectCodeID: StoreReflectContract(t, parentCtx, keepers).CodeID}.GetBytes(t), - fromCodeID: ibcCodeID, - toCodeID: newCodeID, - migrateMsg: migMsgBz, - expErr: types.ErrMigrationFailed, - }, - } - - blockHeight := parentCtx.BlockHeight() - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - // given a contract instance - ctx, _ := parentCtx.WithBlockHeight(blockHeight + 1).CacheContext() - blockHeight++ - - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, spec.fromCodeID, creator, spec.admin, spec.initMsg, "demo contract", nil) - require.NoError(t, err) - if spec.overrideContractAddr != nil { - contractAddr = spec.overrideContractAddr - } - // when - _, err = keeper.Migrate(ctx, contractAddr, spec.caller, spec.toCodeID, spec.migrateMsg) - - // then - require.True(t, spec.expErr.Is(err), "expected %v but got %+v", spec.expErr, err) - if spec.expErr != nil { - return - } - cInfo := keepers.WasmKeeper.GetContractInfo(ctx, contractAddr) - assert.Equal(t, spec.toCodeID, cInfo.CodeID) - assert.Equal(t, spec.expIBCPort, cInfo.IBCPortID != "", cInfo.IBCPortID) - - expHistory := []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeInit, - CodeID: spec.fromCodeID, - Updated: types.NewAbsoluteTxPosition(ctx), - Msg: initMsgBz, - }, { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: spec.toCodeID, - Updated: types.NewAbsoluteTxPosition(ctx), - Msg: spec.migrateMsg, - }} - assert.Equal(t, expHistory, keepers.WasmKeeper.GetContractHistory(ctx, contractAddr)) - - // and verify contract state - raw := keepers.WasmKeeper.QueryRaw(ctx, contractAddr, []byte("config")) - var stored map[string]string - require.NoError(t, json.Unmarshal(raw, &stored)) - require.Contains(t, stored, "verifier") - require.NoError(t, err) - assert.Equal(t, spec.expVerifier.String(), stored["verifier"]) - }) - } -} - -func TestMigrateReplacesTheSecondIndex(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - example := InstantiateHackatomExampleContract(t, ctx, keepers) - - // then assert a second index exists - store := ctx.KVStore(keepers.WasmKeeper.storeKey) - oldContractInfo := keepers.WasmKeeper.GetContractInfo(ctx, example.Contract) - require.NotNil(t, oldContractInfo) - createHistoryEntry := types.ContractCodeHistoryEntry{ - CodeID: example.CodeID, - Updated: types.NewAbsoluteTxPosition(ctx), - } - exists := store.Has(types.GetContractByCreatedSecondaryIndexKey(example.Contract, createHistoryEntry)) - require.True(t, exists) - - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) // increment for different block - // when do migrate - newCodeExample := StoreBurnerExampleContract(t, ctx, keepers) - migMsgBz := BurnerExampleInitMsg{Payout: example.CreatorAddr}.GetBytes(t) - _, err := keepers.ContractKeeper.Migrate(ctx, example.Contract, example.CreatorAddr, newCodeExample.CodeID, migMsgBz) - require.NoError(t, err) - - // then the new index exists - migrateHistoryEntry := types.ContractCodeHistoryEntry{ - CodeID: newCodeExample.CodeID, - Updated: types.NewAbsoluteTxPosition(ctx), - } - exists = store.Has(types.GetContractByCreatedSecondaryIndexKey(example.Contract, migrateHistoryEntry)) - require.True(t, exists) - // and the old index was removed - exists = store.Has(types.GetContractByCreatedSecondaryIndexKey(example.Contract, createHistoryEntry)) - require.False(t, exists) -} - -func TestMigrateWithDispatchedMessage(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.ContractKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := DeterministicAccountAddress(t, 1) - keepers.Faucet.Fund(ctx, creator, deposit.Add(deposit...)...) - fred := keepers.Faucet.NewFundedRandomAccount(ctx, sdk.NewInt64Coin("denom", 5000)) - - burnerCode, err := os.ReadFile("./testdata/burner.wasm") - require.NoError(t, err) - - originalContractID, _, err := keeper.Create(ctx, creator, hackatomWasm, nil) - require.NoError(t, err) - burnerContractID, _, err := keeper.Create(ctx, creator, burnerCode, nil) - require.NoError(t, err) - require.NotEqual(t, originalContractID, burnerContractID) - - _, myPayoutAddr := keyPubAddr() - initMsg := HackatomExampleInitMsg{ - Verifier: fred, - Beneficiary: fred, - } - initMsgBz := initMsg.GetBytes(t) - - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, originalContractID, creator, fred, initMsgBz, "demo contract", deposit) - require.NoError(t, err) - - migMsgBz := BurnerExampleInitMsg{Payout: myPayoutAddr}.GetBytes(t) - ctx = ctx.WithEventManager(sdk.NewEventManager()).WithBlockHeight(ctx.BlockHeight() + 1) - data, err := keeper.Migrate(ctx, contractAddr, fred, burnerContractID, migMsgBz) - require.NoError(t, err) - assert.Equal(t, "burnt 1 keys", string(data)) - type dict map[string]interface{} - expEvents := []dict{ - { - "Type": "migrate", - "Attr": []dict{ - {"code_id": "2"}, - {"_contract_address": contractAddr}, - }, - }, - { - "Type": "wasm", - "Attr": []dict{ - {"_contract_address": contractAddr}, - {"action": "burn"}, - {"payout": myPayoutAddr}, - }, - }, - { - "Type": "coin_spent", - "Attr": []dict{ - {"spender": contractAddr}, - {"amount": "100000denom"}, - }, - }, - { - "Type": "coin_received", - "Attr": []dict{ - {"receiver": myPayoutAddr}, - {"amount": "100000denom"}, - }, - }, - { - "Type": "transfer", - "Attr": []dict{ - {"recipient": myPayoutAddr}, - {"sender": contractAddr}, - {"amount": "100000denom"}, - }, - }, - } - expJSONEvts := string(mustMarshal(t, expEvents)) - assert.JSONEq(t, expJSONEvts, prettyEvents(t, ctx.EventManager().Events()), prettyEvents(t, ctx.EventManager().Events())) - - // all persistent data cleared - m := keepers.WasmKeeper.QueryRaw(ctx, contractAddr, []byte("config")) - require.Len(t, m, 0) - - // and all deposit tokens sent to myPayoutAddr - balance := keepers.BankKeeper.GetAllBalances(ctx, myPayoutAddr) - assert.Equal(t, deposit, balance) -} - -func TestIterateContractsByCode(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - k, c := keepers.WasmKeeper, keepers.ContractKeeper - example1 := InstantiateHackatomExampleContract(t, ctx, keepers) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - example2 := InstantiateIBCReflectContract(t, ctx, keepers) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - initMsg := HackatomExampleInitMsg{ - Verifier: RandomAccountAddress(t), - Beneficiary: RandomAccountAddress(t), - }.GetBytes(t) - contractAddr3, _, err := c.Instantiate(ctx, example1.CodeID, example1.CreatorAddr, nil, initMsg, "foo", nil) - require.NoError(t, err) - specs := map[string]struct { - codeID uint64 - exp []sdk.AccAddress - }{ - "multiple results": { - codeID: example1.CodeID, - exp: []sdk.AccAddress{example1.Contract, contractAddr3}, - }, - "single results": { - codeID: example2.CodeID, - exp: []sdk.AccAddress{example2.Contract}, - }, - "empty results": { - codeID: 99999, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - var gotAddr []sdk.AccAddress - k.IterateContractsByCode(ctx, spec.codeID, func(address sdk.AccAddress) bool { - gotAddr = append(gotAddr, address) - return false - }) - assert.Equal(t, spec.exp, gotAddr) - }) - } -} - -func TestIterateContractsByCodeWithMigration(t *testing.T) { - // mock migration so that it does not fail when migrate example1 to example2.codeID - mockWasmVM := wasmtesting.MockWasmer{MigrateFn: func(codeID wasmvm.Checksum, env wasmvmtypes.Env, migrateMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - return &wasmvmtypes.Response{}, 1, nil - }} - wasmtesting.MakeInstantiable(&mockWasmVM) - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities, WithWasmEngine(&mockWasmVM)) - k, c := keepers.WasmKeeper, keepers.ContractKeeper - example1 := InstantiateHackatomExampleContract(t, ctx, keepers) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - example2 := InstantiateIBCReflectContract(t, ctx, keepers) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - _, err := c.Migrate(ctx, example1.Contract, example1.CreatorAddr, example2.CodeID, []byte("{}")) - require.NoError(t, err) - - // when - var gotAddr []sdk.AccAddress - k.IterateContractsByCode(ctx, example2.CodeID, func(address sdk.AccAddress) bool { - gotAddr = append(gotAddr, address) - return false - }) - - // then - exp := []sdk.AccAddress{example2.Contract, example1.Contract} - assert.Equal(t, exp, gotAddr) -} - -type sudoMsg struct { - // This is a tongue-in-check demo command. This is not the intended purpose of Sudo. - // Here we show that some priviledged Go module can make a call that should never be exposed - // to end users (via Tx/Execute). - // - // The contract developer can choose to expose anything to sudo. This functionality is not a true - // backdoor (it can never be called by end users), but allows the developers of the native blockchain - // code to make special calls. This can also be used as an authentication mechanism, if you want to expose - // some callback that only can be triggered by some system module and not faked by external users. - StealFunds stealFundsMsg `json:"steal_funds"` -} - -type stealFundsMsg struct { - Recipient string `json:"recipient"` - Amount wasmvmtypes.Coins `json:"amount"` -} - -func TestSudo(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.ContractKeeper, keepers.BankKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := DeterministicAccountAddress(t, 1) - keepers.Faucet.Fund(ctx, creator, deposit.Add(deposit...)...) - - contractID, _, err := keeper.Create(ctx, creator, hackatomWasm, nil) - require.NoError(t, err) - - _, bob := keyPubAddr() - _, fred := keyPubAddr() - initMsg := HackatomExampleInitMsg{ - Verifier: fred, - Beneficiary: bob, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, nil, initMsgBz, "demo contract 3", deposit) - require.NoError(t, err) - require.Equal(t, "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr", addr.String()) - - // the community is broke - _, community := keyPubAddr() - comAcct := accKeeper.GetAccount(ctx, community) - require.Nil(t, comAcct) - - // now the community wants to get paid via sudo - msg := sudoMsg{ - // This is a tongue-in-check demo command. This is not the intended purpose of Sudo. - // Here we show that some priviledged Go module can make a call that should never be exposed - // to end users (via Tx/Execute). - StealFunds: stealFundsMsg{ - Recipient: community.String(), - Amount: wasmvmtypes.Coins{wasmvmtypes.NewCoin(76543, "denom")}, - }, - } - sudoMsg, err := json.Marshal(msg) - require.NoError(t, err) - - em := sdk.NewEventManager() - - // when - _, err = keepers.WasmKeeper.Sudo(ctx.WithEventManager(em), addr, sudoMsg) - require.NoError(t, err) - - // ensure community now exists and got paid - comAcct = accKeeper.GetAccount(ctx, community) - require.NotNil(t, comAcct) - balance := bankKeeper.GetBalance(ctx, comAcct.GetAddress(), "denom") - assert.Equal(t, sdk.NewInt64Coin("denom", 76543), balance) - // and events emitted - require.Len(t, em.Events(), 4, prettyEvents(t, em.Events())) - expEvt := sdk.NewEvent("sudo", - sdk.NewAttribute("_contract_address", addr.String())) - assert.Equal(t, expEvt, em.Events()[0]) -} - -func prettyEvents(t *testing.T, events sdk.Events) string { - t.Helper() - type prettyEvent struct { - Type string - Attr []map[string]string - } - - r := make([]prettyEvent, len(events)) - for i, e := range events { - attr := make([]map[string]string, len(e.Attributes)) - for j, a := range e.Attributes { - attr[j] = map[string]string{a.Key: a.Value} - } - r[i] = prettyEvent{Type: e.Type, Attr: attr} - } - return string(mustMarshal(t, r)) -} - -func mustMarshal(t *testing.T, r interface{}) []byte { - t.Helper() - bz, err := json.Marshal(r) - require.NoError(t, err) - return bz -} - -func TestUpdateContractAdmin(t *testing.T) { - parentCtx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.ContractKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) - creator := DeterministicAccountAddress(t, 1) - keepers.Faucet.Fund(parentCtx, creator, deposit.Add(deposit...)...) - fred := keepers.Faucet.NewFundedRandomAccount(parentCtx, topUp...) - - originalContractID, _, err := keeper.Create(parentCtx, creator, hackatomWasm, nil) - require.NoError(t, err) - - _, anyAddr := keyPubAddr() - initMsg := HackatomExampleInitMsg{ - Verifier: fred, - Beneficiary: anyAddr, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - specs := map[string]struct { - instAdmin sdk.AccAddress - newAdmin sdk.AccAddress - overrideContractAddr sdk.AccAddress - caller sdk.AccAddress - expErr *errorsmod.Error - }{ - "all good with admin set": { - instAdmin: fred, - newAdmin: anyAddr, - caller: fred, - }, - "prevent update when admin was not set on instantiate": { - caller: creator, - newAdmin: fred, - expErr: sdkerrors.ErrUnauthorized, - }, - "prevent updates from non admin address": { - instAdmin: creator, - newAdmin: fred, - caller: fred, - expErr: sdkerrors.ErrUnauthorized, - }, - "fail with non existing contract addr": { - instAdmin: creator, - newAdmin: anyAddr, - caller: creator, - overrideContractAddr: anyAddr, - expErr: sdkerrors.ErrInvalidRequest, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - ctx, _ := parentCtx.CacheContext() - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, originalContractID, creator, spec.instAdmin, initMsgBz, "demo contract", nil) - require.NoError(t, err) - if spec.overrideContractAddr != nil { - addr = spec.overrideContractAddr - } - err = keeper.UpdateContractAdmin(ctx, addr, spec.caller, spec.newAdmin) - require.True(t, spec.expErr.Is(err), "expected %v but got %+v", spec.expErr, err) - if spec.expErr != nil { - return - } - cInfo := keepers.WasmKeeper.GetContractInfo(ctx, addr) - assert.Equal(t, spec.newAdmin.String(), cInfo.Admin) - }) - } -} - -func TestClearContractAdmin(t *testing.T) { - parentCtx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.ContractKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) - creator := DeterministicAccountAddress(t, 1) - keepers.Faucet.Fund(parentCtx, creator, deposit.Add(deposit...)...) - fred := keepers.Faucet.NewFundedRandomAccount(parentCtx, topUp...) - - originalContractID, _, err := keeper.Create(parentCtx, creator, hackatomWasm, nil) - require.NoError(t, err) - - _, anyAddr := keyPubAddr() - initMsg := HackatomExampleInitMsg{ - Verifier: fred, - Beneficiary: anyAddr, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - specs := map[string]struct { - instAdmin sdk.AccAddress - overrideContractAddr sdk.AccAddress - caller sdk.AccAddress - expErr *errorsmod.Error - }{ - "all good when called by proper admin": { - instAdmin: fred, - caller: fred, - }, - "prevent update when admin was not set on instantiate": { - caller: creator, - expErr: sdkerrors.ErrUnauthorized, - }, - "prevent updates from non admin address": { - instAdmin: creator, - caller: fred, - expErr: sdkerrors.ErrUnauthorized, - }, - "fail with non existing contract addr": { - instAdmin: creator, - caller: creator, - overrideContractAddr: anyAddr, - expErr: sdkerrors.ErrInvalidRequest, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - ctx, _ := parentCtx.CacheContext() - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, originalContractID, creator, spec.instAdmin, initMsgBz, "demo contract", nil) - require.NoError(t, err) - if spec.overrideContractAddr != nil { - addr = spec.overrideContractAddr - } - err = keeper.ClearContractAdmin(ctx, addr, spec.caller) - require.True(t, spec.expErr.Is(err), "expected %v but got %+v", spec.expErr, err) - if spec.expErr != nil { - return - } - cInfo := keepers.WasmKeeper.GetContractInfo(ctx, addr) - assert.Empty(t, cInfo.Admin) - }) - } -} - -func TestPinCode(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - k := keepers.WasmKeeper - - var capturedChecksums []wasmvm.Checksum - mock := wasmtesting.MockWasmer{PinFn: func(checksum wasmvm.Checksum) error { - capturedChecksums = append(capturedChecksums, checksum) - return nil - }} - wasmtesting.MakeInstantiable(&mock) - myCodeID := StoreRandomContract(t, ctx, keepers, &mock).CodeID - require.Equal(t, uint64(1), myCodeID) - em := sdk.NewEventManager() - - // when - gotErr := k.pinCode(ctx.WithEventManager(em), myCodeID) - - // then - require.NoError(t, gotErr) - assert.NotEmpty(t, capturedChecksums) - assert.True(t, k.IsPinnedCode(ctx, myCodeID)) - - // and events - exp := sdk.Events{sdk.NewEvent("pin_code", sdk.NewAttribute("code_id", "1"))} - assert.Equal(t, exp, em.Events()) -} - -func TestUnpinCode(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - k := keepers.WasmKeeper - - var capturedChecksums []wasmvm.Checksum - mock := wasmtesting.MockWasmer{ - PinFn: func(checksum wasmvm.Checksum) error { - return nil - }, - UnpinFn: func(checksum wasmvm.Checksum) error { - capturedChecksums = append(capturedChecksums, checksum) - return nil - }, - } - wasmtesting.MakeInstantiable(&mock) - myCodeID := StoreRandomContract(t, ctx, keepers, &mock).CodeID - require.Equal(t, uint64(1), myCodeID) - err := k.pinCode(ctx, myCodeID) - require.NoError(t, err) - em := sdk.NewEventManager() - - // when - gotErr := k.unpinCode(ctx.WithEventManager(em), myCodeID) - - // then - require.NoError(t, gotErr) - assert.NotEmpty(t, capturedChecksums) - assert.False(t, k.IsPinnedCode(ctx, myCodeID)) - - // and events - exp := sdk.Events{sdk.NewEvent("unpin_code", sdk.NewAttribute("code_id", "1"))} - assert.Equal(t, exp, em.Events()) -} - -func TestInitializePinnedCodes(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - k := keepers.WasmKeeper - - var capturedChecksums []wasmvm.Checksum - mock := wasmtesting.MockWasmer{PinFn: func(checksum wasmvm.Checksum) error { - capturedChecksums = append(capturedChecksums, checksum) - return nil - }} - wasmtesting.MakeInstantiable(&mock) - - const testItems = 3 - myCodeIDs := make([]uint64, testItems) - for i := 0; i < testItems; i++ { - myCodeIDs[i] = StoreRandomContract(t, ctx, keepers, &mock).CodeID - require.NoError(t, k.pinCode(ctx, myCodeIDs[i])) - } - capturedChecksums = nil - - // when - gotErr := k.InitializePinnedCodes(ctx) - - // then - require.NoError(t, gotErr) - require.Len(t, capturedChecksums, testItems) - for i, c := range myCodeIDs { - var exp wasmvm.Checksum = k.GetCodeInfo(ctx, c).CodeHash - assert.Equal(t, exp, capturedChecksums[i]) - } -} - -func TestPinnedContractLoops(t *testing.T) { - var capturedChecksums []wasmvm.Checksum - mock := wasmtesting.MockWasmer{PinFn: func(checksum wasmvm.Checksum) error { - capturedChecksums = append(capturedChecksums, checksum) - return nil - }} - wasmtesting.MakeInstantiable(&mock) - - // a pinned contract that calls itself via submessages should terminate with an - // error at some point - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities, WithWasmEngine(&mock)) - k := keepers.WasmKeeper - - example := SeedNewContractInstance(t, ctx, keepers, &mock) - require.NoError(t, k.pinCode(ctx, example.CodeID)) - var loops int - anyMsg := []byte(`{}`) - mock.ExecuteFn = func(codeID wasmvm.Checksum, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, executeMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - loops++ - return &wasmvmtypes.Response{ - Messages: []wasmvmtypes.SubMsg{ - { - ID: 1, - ReplyOn: wasmvmtypes.ReplyNever, - Msg: wasmvmtypes.CosmosMsg{ - Wasm: &wasmvmtypes.WasmMsg{ - Execute: &wasmvmtypes.ExecuteMsg{ - ContractAddr: example.Contract.String(), - Msg: anyMsg, - }, - }, - }, - }, - }, - }, 0, nil - } - ctx = ctx.WithGasMeter(sdk.NewGasMeter(20000)) - require.PanicsWithValue(t, sdk.ErrorOutOfGas{Descriptor: "ReadFlat"}, func() { - _, err := k.execute(ctx, example.Contract, RandomAccountAddress(t), anyMsg, nil) - require.NoError(t, err) - }) - assert.True(t, ctx.GasMeter().IsOutOfGas()) - assert.Greater(t, loops, 2) -} - -func TestNewDefaultWasmVMContractResponseHandler(t *testing.T) { - specs := map[string]struct { - srcData []byte - setup func(m *wasmtesting.MockMsgDispatcher) - expErr bool - expData []byte - expEvts sdk.Events - }{ - "submessage overwrites result when set": { - srcData: []byte("otherData"), - setup: func(m *wasmtesting.MockMsgDispatcher) { - m.DispatchSubmessagesFn = func(ctx sdk.Context, contractAddr sdk.AccAddress, ibcPort string, msgs []wasmvmtypes.SubMsg) ([]byte, error) { - return []byte("mySubMsgData"), nil - } - }, - expErr: false, - expData: []byte("mySubMsgData"), - expEvts: sdk.Events{}, - }, - "submessage overwrites result when empty": { - srcData: []byte("otherData"), - setup: func(m *wasmtesting.MockMsgDispatcher) { - m.DispatchSubmessagesFn = func(ctx sdk.Context, contractAddr sdk.AccAddress, ibcPort string, msgs []wasmvmtypes.SubMsg) ([]byte, error) { - return []byte(""), nil - } - }, - expErr: false, - expData: []byte(""), - expEvts: sdk.Events{}, - }, - "submessage do not overwrite result when nil": { - srcData: []byte("otherData"), - setup: func(m *wasmtesting.MockMsgDispatcher) { - m.DispatchSubmessagesFn = func(ctx sdk.Context, contractAddr sdk.AccAddress, ibcPort string, msgs []wasmvmtypes.SubMsg) ([]byte, error) { - return nil, nil - } - }, - expErr: false, - expData: []byte("otherData"), - expEvts: sdk.Events{}, - }, - "submessage error aborts process": { - setup: func(m *wasmtesting.MockMsgDispatcher) { - m.DispatchSubmessagesFn = func(ctx sdk.Context, contractAddr sdk.AccAddress, ibcPort string, msgs []wasmvmtypes.SubMsg) ([]byte, error) { - return nil, errors.New("test - ignore") - } - }, - expErr: true, - }, - "message emit non message events": { - setup: func(m *wasmtesting.MockMsgDispatcher) { - m.DispatchSubmessagesFn = func(ctx sdk.Context, contractAddr sdk.AccAddress, ibcPort string, msgs []wasmvmtypes.SubMsg) ([]byte, error) { - ctx.EventManager().EmitEvent(sdk.NewEvent("myEvent")) - return nil, nil - } - }, - expEvts: sdk.Events{sdk.NewEvent("myEvent")}, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - var msgs []wasmvmtypes.SubMsg - var mock wasmtesting.MockMsgDispatcher - spec.setup(&mock) - d := NewDefaultWasmVMContractResponseHandler(&mock) - em := sdk.NewEventManager() - - // when - gotData, gotErr := d.Handle(sdk.Context{}.WithEventManager(em), RandomAccountAddress(t), "ibc-port", msgs, spec.srcData) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - assert.Equal(t, spec.expData, gotData) - assert.Equal(t, spec.expEvts, em.Events()) - }) - } -} - -func TestReply(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - k := keepers.WasmKeeper - var mock wasmtesting.MockWasmer - wasmtesting.MakeInstantiable(&mock) - example := SeedNewContractInstance(t, ctx, keepers, &mock) - - specs := map[string]struct { - replyFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, reply wasmvmtypes.Reply, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) - expData []byte - expErr bool - expEvt sdk.Events - }{ - "all good": { - replyFn: func(codeID wasmvm.Checksum, env wasmvmtypes.Env, reply wasmvmtypes.Reply, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - return &wasmvmtypes.Response{Data: []byte("foo")}, 1, nil - }, - expData: []byte("foo"), - expEvt: sdk.Events{sdk.NewEvent("reply", sdk.NewAttribute("_contract_address", example.Contract.String()))}, - }, - "with query": { - replyFn: func(codeID wasmvm.Checksum, env wasmvmtypes.Env, reply wasmvmtypes.Reply, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - bzRsp, err := querier.Query(wasmvmtypes.QueryRequest{ - Bank: &wasmvmtypes.BankQuery{ - Balance: &wasmvmtypes.BalanceQuery{Address: env.Contract.Address, Denom: "stake"}, - }, - }, 10_000*DefaultGasMultiplier) - require.NoError(t, err) - var gotBankRsp wasmvmtypes.BalanceResponse - require.NoError(t, json.Unmarshal(bzRsp, &gotBankRsp)) - assert.Equal(t, wasmvmtypes.BalanceResponse{Amount: wasmvmtypes.NewCoin(0, "stake")}, gotBankRsp) - return &wasmvmtypes.Response{Data: []byte("foo")}, 1, nil - }, - expData: []byte("foo"), - expEvt: sdk.Events{sdk.NewEvent("reply", sdk.NewAttribute("_contract_address", example.Contract.String()))}, - }, - "with query error handled": { - replyFn: func(codeID wasmvm.Checksum, env wasmvmtypes.Env, reply wasmvmtypes.Reply, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - bzRsp, err := querier.Query(wasmvmtypes.QueryRequest{}, 0) - require.Error(t, err) - assert.Nil(t, bzRsp) - return &wasmvmtypes.Response{Data: []byte("foo")}, 1, nil - }, - expData: []byte("foo"), - expEvt: sdk.Events{sdk.NewEvent("reply", sdk.NewAttribute("_contract_address", example.Contract.String()))}, - }, - "error": { - replyFn: func(codeID wasmvm.Checksum, env wasmvmtypes.Env, reply wasmvmtypes.Reply, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - return nil, 1, errors.New("testing") - }, - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - mock.ReplyFn = spec.replyFn - em := sdk.NewEventManager() - gotData, gotErr := k.reply(ctx.WithEventManager(em), example.Contract, wasmvmtypes.Reply{}) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - assert.Equal(t, spec.expData, gotData) - assert.Equal(t, spec.expEvt, em.Events()) - }) - } -} - -func TestQueryIsolation(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - k := keepers.WasmKeeper - var mock wasmtesting.MockWasmer - wasmtesting.MakeInstantiable(&mock) - example := SeedNewContractInstance(t, ctx, keepers, &mock) - WithQueryHandlerDecorator(func(other WasmVMQueryHandler) WasmVMQueryHandler { - return WasmVMQueryHandlerFn(func(ctx sdk.Context, caller sdk.AccAddress, request wasmvmtypes.QueryRequest) ([]byte, error) { - if request.Custom == nil { - return other.HandleQuery(ctx, caller, request) - } - // here we write to DB which should not be persisted - ctx.KVStore(k.storeKey).Set([]byte(`set_in_query`), []byte(`this_is_allowed`)) - return nil, nil - }) - }).apply(k) - - // when - mock.ReplyFn = func(codeID wasmvm.Checksum, env wasmvmtypes.Env, reply wasmvmtypes.Reply, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - _, err := querier.Query(wasmvmtypes.QueryRequest{ - Custom: []byte(`{}`), - }, 10000*DefaultGasMultiplier) - require.NoError(t, err) - return &wasmvmtypes.Response{}, 0, nil - } - em := sdk.NewEventManager() - _, gotErr := k.reply(ctx.WithEventManager(em), example.Contract, wasmvmtypes.Reply{}) - require.NoError(t, gotErr) - assert.Nil(t, ctx.KVStore(k.storeKey).Get([]byte(`set_in_query`))) -} - -func TestSetAccessConfig(t *testing.T) { - parentCtx, keepers := CreateTestInput(t, false, AvailableCapabilities) - k := keepers.WasmKeeper - creatorAddr := RandomAccountAddress(t) - nonCreatorAddr := RandomAccountAddress(t) - const codeID = 1 - - specs := map[string]struct { - authz AuthorizationPolicy - chainPermission types.AccessType - newConfig types.AccessConfig - caller sdk.AccAddress - expErr bool - expEvts map[string]string - }{ - "user with new permissions == chain permissions": { - authz: DefaultAuthorizationPolicy{}, - chainPermission: types.AccessTypeEverybody, - newConfig: types.AllowEverybody, - caller: creatorAddr, - expEvts: map[string]string{ - "code_id": "1", - "code_permission": "Everybody", - }, - }, - "user with new permissions < chain permissions": { - authz: DefaultAuthorizationPolicy{}, - chainPermission: types.AccessTypeEverybody, - newConfig: types.AllowNobody, - caller: creatorAddr, - expEvts: map[string]string{ - "code_id": "1", - "code_permission": "Nobody", - }, - }, - "user with new permissions > chain permissions": { - authz: DefaultAuthorizationPolicy{}, - chainPermission: types.AccessTypeNobody, - newConfig: types.AllowEverybody, - caller: creatorAddr, - expErr: true, - }, - "different actor": { - authz: DefaultAuthorizationPolicy{}, - chainPermission: types.AccessTypeEverybody, - newConfig: types.AllowEverybody, - caller: nonCreatorAddr, - expErr: true, - }, - "gov with new permissions == chain permissions": { - authz: GovAuthorizationPolicy{}, - chainPermission: types.AccessTypeEverybody, - newConfig: types.AllowEverybody, - caller: creatorAddr, - expEvts: map[string]string{ - "code_id": "1", - "code_permission": "Everybody", - }, - }, - "gov with new permissions < chain permissions": { - authz: GovAuthorizationPolicy{}, - chainPermission: types.AccessTypeEverybody, - newConfig: types.AllowNobody, - caller: creatorAddr, - expEvts: map[string]string{ - "code_id": "1", - "code_permission": "Nobody", - }, - }, - "gov with new permissions > chain permissions": { - authz: GovAuthorizationPolicy{}, - chainPermission: types.AccessTypeNobody, - newConfig: types.AccessTypeOnlyAddress.With(creatorAddr), - caller: creatorAddr, - expEvts: map[string]string{ - "code_id": "1", - "code_permission": "OnlyAddress", - "authorized_addresses": creatorAddr.String(), - }, - }, - "gov with new permissions > chain permissions - multiple addresses": { - authz: GovAuthorizationPolicy{}, - chainPermission: types.AccessTypeNobody, - newConfig: types.AccessTypeAnyOfAddresses.With(creatorAddr, nonCreatorAddr), - caller: creatorAddr, - expEvts: map[string]string{ - "code_id": "1", - "code_permission": "AnyOfAddresses", - "authorized_addresses": creatorAddr.String() + "," + nonCreatorAddr.String(), - }, - }, - "gov without actor": { - authz: GovAuthorizationPolicy{}, - chainPermission: types.AccessTypeEverybody, - newConfig: types.AllowEverybody, - expEvts: map[string]string{ - "code_id": "1", - "code_permission": "Everybody", - }, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - ctx, _ := parentCtx.CacheContext() - em := sdk.NewEventManager() - ctx = ctx.WithEventManager(em) - - newParams := types.DefaultParams() - newParams.InstantiateDefaultPermission = spec.chainPermission - err := k.SetParams(ctx, newParams) - require.NoError(t, err) - - k.storeCodeInfo(ctx, codeID, types.NewCodeInfo(nil, creatorAddr, types.AllowNobody)) - // when - gotErr := k.setAccessConfig(ctx, codeID, spec.caller, spec.newConfig, spec.authz) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - // and event emitted - require.Len(t, em.Events(), 1) - assert.Equal(t, "update_code_access_config", em.Events()[0].Type) - assert.Equal(t, spec.expEvts, attrsToStringMap(em.Events()[0].Attributes)) - }) - } -} - -func TestAppendToContractHistory(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - var contractAddr sdk.AccAddress = rand.Bytes(types.ContractAddrLen) - var orderedEntries []types.ContractCodeHistoryEntry - - f := fuzz.New().Funcs(ModelFuzzers...) - for i := 0; i < 10; i++ { - var entry types.ContractCodeHistoryEntry - f.Fuzz(&entry) - keepers.WasmKeeper.appendToContractHistory(ctx, contractAddr, entry) - orderedEntries = append(orderedEntries, entry) - } - // when - gotHistory := keepers.WasmKeeper.GetContractHistory(ctx, contractAddr) - assert.Equal(t, orderedEntries, gotHistory) -} - -func TestCoinBurnerPruneBalances(t *testing.T) { - parentCtx, keepers := CreateTestInput(t, false, AvailableCapabilities) - amts := sdk.NewCoins(sdk.NewInt64Coin("denom", 100)) - senderAddr := keepers.Faucet.NewFundedRandomAccount(parentCtx, amts...) - - // create vesting account - var vestingAddr sdk.AccAddress = rand.Bytes(types.ContractAddrLen) - msgCreateVestingAccount := vestingtypes.NewMsgCreateVestingAccount(senderAddr, vestingAddr, amts, time.Now().Add(time.Minute).Unix(), false) - _, err := vesting.NewMsgServerImpl(keepers.AccountKeeper, keepers.BankKeeper).CreateVestingAccount(sdk.WrapSDKContext(parentCtx), msgCreateVestingAccount) - require.NoError(t, err) - myVestingAccount := keepers.AccountKeeper.GetAccount(parentCtx, vestingAddr) - require.NotNil(t, myVestingAccount) - - specs := map[string]struct { - setupAcc func(t *testing.T, ctx sdk.Context) authtypes.AccountI - expBalances sdk.Coins - expHandled bool - expErr *errorsmod.Error - }{ - "vesting account - all removed": { - setupAcc: func(t *testing.T, ctx sdk.Context) authtypes.AccountI { return myVestingAccount }, - - expBalances: sdk.NewCoins(), - expHandled: true, - }, - "vesting account with other tokens - only original denoms removed": { - setupAcc: func(t *testing.T, ctx sdk.Context) authtypes.AccountI { - keepers.Faucet.Fund(ctx, vestingAddr, sdk.NewCoin("other", sdk.NewInt(2))) - return myVestingAccount - }, - expBalances: sdk.NewCoins(sdk.NewCoin("other", sdk.NewInt(2))), - expHandled: true, - }, - "non vesting account - not handled": { - setupAcc: func(t *testing.T, ctx sdk.Context) authtypes.AccountI { - return &authtypes.BaseAccount{Address: myVestingAccount.GetAddress().String()} - }, - expBalances: sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(100))), - expHandled: false, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - ctx, _ := parentCtx.CacheContext() - existingAccount := spec.setupAcc(t, ctx) - // overwrite account in store as in keeper before calling prune - keepers.AccountKeeper.SetAccount(ctx, keepers.AccountKeeper.NewAccountWithAddress(ctx, vestingAddr)) - - // when - noGasCtx := ctx.WithGasMeter(sdk.NewGasMeter(0)) // should not use callers gas - gotHandled, gotErr := NewVestingCoinBurner(keepers.BankKeeper).CleanupExistingAccount(noGasCtx, existingAccount) - // then - if spec.expErr != nil { - require.ErrorIs(t, gotErr, spec.expErr) - return - } - require.NoError(t, gotErr) - assert.Equal(t, spec.expBalances, keepers.BankKeeper.GetAllBalances(ctx, vestingAddr)) - assert.Equal(t, spec.expHandled, gotHandled) - // and no out of gas panic - }) - } -} - -func TestIteratorAllContract(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - example1 := InstantiateHackatomExampleContract(t, ctx, keepers) - example2 := InstantiateHackatomExampleContract(t, ctx, keepers) - example3 := InstantiateHackatomExampleContract(t, ctx, keepers) - example4 := InstantiateHackatomExampleContract(t, ctx, keepers) - - var allContract []string - keepers.WasmKeeper.IterateContractInfo(ctx, func(addr sdk.AccAddress, _ types.ContractInfo) bool { - allContract = append(allContract, addr.String()) - return false - }) - - // IterateContractInfo not ordering - expContracts := []string{example4.Contract.String(), example2.Contract.String(), example1.Contract.String(), example3.Contract.String()} - require.Equal(t, allContract, expContracts) -} - -func TestIteratorContractByCreator(t *testing.T) { - // setup test - parentCtx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.ContractKeeper - - depositFund := sdk.NewCoins(sdk.NewInt64Coin("denom", 1000000)) - topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) - creator := DeterministicAccountAddress(t, 1) - keepers.Faucet.Fund(parentCtx, creator, depositFund.Add(depositFund...)...) - mockAddress1 := keepers.Faucet.NewFundedRandomAccount(parentCtx, topUp...) - mockAddress2 := keepers.Faucet.NewFundedRandomAccount(parentCtx, topUp...) - mockAddress3 := keepers.Faucet.NewFundedRandomAccount(parentCtx, topUp...) - - contract1ID, _, err := keeper.Create(parentCtx, creator, hackatomWasm, nil) - require.NoError(t, err) - - contract2ID, _, err := keeper.Create(parentCtx, creator, hackatomWasm, nil) - require.NoError(t, err) - - initMsgBz := HackatomExampleInitMsg{ - Verifier: mockAddress1, - Beneficiary: mockAddress1, - }.GetBytes(t) - - depositContract := sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(1_000))) - - gotAddr1, _, _ := keepers.ContractKeeper.Instantiate(parentCtx, contract1ID, mockAddress1, nil, initMsgBz, "label", depositContract) - ctx := parentCtx.WithBlockHeight(parentCtx.BlockHeight() + 1) - gotAddr2, _, _ := keepers.ContractKeeper.Instantiate(ctx, contract1ID, mockAddress2, nil, initMsgBz, "label", depositContract) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - gotAddr3, _, _ := keepers.ContractKeeper.Instantiate(ctx, contract1ID, gotAddr1, nil, initMsgBz, "label", depositContract) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - gotAddr4, _, _ := keepers.ContractKeeper.Instantiate(ctx, contract2ID, mockAddress2, nil, initMsgBz, "label", depositContract) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - gotAddr5, _, _ := keepers.ContractKeeper.Instantiate(ctx, contract2ID, mockAddress2, nil, initMsgBz, "label", depositContract) - - specs := map[string]struct { - creatorAddr sdk.AccAddress - contractsAddr []string - }{ - "single contract": { - creatorAddr: mockAddress1, - contractsAddr: []string{gotAddr1.String()}, - }, - "multiple contracts": { - creatorAddr: mockAddress2, - contractsAddr: []string{gotAddr2.String(), gotAddr4.String(), gotAddr5.String()}, - }, - "contractAdress": { - creatorAddr: gotAddr1, - contractsAddr: []string{gotAddr3.String()}, - }, - "no contracts- unknown": { - creatorAddr: mockAddress3, - contractsAddr: nil, - }, - } - - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - var allContract []string - keepers.WasmKeeper.IterateContractsByCreator(parentCtx, spec.creatorAddr, func(addr sdk.AccAddress) bool { - allContract = append(allContract, addr.String()) - return false - }) - require.Equal(t, - allContract, - spec.contractsAddr, - ) - }) - } -} - -func TestSetContractAdmin(t *testing.T) { - parentCtx, keepers := CreateTestInput(t, false, AvailableCapabilities) - k := keepers.WasmKeeper - myAddr := RandomAccountAddress(t) - example := InstantiateReflectExampleContract(t, parentCtx, keepers) - specs := map[string]struct { - newAdmin sdk.AccAddress - caller sdk.AccAddress - policy AuthorizationPolicy - expAdmin string - expErr bool - }{ - "update admin": { - newAdmin: myAddr, - caller: example.CreatorAddr, - policy: DefaultAuthorizationPolicy{}, - expAdmin: myAddr.String(), - }, - "update admin - unauthorized": { - newAdmin: myAddr, - caller: RandomAccountAddress(t), - policy: DefaultAuthorizationPolicy{}, - expErr: true, - }, - "clear admin - default policy": { - caller: example.CreatorAddr, - policy: DefaultAuthorizationPolicy{}, - expAdmin: "", - }, - "clear admin - unauthorized": { - expAdmin: "", - policy: DefaultAuthorizationPolicy{}, - caller: RandomAccountAddress(t), - expErr: true, - }, - "clear admin - gov policy": { - newAdmin: nil, - policy: GovAuthorizationPolicy{}, - caller: example.CreatorAddr, - expAdmin: "", - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - ctx, _ := parentCtx.CacheContext() - em := sdk.NewEventManager() - ctx = ctx.WithEventManager(em) - gotErr := k.setContractAdmin(ctx, example.Contract, spec.caller, spec.newAdmin, spec.policy) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - assert.Equal(t, spec.expAdmin, k.GetContractInfo(ctx, example.Contract).Admin) - // and event emitted - require.Len(t, em.Events(), 1) - assert.Equal(t, "update_contract_admin", em.Events()[0].Type) - exp := map[string]string{ - "_contract_address": example.Contract.String(), - "new_admin_address": spec.expAdmin, - } - assert.Equal(t, exp, attrsToStringMap(em.Events()[0].Attributes)) - }) - } -} - -func attrsToStringMap(attrs []abci.EventAttribute) map[string]string { - r := make(map[string]string, len(attrs)) - for _, v := range attrs { - r[v.Key] = v.Value - } - return r -} diff --git a/x/wasm/keeper/metrics.go b/x/wasm/keeper/metrics.go deleted file mode 100644 index 4c4b959..0000000 --- a/x/wasm/keeper/metrics.go +++ /dev/null @@ -1,72 +0,0 @@ -package keeper - -import ( - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/prometheus/client_golang/prometheus" -) - -const ( - labelPinned = "pinned" - labelMemory = "memory" - labelFs = "fs" -) - -// metricSource source of wasmvm metrics -type metricSource interface { - GetMetrics() (*wasmvmtypes.Metrics, error) -} - -var _ prometheus.Collector = (*WasmVMMetricsCollector)(nil) - -// WasmVMMetricsCollector custom metrics collector to be used with Prometheus -type WasmVMMetricsCollector struct { - source metricSource - CacheHitsDescr *prometheus.Desc - CacheMissesDescr *prometheus.Desc - CacheElementsDescr *prometheus.Desc - CacheSizeDescr *prometheus.Desc -} - -// NewWasmVMMetricsCollector constructor -func NewWasmVMMetricsCollector(s metricSource) *WasmVMMetricsCollector { - return &WasmVMMetricsCollector{ - source: s, - CacheHitsDescr: prometheus.NewDesc("wasmvm_cache_hits_total", "Total number of cache hits", []string{"type"}, nil), - CacheMissesDescr: prometheus.NewDesc("wasmvm_cache_misses_total", "Total number of cache misses", nil, nil), - CacheElementsDescr: prometheus.NewDesc("wasmvm_cache_elements_total", "Total number of elements in the cache", []string{"type"}, nil), - CacheSizeDescr: prometheus.NewDesc("wasmvm_cache_size_bytes", "Total number of elements in the cache", []string{"type"}, nil), - } -} - -// Register registers all metrics -func (p *WasmVMMetricsCollector) Register(r prometheus.Registerer) { - r.MustRegister(p) -} - -// Describe sends the super-set of all possible descriptors of metrics -func (p *WasmVMMetricsCollector) Describe(descs chan<- *prometheus.Desc) { - descs <- p.CacheHitsDescr - descs <- p.CacheMissesDescr - descs <- p.CacheElementsDescr - descs <- p.CacheSizeDescr -} - -// Collect is called by the Prometheus registry when collecting metrics. -func (p *WasmVMMetricsCollector) Collect(c chan<- prometheus.Metric) { - m, err := p.source.GetMetrics() - if err != nil { - return - } - c <- prometheus.MustNewConstMetric(p.CacheHitsDescr, prometheus.CounterValue, float64(m.HitsPinnedMemoryCache), labelPinned) - c <- prometheus.MustNewConstMetric(p.CacheHitsDescr, prometheus.CounterValue, float64(m.HitsMemoryCache), labelMemory) - c <- prometheus.MustNewConstMetric(p.CacheHitsDescr, prometheus.CounterValue, float64(m.HitsFsCache), labelFs) - c <- prometheus.MustNewConstMetric(p.CacheMissesDescr, prometheus.CounterValue, float64(m.Misses)) - c <- prometheus.MustNewConstMetric(p.CacheElementsDescr, prometheus.GaugeValue, float64(m.ElementsPinnedMemoryCache), labelPinned) - c <- prometheus.MustNewConstMetric(p.CacheElementsDescr, prometheus.GaugeValue, float64(m.ElementsMemoryCache), labelMemory) - c <- prometheus.MustNewConstMetric(p.CacheSizeDescr, prometheus.GaugeValue, float64(m.SizeMemoryCache), labelMemory) - c <- prometheus.MustNewConstMetric(p.CacheSizeDescr, prometheus.GaugeValue, float64(m.SizePinnedMemoryCache), labelPinned) - // Node about fs metrics: - // The number of elements and the size of elements in the file system cache cannot easily be obtained. - // We had to either scan the whole directory of potentially thousands of files or track the values when files are added or removed. - // Such a tracking would need to be on disk such that the values are not cleared when the node is restarted. -} diff --git a/x/wasm/keeper/migrations.go b/x/wasm/keeper/migrations.go deleted file mode 100644 index 7ce1211..0000000 --- a/x/wasm/keeper/migrations.go +++ /dev/null @@ -1,32 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - v1 "github.com/terpnetwork/terp-core/x/wasm/migrations/v1" - v2 "github.com/terpnetwork/terp-core/x/wasm/migrations/v2" - - "github.com/terpnetwork/terp-core/x/wasm/exported" -) - -// Migrator is a struct for handling in-place store migrations. -type Migrator struct { - keeper Keeper - legacySubspace exported.Subspace -} - -// NewMigrator returns a new Migrator. -func NewMigrator(keeper Keeper, legacySubspace exported.Subspace) Migrator { - return Migrator{keeper: keeper, legacySubspace: legacySubspace} -} - -// Migrate1to2 migrates from version 1 to 2. -func (m Migrator) Migrate1to2(ctx sdk.Context) error { - return v1.NewMigrator(m.keeper, m.keeper.addToContractCreatorSecondaryIndex).Migrate1to2(ctx) -} - -// Migrate2to3 migrates the x/wasm module state from the consensus -// version 2 to version 3. -func (m Migrator) Migrate2to3(ctx sdk.Context) error { - return v2.MigrateStore(ctx, m.keeper.storeKey, m.legacySubspace, m.keeper.cdc) -} diff --git a/x/wasm/keeper/migrations_integration_test.go b/x/wasm/keeper/migrations_integration_test.go deleted file mode 100644 index 0e7a033..0000000 --- a/x/wasm/keeper/migrations_integration_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package keeper_test - -import ( - "testing" - - "github.com/terpnetwork/terp-core/x/wasm/types" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/app" - "github.com/terpnetwork/terp-core/x/wasm" -) - -func TestModuleMigrations(t *testing.T) { - wasmApp := app.Setup(t) - upgradeHandler := func(ctx sdk.Context, plan upgradetypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) { //nolint:unparam - return wasmApp.ModuleManager.RunMigrations(ctx, wasmApp.Configurator(), fromVM) - } - - specs := map[string]struct { - setup func(ctx sdk.Context) - startVersion uint64 - exp types.Params - }{ - "with legacy params migrated": { - startVersion: 1, - setup: func(ctx sdk.Context) { - params := types.Params{ - CodeUploadAccess: types.AllowNobody, - InstantiateDefaultPermission: types.AccessTypeNobody, - } - sp, _ := wasmApp.ParamsKeeper.GetSubspace(types.ModuleName) - sp.SetParamSet(ctx, ¶ms) - }, - exp: types.Params{ - CodeUploadAccess: types.AllowNobody, - InstantiateDefaultPermission: types.AccessTypeNobody, - }, - }, - "fresh from genesis": { - startVersion: wasmApp.ModuleManager.GetVersionMap()[types.ModuleName], // latest - setup: func(ctx sdk.Context) {}, - exp: types.DefaultParams(), - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - ctx, _ := wasmApp.BaseApp.NewContext(false, tmproto.Header{}).CacheContext() - spec.setup(ctx) - - fromVM := wasmApp.UpgradeKeeper.GetModuleVersionMap(ctx) - fromVM[wasm.ModuleName] = spec.startVersion - _, err := upgradeHandler(ctx, upgradetypes.Plan{Name: "testing"}, fromVM) - require.NoError(t, err) - - // when - gotVM, err := wasmApp.ModuleManager.RunMigrations(ctx, wasmApp.Configurator(), fromVM) - - // then - require.NoError(t, err) - var expModuleVersion uint64 = 3 - assert.Equal(t, expModuleVersion, gotVM[wasm.ModuleName]) - gotParams := wasmApp.WasmKeeper.GetParams(ctx) - assert.Equal(t, spec.exp, gotParams) - }) - } -} diff --git a/x/wasm/keeper/msg_dispatcher.go b/x/wasm/keeper/msg_dispatcher.go deleted file mode 100644 index 392dbd2..0000000 --- a/x/wasm/keeper/msg_dispatcher.go +++ /dev/null @@ -1,223 +0,0 @@ -package keeper - -import ( - "fmt" - "sort" - "strings" - - errorsmod "cosmossdk.io/errors" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - abci "github.com/cometbft/cometbft/abci/types" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// Messenger is an extension point for custom wasmd message handling -type Messenger interface { - // DispatchMsg encodes the wasmVM message and dispatches it. - DispatchMsg(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) -} - -// replyer is a subset of keeper that can handle replies to submessages -type replyer interface { - reply(ctx sdk.Context, contractAddress sdk.AccAddress, reply wasmvmtypes.Reply) ([]byte, error) -} - -// MessageDispatcher coordinates message sending and submessage reply/ state commits -type MessageDispatcher struct { - messenger Messenger - keeper replyer -} - -// NewMessageDispatcher constructor -func NewMessageDispatcher(messenger Messenger, keeper replyer) *MessageDispatcher { - return &MessageDispatcher{messenger: messenger, keeper: keeper} -} - -// DispatchMessages sends all messages. -func (d MessageDispatcher) DispatchMessages(ctx sdk.Context, contractAddr sdk.AccAddress, ibcPort string, msgs []wasmvmtypes.CosmosMsg) error { - for _, msg := range msgs { - events, _, err := d.messenger.DispatchMsg(ctx, contractAddr, ibcPort, msg) - if err != nil { - return err - } - // redispatch all events, (type sdk.EventTypeMessage will be filtered out in the handler) - ctx.EventManager().EmitEvents(events) - } - return nil -} - -// dispatchMsgWithGasLimit sends a message with gas limit applied -func (d MessageDispatcher) dispatchMsgWithGasLimit(ctx sdk.Context, contractAddr sdk.AccAddress, ibcPort string, msg wasmvmtypes.CosmosMsg, gasLimit uint64) (events []sdk.Event, data [][]byte, err error) { - limitedMeter := sdk.NewGasMeter(gasLimit) - subCtx := ctx.WithGasMeter(limitedMeter) - - // catch out of gas panic and just charge the entire gas limit - defer func() { - if r := recover(); r != nil { - // if it's not an OutOfGas error, raise it again - if _, ok := r.(sdk.ErrorOutOfGas); !ok { - // log it to get the original stack trace somewhere (as panic(r) keeps message but stacktrace to here - moduleLogger(ctx).Info("SubMsg rethrowing panic: %#v", r) - panic(r) - } - ctx.GasMeter().ConsumeGas(gasLimit, "Sub-Message OutOfGas panic") - err = errorsmod.Wrap(sdkerrors.ErrOutOfGas, "SubMsg hit gas limit") - } - }() - events, data, err = d.messenger.DispatchMsg(subCtx, contractAddr, ibcPort, msg) - - // make sure we charge the parent what was spent - spent := subCtx.GasMeter().GasConsumed() - ctx.GasMeter().ConsumeGas(spent, "From limited Sub-Message") - - return events, data, err -} - -// DispatchSubmessages builds a sandbox to execute these messages and returns the execution result to the contract -// that dispatched them, both on success as well as failure -func (d MessageDispatcher) DispatchSubmessages(ctx sdk.Context, contractAddr sdk.AccAddress, ibcPort string, msgs []wasmvmtypes.SubMsg) ([]byte, error) { - var rsp []byte - for _, msg := range msgs { - switch msg.ReplyOn { - case wasmvmtypes.ReplySuccess, wasmvmtypes.ReplyError, wasmvmtypes.ReplyAlways, wasmvmtypes.ReplyNever: - default: - return nil, errorsmod.Wrap(types.ErrInvalid, "replyOn value") - } - // first, we build a sub-context which we can use inside the submessages - subCtx, commit := ctx.CacheContext() - em := sdk.NewEventManager() - subCtx = subCtx.WithEventManager(em) - - // check how much gas left locally, optionally wrap the gas meter - gasRemaining := ctx.GasMeter().Limit() - ctx.GasMeter().GasConsumed() - limitGas := msg.GasLimit != nil && (*msg.GasLimit < gasRemaining) - - var err error - var events []sdk.Event - var data [][]byte - if limitGas { - events, data, err = d.dispatchMsgWithGasLimit(subCtx, contractAddr, ibcPort, msg.Msg, *msg.GasLimit) - } else { - events, data, err = d.messenger.DispatchMsg(subCtx, contractAddr, ibcPort, msg.Msg) - } - - // if it succeeds, commit state changes from submessage, and pass on events to Event Manager - var filteredEvents []sdk.Event - if err == nil { - commit() - filteredEvents = filterEvents(append(em.Events(), events...)) - ctx.EventManager().EmitEvents(filteredEvents) - if msg.Msg.Wasm == nil { - filteredEvents = []sdk.Event{} - } else { - for _, e := range filteredEvents { - attributes := e.Attributes - sort.SliceStable(attributes, func(i, j int) bool { - return strings.Compare(attributes[i].Key, attributes[j].Key) < 0 - }) - } - } - } // on failure, revert state from sandbox, and ignore events (just skip doing the above) - - // we only callback if requested. Short-circuit here the cases we don't want to - if (msg.ReplyOn == wasmvmtypes.ReplySuccess || msg.ReplyOn == wasmvmtypes.ReplyNever) && err != nil { - return nil, err - } - if msg.ReplyOn == wasmvmtypes.ReplyNever || (msg.ReplyOn == wasmvmtypes.ReplyError && err == nil) { - continue - } - - // otherwise, we create a SubMsgResult and pass it into the calling contract - var result wasmvmtypes.SubMsgResult - if err == nil { - // just take the first one for now if there are multiple sub-sdk messages - // and safely return nothing if no data - var responseData []byte - if len(data) > 0 { - responseData = data[0] - } - result = wasmvmtypes.SubMsgResult{ - Ok: &wasmvmtypes.SubMsgResponse{ - Events: sdkEventsToWasmVMEvents(filteredEvents), - Data: responseData, - }, - } - } else { - // Issue #759 - we don't return error string for worries of non-determinism - moduleLogger(ctx).Info("Redacting submessage error", "cause", err) - result = wasmvmtypes.SubMsgResult{ - Err: redactError(err).Error(), - } - } - - // now handle the reply, we use the parent context, and abort on error - reply := wasmvmtypes.Reply{ - ID: msg.ID, - Result: result, - } - - // we can ignore any result returned as there is nothing to do with the data - // and the events are already in the ctx.EventManager() - rspData, err := d.keeper.reply(ctx, contractAddr, reply) - switch { - case err != nil: - return nil, errorsmod.Wrap(err, "reply") - case rspData != nil: - rsp = rspData - } - } - return rsp, nil -} - -// Issue #759 - we don't return error string for worries of non-determinism -func redactError(err error) error { - // Do not redact system errors - // SystemErrors must be created in x/wasm and we can ensure determinism - if wasmvmtypes.ToSystemError(err) != nil { - return err - } - - // FIXME: do we want to hardcode some constant string mappings here as well? - // Or better document them? (SDK error string may change on a patch release to fix wording) - // sdk/11 is out of gas - // sdk/5 is insufficient funds (on bank send) - // (we can theoretically redact less in the future, but this is a first step to safety) - codespace, code, _ := errorsmod.ABCIInfo(err, false) - return fmt.Errorf("codespace: %s, code: %d", codespace, code) -} - -func filterEvents(events []sdk.Event) []sdk.Event { - // pre-allocate space for efficiency - res := make([]sdk.Event, 0, len(events)) - for _, ev := range events { - if ev.Type != "message" { - res = append(res, ev) - } - } - return res -} - -func sdkEventsToWasmVMEvents(events []sdk.Event) []wasmvmtypes.Event { - res := make([]wasmvmtypes.Event, len(events)) - for i, ev := range events { - res[i] = wasmvmtypes.Event{ - Type: ev.Type, - Attributes: sdkAttributesToWasmVMAttributes(ev.Attributes), - } - } - return res -} - -func sdkAttributesToWasmVMAttributes(attrs []abci.EventAttribute) []wasmvmtypes.EventAttribute { - res := make([]wasmvmtypes.EventAttribute, len(attrs)) - for i, attr := range attrs { - res[i] = wasmvmtypes.EventAttribute{ - Key: attr.Key, - Value: attr.Value, - } - } - return res -} diff --git a/x/wasm/keeper/msg_dispatcher_test.go b/x/wasm/keeper/msg_dispatcher_test.go deleted file mode 100644 index 436ad6d..0000000 --- a/x/wasm/keeper/msg_dispatcher_test.go +++ /dev/null @@ -1,430 +0,0 @@ -package keeper - -import ( - "errors" - "fmt" - "testing" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cometbft/cometbft/libs/log" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/keeper/wasmtesting" -) - -func TestDispatchSubmessages(t *testing.T) { - noReplyCalled := &mockReplyer{} - var anyGasLimit uint64 = 1 - specs := map[string]struct { - msgs []wasmvmtypes.SubMsg - replyer *mockReplyer - msgHandler *wasmtesting.MockMessageHandler - expErr bool - expData []byte - expCommits []bool - expEvents sdk.Events - }{ - "no reply on error without error": { - msgs: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyError}}, - replyer: noReplyCalled, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - return nil, [][]byte{[]byte("myData")}, nil - }, - }, - expCommits: []bool{true}, - }, - "no reply on success without success": { - msgs: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplySuccess}}, - replyer: noReplyCalled, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - return nil, nil, errors.New("test, ignore") - }, - }, - expCommits: []bool{false}, - expErr: true, - }, - "reply on success - received": { - msgs: []wasmvmtypes.SubMsg{{ - ReplyOn: wasmvmtypes.ReplySuccess, - }}, - replyer: &mockReplyer{ - replyFn: func(ctx sdk.Context, contractAddress sdk.AccAddress, reply wasmvmtypes.Reply) ([]byte, error) { - return []byte("myReplyData"), nil - }, - }, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - return nil, [][]byte{[]byte("myData")}, nil - }, - }, - expData: []byte("myReplyData"), - expCommits: []bool{true}, - }, - "reply on error - handled": { - msgs: []wasmvmtypes.SubMsg{{ - ReplyOn: wasmvmtypes.ReplyError, - }}, - replyer: &mockReplyer{ - replyFn: func(ctx sdk.Context, contractAddress sdk.AccAddress, reply wasmvmtypes.Reply) ([]byte, error) { - return []byte("myReplyData"), nil - }, - }, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - return nil, nil, errors.New("my error") - }, - }, - expData: []byte("myReplyData"), - expCommits: []bool{false}, - }, - "with reply events": { - msgs: []wasmvmtypes.SubMsg{{ - ReplyOn: wasmvmtypes.ReplySuccess, - }}, - replyer: &mockReplyer{ - replyFn: func(ctx sdk.Context, contractAddress sdk.AccAddress, reply wasmvmtypes.Reply) ([]byte, error) { - ctx.EventManager().EmitEvent(sdk.NewEvent("wasm-reply")) - return []byte("myReplyData"), nil - }, - }, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - myEvents := []sdk.Event{{Type: "myEvent", Attributes: []abci.EventAttribute{{Key: "foo", Value: "bar"}}}} - return myEvents, [][]byte{[]byte("myData")}, nil - }, - }, - expData: []byte("myReplyData"), - expCommits: []bool{true}, - expEvents: []sdk.Event{ - { - Type: "myEvent", - Attributes: []abci.EventAttribute{{Key: "foo", Value: "bar"}}, - }, - sdk.NewEvent("wasm-reply"), - }, - }, - "with context events - released on commit": { - msgs: []wasmvmtypes.SubMsg{{ - ReplyOn: wasmvmtypes.ReplyNever, - }}, - replyer: &mockReplyer{}, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - myEvents := []sdk.Event{{Type: "myEvent", Attributes: []abci.EventAttribute{{Key: "foo", Value: "bar"}}}} - ctx.EventManager().EmitEvents(myEvents) - return nil, nil, nil - }, - }, - expCommits: []bool{true}, - expEvents: []sdk.Event{{ - Type: "myEvent", - Attributes: []abci.EventAttribute{{Key: "foo", Value: "bar"}}, - }}, - }, - "with context events - discarded on failure": { - msgs: []wasmvmtypes.SubMsg{{ - ReplyOn: wasmvmtypes.ReplyNever, - }}, - replyer: &mockReplyer{}, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - myEvents := []sdk.Event{{Type: "myEvent", Attributes: []abci.EventAttribute{{Key: "foo", Value: "bar"}}}} - ctx.EventManager().EmitEvents(myEvents) - return nil, nil, errors.New("testing") - }, - }, - expCommits: []bool{false}, - expErr: true, - }, - "reply returns error": { - msgs: []wasmvmtypes.SubMsg{{ - ReplyOn: wasmvmtypes.ReplySuccess, - }}, - replyer: &mockReplyer{ - replyFn: func(ctx sdk.Context, contractAddress sdk.AccAddress, reply wasmvmtypes.Reply) ([]byte, error) { - return nil, errors.New("reply failed") - }, - }, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - return nil, nil, nil - }, - }, - expCommits: []bool{false}, - expErr: true, - }, - "with gas limit - out of gas": { - msgs: []wasmvmtypes.SubMsg{{ - GasLimit: &anyGasLimit, - ReplyOn: wasmvmtypes.ReplyError, - }}, - replyer: &mockReplyer{ - replyFn: func(ctx sdk.Context, contractAddress sdk.AccAddress, reply wasmvmtypes.Reply) ([]byte, error) { - return []byte("myReplyData"), nil - }, - }, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - ctx.GasMeter().ConsumeGas(sdk.Gas(101), "testing") - return nil, [][]byte{[]byte("someData")}, nil - }, - }, - expData: []byte("myReplyData"), - expCommits: []bool{false}, - }, - "with gas limit - within limit no error": { - msgs: []wasmvmtypes.SubMsg{{ - GasLimit: &anyGasLimit, - ReplyOn: wasmvmtypes.ReplyError, - }}, - replyer: &mockReplyer{}, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - ctx.GasMeter().ConsumeGas(sdk.Gas(1), "testing") - return nil, [][]byte{[]byte("someData")}, nil - }, - }, - expCommits: []bool{true}, - }, - "never reply - with nil response": { - msgs: []wasmvmtypes.SubMsg{{ID: 1, ReplyOn: wasmvmtypes.ReplyNever}, {ID: 2, ReplyOn: wasmvmtypes.ReplyNever}}, - replyer: &mockReplyer{}, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - return nil, [][]byte{nil}, nil - }, - }, - expCommits: []bool{true, true}, - }, - "never reply - with any non nil response": { - msgs: []wasmvmtypes.SubMsg{{ID: 1, ReplyOn: wasmvmtypes.ReplyNever}, {ID: 2, ReplyOn: wasmvmtypes.ReplyNever}}, - replyer: &mockReplyer{}, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - return nil, [][]byte{{}}, nil - }, - }, - expCommits: []bool{true, true}, - }, - "never reply - with error": { - msgs: []wasmvmtypes.SubMsg{{ID: 1, ReplyOn: wasmvmtypes.ReplyNever}, {ID: 2, ReplyOn: wasmvmtypes.ReplyNever}}, - replyer: &mockReplyer{}, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - return nil, [][]byte{{}}, errors.New("testing") - }, - }, - expCommits: []bool{false, false}, - expErr: true, - }, - "multiple msg - last reply returned": { - msgs: []wasmvmtypes.SubMsg{{ID: 1, ReplyOn: wasmvmtypes.ReplyError}, {ID: 2, ReplyOn: wasmvmtypes.ReplyError}}, - replyer: &mockReplyer{ - replyFn: func(ctx sdk.Context, contractAddress sdk.AccAddress, reply wasmvmtypes.Reply) ([]byte, error) { - return []byte(fmt.Sprintf("myReplyData:%d", reply.ID)), nil - }, - }, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - return nil, nil, errors.New("my error") - }, - }, - expData: []byte("myReplyData:2"), - expCommits: []bool{false, false}, - }, - "multiple msg - last non nil reply returned": { - msgs: []wasmvmtypes.SubMsg{{ID: 1, ReplyOn: wasmvmtypes.ReplyError}, {ID: 2, ReplyOn: wasmvmtypes.ReplyError}}, - replyer: &mockReplyer{ - replyFn: func(ctx sdk.Context, contractAddress sdk.AccAddress, reply wasmvmtypes.Reply) ([]byte, error) { - if reply.ID == 2 { - return nil, nil - } - return []byte("myReplyData:1"), nil - }, - }, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - return nil, nil, errors.New("my error") - }, - }, - expData: []byte("myReplyData:1"), - expCommits: []bool{false, false}, - }, - "multiple msg - empty reply can overwrite result": { - msgs: []wasmvmtypes.SubMsg{{ID: 1, ReplyOn: wasmvmtypes.ReplyError}, {ID: 2, ReplyOn: wasmvmtypes.ReplyError}}, - replyer: &mockReplyer{ - replyFn: func(ctx sdk.Context, contractAddress sdk.AccAddress, reply wasmvmtypes.Reply) ([]byte, error) { - if reply.ID == 2 { - return []byte{}, nil - } - return []byte("myReplyData:1"), nil - }, - }, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - return nil, nil, errors.New("my error") - }, - }, - expData: []byte{}, - expCommits: []bool{false, false}, - }, - "message event filtered without reply": { - msgs: []wasmvmtypes.SubMsg{{ - ReplyOn: wasmvmtypes.ReplyNever, - }}, - replyer: &mockReplyer{ - replyFn: func(ctx sdk.Context, contractAddress sdk.AccAddress, reply wasmvmtypes.Reply) ([]byte, error) { - return nil, errors.New("should never be called") - }, - }, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - myEvents := []sdk.Event{ - sdk.NewEvent("message"), - sdk.NewEvent("execute", sdk.NewAttribute("foo", "bar")), - } - return myEvents, [][]byte{[]byte("myData")}, nil - }, - }, - expData: nil, - expCommits: []bool{true}, - expEvents: []sdk.Event{sdk.NewEvent("execute", sdk.NewAttribute("foo", "bar"))}, - }, - "wasm reply gets proper events": { - // put fake wasmmsg in here to show where it comes from - msgs: []wasmvmtypes.SubMsg{{ID: 1, ReplyOn: wasmvmtypes.ReplyAlways, Msg: wasmvmtypes.CosmosMsg{Wasm: &wasmvmtypes.WasmMsg{}}}}, - replyer: &mockReplyer{ - replyFn: func(ctx sdk.Context, contractAddress sdk.AccAddress, reply wasmvmtypes.Reply) ([]byte, error) { - if reply.Result.Err != "" { - return nil, errors.New(reply.Result.Err) - } - res := reply.Result.Ok - - // ensure the input events are what we expect - // I didn't use require.Equal() to act more like a contract... but maybe that would be better - if len(res.Events) != 2 { - return nil, fmt.Errorf("event count: %#v", res.Events) - } - if res.Events[0].Type != "execute" { - return nil, fmt.Errorf("event0: %#v", res.Events[0]) - } - if res.Events[1].Type != "wasm" { - return nil, fmt.Errorf("event1: %#v", res.Events[1]) - } - - // let's add a custom event here and see if it makes it out - ctx.EventManager().EmitEvent(sdk.NewEvent("wasm-reply")) - - // update data from what we got in - return res.Data, nil - }, - }, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - events = []sdk.Event{ - sdk.NewEvent("message", sdk.NewAttribute("_contract_address", contractAddr.String())), - // we don't know what the contarctAddr will be so we can't use it in the final tests - sdk.NewEvent("execute", sdk.NewAttribute("_contract_address", "placeholder-random-addr")), - sdk.NewEvent("wasm", sdk.NewAttribute("random", "data")), - } - return events, [][]byte{[]byte("subData")}, nil - }, - }, - expData: []byte("subData"), - expCommits: []bool{true}, - expEvents: []sdk.Event{ - sdk.NewEvent("execute", sdk.NewAttribute("_contract_address", "placeholder-random-addr")), - sdk.NewEvent("wasm", sdk.NewAttribute("random", "data")), - sdk.NewEvent("wasm-reply"), - }, - }, - "non-wasm reply events get filtered": { - // show events from a stargate message gets filtered out - msgs: []wasmvmtypes.SubMsg{{ID: 1, ReplyOn: wasmvmtypes.ReplyAlways, Msg: wasmvmtypes.CosmosMsg{Stargate: &wasmvmtypes.StargateMsg{}}}}, - replyer: &mockReplyer{ - replyFn: func(ctx sdk.Context, contractAddress sdk.AccAddress, reply wasmvmtypes.Reply) ([]byte, error) { - if reply.Result.Err != "" { - return nil, errors.New(reply.Result.Err) - } - res := reply.Result.Ok - - // ensure the input events are what we expect - // I didn't use require.Equal() to act more like a contract... but maybe that would be better - if len(res.Events) != 0 { - return nil, errors.New("events not filtered out") - } - - // let's add a custom event here and see if it makes it out - ctx.EventManager().EmitEvent(sdk.NewEvent("stargate-reply")) - - // update data from what we got in - return res.Data, nil - }, - }, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - events = []sdk.Event{ - // this is filtered out - sdk.NewEvent("message", sdk.NewAttribute("stargate", "something-something")), - // we still emit this to the client, but not the contract - sdk.NewEvent("non-determinstic"), - } - return events, [][]byte{[]byte("subData")}, nil - }, - }, - expData: []byte("subData"), - expCommits: []bool{true}, - expEvents: []sdk.Event{ - sdk.NewEvent("non-determinstic"), - // the event from reply is also exposed - sdk.NewEvent("stargate-reply"), - }, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - var mockStore wasmtesting.MockCommitMultiStore - em := sdk.NewEventManager() - ctx := sdk.Context{}.WithMultiStore(&mockStore). - WithGasMeter(sdk.NewGasMeter(100)). - WithEventManager(em).WithLogger(log.TestingLogger()) - d := NewMessageDispatcher(spec.msgHandler, spec.replyer) - - // run the test - gotData, gotErr := d.DispatchSubmessages(ctx, RandomAccountAddress(t), "any_port", spec.msgs) - if spec.expErr { - require.Error(t, gotErr) - assert.Empty(t, em.Events()) - return - } - - // if we don't expect an error, we should get no error - require.NoError(t, gotErr) - assert.Equal(t, spec.expData, gotData) - - // ensure the commits are what we expect - assert.Equal(t, spec.expCommits, mockStore.Committed) - if len(spec.expEvents) == 0 { - assert.Empty(t, em.Events()) - } else { - assert.Equal(t, spec.expEvents, em.Events()) - } - }) - } -} - -type mockReplyer struct { - replyFn func(ctx sdk.Context, contractAddress sdk.AccAddress, reply wasmvmtypes.Reply) ([]byte, error) -} - -func (m mockReplyer) reply(ctx sdk.Context, contractAddress sdk.AccAddress, reply wasmvmtypes.Reply) ([]byte, error) { - if m.replyFn == nil { - panic("not expected to be called") - } - return m.replyFn(ctx, contractAddress, reply) -} diff --git a/x/wasm/keeper/msg_server.go b/x/wasm/keeper/msg_server.go deleted file mode 100644 index 66d1cd6..0000000 --- a/x/wasm/keeper/msg_server.go +++ /dev/null @@ -1,365 +0,0 @@ -package keeper - -import ( - "context" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -var _ types.MsgServer = msgServer{} - -// grpc message server implementation -type msgServer struct { - keeper *Keeper -} - -// NewMsgServerImpl default constructor -func NewMsgServerImpl(k *Keeper) types.MsgServer { - return &msgServer{keeper: k} -} - -// StoreCode stores a new wasm code on chain -func (m msgServer) StoreCode(goCtx context.Context, msg *types.MsgStoreCode) (*types.MsgStoreCodeResponse, error) { - if err := msg.ValidateBasic(); err != nil { - return nil, err - } - ctx := sdk.UnwrapSDKContext(goCtx) - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, errorsmod.Wrap(err, "sender") - } - - policy := m.selectAuthorizationPolicy(msg.Sender) - - codeID, checksum, err := m.keeper.create(ctx, senderAddr, msg.WASMByteCode, msg.InstantiatePermission, policy) - if err != nil { - return nil, err - } - - return &types.MsgStoreCodeResponse{ - CodeID: codeID, - Checksum: checksum, - }, nil -} - -// InstantiateContract instantiate a new contract with classic sequence based address generation -func (m msgServer) InstantiateContract(goCtx context.Context, msg *types.MsgInstantiateContract) (*types.MsgInstantiateContractResponse, error) { - if err := msg.ValidateBasic(); err != nil { - return nil, err - } - ctx := sdk.UnwrapSDKContext(goCtx) - - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, errorsmod.Wrap(err, "sender") - } - var adminAddr sdk.AccAddress - if msg.Admin != "" { - if adminAddr, err = sdk.AccAddressFromBech32(msg.Admin); err != nil { - return nil, errorsmod.Wrap(err, "admin") - } - } - - policy := m.selectAuthorizationPolicy(msg.Sender) - - contractAddr, data, err := m.keeper.instantiate(ctx, msg.CodeID, senderAddr, adminAddr, msg.Msg, msg.Label, msg.Funds, m.keeper.ClassicAddressGenerator(), policy) - if err != nil { - return nil, err - } - - return &types.MsgInstantiateContractResponse{ - Address: contractAddr.String(), - Data: data, - }, nil -} - -// InstantiateContract2 instantiate a new contract with predicatable address generated -func (m msgServer) InstantiateContract2(goCtx context.Context, msg *types.MsgInstantiateContract2) (*types.MsgInstantiateContract2Response, error) { - if err := msg.ValidateBasic(); err != nil { - return nil, err - } - ctx := sdk.UnwrapSDKContext(goCtx) - - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, errorsmod.Wrap(err, "sender") - } - var adminAddr sdk.AccAddress - if msg.Admin != "" { - if adminAddr, err = sdk.AccAddressFromBech32(msg.Admin); err != nil { - return nil, errorsmod.Wrap(err, "admin") - } - } - - policy := m.selectAuthorizationPolicy(msg.Sender) - - addrGenerator := PredicableAddressGenerator(senderAddr, msg.Salt, msg.Msg, msg.FixMsg) - - contractAddr, data, err := m.keeper.instantiate(ctx, msg.CodeID, senderAddr, adminAddr, msg.Msg, msg.Label, msg.Funds, addrGenerator, policy) - if err != nil { - return nil, err - } - - return &types.MsgInstantiateContract2Response{ - Address: contractAddr.String(), - Data: data, - }, nil -} - -func (m msgServer) ExecuteContract(goCtx context.Context, msg *types.MsgExecuteContract) (*types.MsgExecuteContractResponse, error) { - if err := msg.ValidateBasic(); err != nil { - return nil, err - } - - ctx := sdk.UnwrapSDKContext(goCtx) - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, errorsmod.Wrap(err, "sender") - } - contractAddr, err := sdk.AccAddressFromBech32(msg.Contract) - if err != nil { - return nil, errorsmod.Wrap(err, "contract") - } - - data, err := m.keeper.execute(ctx, contractAddr, senderAddr, msg.Msg, msg.Funds) - if err != nil { - return nil, err - } - - return &types.MsgExecuteContractResponse{ - Data: data, - }, nil -} - -func (m msgServer) MigrateContract(goCtx context.Context, msg *types.MsgMigrateContract) (*types.MsgMigrateContractResponse, error) { - if err := msg.ValidateBasic(); err != nil { - return nil, err - } - - ctx := sdk.UnwrapSDKContext(goCtx) - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, errorsmod.Wrap(err, "sender") - } - contractAddr, err := sdk.AccAddressFromBech32(msg.Contract) - if err != nil { - return nil, errorsmod.Wrap(err, "contract") - } - - policy := m.selectAuthorizationPolicy(msg.Sender) - - data, err := m.keeper.migrate(ctx, contractAddr, senderAddr, msg.CodeID, msg.Msg, policy) - if err != nil { - return nil, err - } - - return &types.MsgMigrateContractResponse{ - Data: data, - }, nil -} - -func (m msgServer) UpdateAdmin(goCtx context.Context, msg *types.MsgUpdateAdmin) (*types.MsgUpdateAdminResponse, error) { - if err := msg.ValidateBasic(); err != nil { - return nil, err - } - - ctx := sdk.UnwrapSDKContext(goCtx) - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, errorsmod.Wrap(err, "sender") - } - contractAddr, err := sdk.AccAddressFromBech32(msg.Contract) - if err != nil { - return nil, errorsmod.Wrap(err, "contract") - } - newAdminAddr, err := sdk.AccAddressFromBech32(msg.NewAdmin) - if err != nil { - return nil, errorsmod.Wrap(err, "new admin") - } - - policy := m.selectAuthorizationPolicy(msg.Sender) - - if err := m.keeper.setContractAdmin(ctx, contractAddr, senderAddr, newAdminAddr, policy); err != nil { - return nil, err - } - - return &types.MsgUpdateAdminResponse{}, nil -} - -func (m msgServer) ClearAdmin(goCtx context.Context, msg *types.MsgClearAdmin) (*types.MsgClearAdminResponse, error) { - if err := msg.ValidateBasic(); err != nil { - return nil, err - } - - ctx := sdk.UnwrapSDKContext(goCtx) - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, errorsmod.Wrap(err, "sender") - } - contractAddr, err := sdk.AccAddressFromBech32(msg.Contract) - if err != nil { - return nil, errorsmod.Wrap(err, "contract") - } - - policy := m.selectAuthorizationPolicy(msg.Sender) - - if err := m.keeper.setContractAdmin(ctx, contractAddr, senderAddr, nil, policy); err != nil { - return nil, err - } - - return &types.MsgClearAdminResponse{}, nil -} - -func (m msgServer) UpdateInstantiateConfig(goCtx context.Context, msg *types.MsgUpdateInstantiateConfig) (*types.MsgUpdateInstantiateConfigResponse, error) { - if err := msg.ValidateBasic(); err != nil { - return nil, err - } - - ctx := sdk.UnwrapSDKContext(goCtx) - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, errorsmod.Wrap(err, "sender") - } - policy := m.selectAuthorizationPolicy(msg.Sender) - - if err := m.keeper.setAccessConfig(ctx, msg.CodeID, senderAddr, *msg.NewInstantiatePermission, policy); err != nil { - return nil, err - } - - return &types.MsgUpdateInstantiateConfigResponse{}, nil -} - -// UpdateParams updates the module parameters -func (m msgServer) UpdateParams(goCtx context.Context, req *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) { - if err := req.ValidateBasic(); err != nil { - return nil, err - } - authority := m.keeper.GetAuthority() - if authority != req.Authority { - return nil, errorsmod.Wrapf(types.ErrInvalid, "invalid authority; expected %s, got %s", authority, req.Authority) - } - - ctx := sdk.UnwrapSDKContext(goCtx) - if err := m.keeper.SetParams(ctx, req.Params); err != nil { - return nil, err - } - - return &types.MsgUpdateParamsResponse{}, nil -} - -// PinCodes pins a set of code ids in the wasmvm cache. -func (m msgServer) PinCodes(goCtx context.Context, req *types.MsgPinCodes) (*types.MsgPinCodesResponse, error) { - if err := req.ValidateBasic(); err != nil { - return nil, err - } - - authority := m.keeper.GetAuthority() - if authority != req.Authority { - return nil, errorsmod.Wrapf(types.ErrInvalid, "invalid authority; expected %s, got %s", authority, req.Authority) - } - - ctx := sdk.UnwrapSDKContext(goCtx) - for _, codeID := range req.CodeIDs { - if err := m.keeper.pinCode(ctx, codeID); err != nil { - return nil, err - } - } - - return &types.MsgPinCodesResponse{}, nil -} - -// UnpinCodes unpins a set of code ids in the wasmvm cache. -func (m msgServer) UnpinCodes(goCtx context.Context, req *types.MsgUnpinCodes) (*types.MsgUnpinCodesResponse, error) { - if err := req.ValidateBasic(); err != nil { - return nil, err - } - - authority := m.keeper.GetAuthority() - if authority != req.Authority { - return nil, errorsmod.Wrapf(types.ErrInvalid, "invalid authority; expected %s, got %s", authority, req.Authority) - } - - ctx := sdk.UnwrapSDKContext(goCtx) - for _, codeID := range req.CodeIDs { - if err := m.keeper.unpinCode(ctx, codeID); err != nil { - return nil, err - } - } - - return &types.MsgUnpinCodesResponse{}, nil -} - -// SudoContract calls sudo on a contract. -func (m msgServer) SudoContract(goCtx context.Context, req *types.MsgSudoContract) (*types.MsgSudoContractResponse, error) { - if err := req.ValidateBasic(); err != nil { - return nil, err - } - authority := m.keeper.GetAuthority() - if authority != req.Authority { - return nil, errorsmod.Wrapf(types.ErrInvalid, "invalid authority; expected %s, got %s", authority, req.Authority) - } - - contractAddr, err := sdk.AccAddressFromBech32(req.Contract) - if err != nil { - return nil, errorsmod.Wrap(err, "contract") - } - - ctx := sdk.UnwrapSDKContext(goCtx) - data, err := m.keeper.Sudo(ctx, contractAddr, req.Msg) - if err != nil { - return nil, err - } - - return &types.MsgSudoContractResponse{Data: data}, nil -} - -// StoreAndInstantiateContract stores and instantiates the contract. -func (m msgServer) StoreAndInstantiateContract(goCtx context.Context, req *types.MsgStoreAndInstantiateContract) (*types.MsgStoreAndInstantiateContractResponse, error) { - if err := req.ValidateBasic(); err != nil { - return nil, err - } - - authorityAddr, err := sdk.AccAddressFromBech32(req.Authority) - if err != nil { - return nil, errorsmod.Wrap(err, "authority") - } - - if err = req.ValidateBasic(); err != nil { - return nil, err - } - - var adminAddr sdk.AccAddress - if req.Admin != "" { - if adminAddr, err = sdk.AccAddressFromBech32(req.Admin); err != nil { - return nil, errorsmod.Wrap(err, "admin") - } - } - - ctx := sdk.UnwrapSDKContext(goCtx) - policy := m.selectAuthorizationPolicy(req.Authority) - - codeID, _, err := m.keeper.create(ctx, authorityAddr, req.WASMByteCode, req.InstantiatePermission, policy) - if err != nil { - return nil, err - } - - contractAddr, data, err := m.keeper.instantiate(ctx, codeID, authorityAddr, adminAddr, req.Msg, req.Label, req.Funds, m.keeper.ClassicAddressGenerator(), policy) - if err != nil { - return nil, err - } - - return &types.MsgStoreAndInstantiateContractResponse{ - Address: contractAddr.String(), - Data: data, - }, nil -} - -func (m msgServer) selectAuthorizationPolicy(actor string) AuthorizationPolicy { - if actor == m.keeper.GetAuthority() { - return GovAuthorizationPolicy{} - } - return DefaultAuthorizationPolicy{} -} diff --git a/x/wasm/keeper/msg_server_integration_test.go b/x/wasm/keeper/msg_server_integration_test.go deleted file mode 100644 index 11003c0..0000000 --- a/x/wasm/keeper/msg_server_integration_test.go +++ /dev/null @@ -1,855 +0,0 @@ -package keeper_test - -import ( - "crypto/sha256" - _ "embed" - "encoding/json" - "testing" - "time" - - "github.com/cosmos/cosmos-sdk/testutil/testdata" - sdk "github.com/cosmos/cosmos-sdk/types" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/app" - "github.com/terpnetwork/terp-core/x/wasm/keeper" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -//go:embed testdata/reflect.wasm -var wasmContract []byte - -//go:embed testdata/hackatom.wasm -var hackatomContract []byte - -func TestStoreCode(t *testing.T) { - wasmApp := app.Setup(t) - ctx := wasmApp.BaseApp.NewContext(false, tmproto.Header{}) - _, _, sender := testdata.KeyTestPubAddr() - msg := types.MsgStoreCodeFixture(func(m *types.MsgStoreCode) { - m.WASMByteCode = wasmContract - m.Sender = sender.String() - }) - - // when - rsp, err := wasmApp.MsgServiceRouter().Handler(msg)(ctx, msg) - - // then - require.NoError(t, err) - var result types.MsgStoreCodeResponse - require.NoError(t, wasmApp.AppCodec().Unmarshal(rsp.Data, &result)) - assert.Equal(t, uint64(1), result.CodeID) - expHash := sha256.Sum256(wasmContract) - assert.Equal(t, expHash[:], result.Checksum) - // and - info := wasmApp.WasmKeeper.GetCodeInfo(ctx, 1) - assert.NotNil(t, info) - assert.Equal(t, expHash[:], info.CodeHash) - assert.Equal(t, sender.String(), info.Creator) - assert.Equal(t, types.DefaultParams().InstantiateDefaultPermission.With(sender), info.InstantiateConfig) -} - -func TestUpdateParams(t *testing.T) { - wasmApp := app.Setup(t) - ctx := wasmApp.BaseApp.NewContext(false, tmproto.Header{}) - - var ( - myAddress sdk.AccAddress = make([]byte, types.ContractAddrLen) - oneAddressAccessConfig = types.AccessTypeOnlyAddress.With(myAddress) - govAuthority = wasmApp.WasmKeeper.GetAuthority() - ) - - specs := map[string]struct { - src types.MsgUpdateParams - expUploadConfig types.AccessConfig - expInstantiateType types.AccessType - }{ - "update upload permission param": { - src: types.MsgUpdateParams{ - Authority: govAuthority, - Params: types.Params{ - CodeUploadAccess: types.AllowNobody, - InstantiateDefaultPermission: types.AccessTypeEverybody, - }, - }, - expUploadConfig: types.AllowNobody, - expInstantiateType: types.AccessTypeEverybody, - }, - "update upload permission with same as current value": { - src: types.MsgUpdateParams{ - Authority: govAuthority, - Params: types.Params{ - CodeUploadAccess: types.AllowEverybody, - InstantiateDefaultPermission: types.AccessTypeEverybody, - }, - }, - expUploadConfig: types.AllowEverybody, - expInstantiateType: types.AccessTypeEverybody, - }, - "update upload permission param with address": { - src: types.MsgUpdateParams{ - Authority: govAuthority, - Params: types.Params{ - CodeUploadAccess: oneAddressAccessConfig, - InstantiateDefaultPermission: types.AccessTypeEverybody, - }, - }, - expUploadConfig: oneAddressAccessConfig, - expInstantiateType: types.AccessTypeEverybody, - }, - "update instantiate param": { - src: types.MsgUpdateParams{ - Authority: govAuthority, - Params: types.Params{ - CodeUploadAccess: types.AllowEverybody, - InstantiateDefaultPermission: types.AccessTypeNobody, - }, - }, - expUploadConfig: types.AllowEverybody, - expInstantiateType: types.AccessTypeNobody, - }, - "update instantiate param as default": { - src: types.MsgUpdateParams{ - Authority: govAuthority, - Params: types.Params{ - CodeUploadAccess: types.AllowEverybody, - InstantiateDefaultPermission: types.AccessTypeEverybody, - }, - }, - expUploadConfig: types.AllowEverybody, - expInstantiateType: types.AccessTypeEverybody, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - err := wasmApp.WasmKeeper.SetParams(ctx, types.DefaultParams()) - require.NoError(t, err) - - // when - rsp, err := wasmApp.MsgServiceRouter().Handler(&spec.src)(ctx, &spec.src) - require.NoError(t, err) - var result types.MsgUpdateParamsResponse - require.NoError(t, wasmApp.AppCodec().Unmarshal(rsp.Data, &result)) - - // then - assert.True(t, spec.expUploadConfig.Equals(wasmApp.WasmKeeper.GetParams(ctx).CodeUploadAccess), - "got %#v not %#v", wasmApp.WasmKeeper.GetParams(ctx).CodeUploadAccess, spec.expUploadConfig) - assert.Equal(t, spec.expInstantiateType, wasmApp.WasmKeeper.GetParams(ctx).InstantiateDefaultPermission) - }) - } -} - -func TestPinCodes(t *testing.T) { - wasmApp := app.Setup(t) - ctx := wasmApp.BaseApp.NewContext(false, tmproto.Header{}) - - var ( - myAddress sdk.AccAddress = make([]byte, types.ContractAddrLen) - authority = wasmApp.WasmKeeper.GetAuthority() - ) - - specs := map[string]struct { - addr string - expErr bool - }{ - "authority can pin codes": { - addr: authority, - expErr: false, - }, - "other address cannot pin codes": { - addr: myAddress.String(), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - // setup - _, _, sender := testdata.KeyTestPubAddr() - msg := types.MsgStoreCodeFixture(func(m *types.MsgStoreCode) { - m.WASMByteCode = wasmContract - m.Sender = sender.String() - }) - - // store code - rsp, err := wasmApp.MsgServiceRouter().Handler(msg)(ctx, msg) - require.NoError(t, err) - var result types.MsgStoreCodeResponse - require.NoError(t, wasmApp.AppCodec().Unmarshal(rsp.Data, &result)) - require.False(t, wasmApp.WasmKeeper.IsPinnedCode(ctx, result.CodeID)) - - // when - msgPinCodes := &types.MsgPinCodes{ - Authority: spec.addr, - CodeIDs: []uint64{result.CodeID}, - } - _, err = wasmApp.MsgServiceRouter().Handler(msgPinCodes)(ctx, msgPinCodes) - - // then - if spec.expErr { - require.Error(t, err) - assert.False(t, wasmApp.WasmKeeper.IsPinnedCode(ctx, result.CodeID)) - } else { - require.NoError(t, err) - assert.True(t, wasmApp.WasmKeeper.IsPinnedCode(ctx, result.CodeID)) - } - }) - } -} - -func TestUnpinCodes(t *testing.T) { - wasmApp := app.Setup(t) - ctx := wasmApp.BaseApp.NewContext(false, tmproto.Header{}) - - var ( - myAddress sdk.AccAddress = make([]byte, types.ContractAddrLen) - authority = wasmApp.WasmKeeper.GetAuthority() - ) - - specs := map[string]struct { - addr string - expErr bool - }{ - "authority can unpin codes": { - addr: authority, - expErr: false, - }, - "other address cannot unpin codes": { - addr: myAddress.String(), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - // setup - _, _, sender := testdata.KeyTestPubAddr() - msg := types.MsgStoreCodeFixture(func(m *types.MsgStoreCode) { - m.WASMByteCode = wasmContract - m.Sender = sender.String() - }) - - // store code - rsp, err := wasmApp.MsgServiceRouter().Handler(msg)(ctx, msg) - require.NoError(t, err) - var result types.MsgStoreCodeResponse - require.NoError(t, wasmApp.AppCodec().Unmarshal(rsp.Data, &result)) - - // pin code - msgPin := &types.MsgPinCodes{ - Authority: authority, - CodeIDs: []uint64{result.CodeID}, - } - _, err = wasmApp.MsgServiceRouter().Handler(msgPin)(ctx, msgPin) - require.NoError(t, err) - assert.True(t, wasmApp.WasmKeeper.IsPinnedCode(ctx, result.CodeID)) - - // when - msgUnpinCodes := &types.MsgUnpinCodes{ - Authority: spec.addr, - CodeIDs: []uint64{result.CodeID}, - } - _, err = wasmApp.MsgServiceRouter().Handler(msgUnpinCodes)(ctx, msgUnpinCodes) - - // then - if spec.expErr { - require.Error(t, err) - assert.True(t, wasmApp.WasmKeeper.IsPinnedCode(ctx, result.CodeID)) - } else { - require.NoError(t, err) - assert.False(t, wasmApp.WasmKeeper.IsPinnedCode(ctx, result.CodeID)) - } - }) - } -} - -func TestSudoContract(t *testing.T) { - wasmApp := app.Setup(t) - ctx := wasmApp.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) - - var ( - myAddress sdk.AccAddress = make([]byte, types.ContractAddrLen) - authority = wasmApp.WasmKeeper.GetAuthority() - ) - - type StealMsg struct { - Recipient string `json:"recipient"` - Amount []sdk.Coin `json:"amount"` - } - - stealMsg := struct { - Steal StealMsg `json:"steal_funds"` - }{Steal: StealMsg{ - Recipient: myAddress.String(), - Amount: []sdk.Coin{}, - }} - - stealMsgBz, err := json.Marshal(stealMsg) - require.NoError(t, err) - - specs := map[string]struct { - addr string - expErr bool - }{ - "authority can call sudo on a contract": { - addr: authority, - expErr: false, - }, - "other address cannot call sudo on a contract": { - addr: myAddress.String(), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - // setup - _, _, sender := testdata.KeyTestPubAddr() - msg := types.MsgStoreCodeFixture(func(m *types.MsgStoreCode) { - m.WASMByteCode = hackatomContract - m.Sender = sender.String() - }) - - // store code - rsp, err := wasmApp.MsgServiceRouter().Handler(msg)(ctx, msg) - require.NoError(t, err) - var storeCodeResponse types.MsgStoreCodeResponse - require.NoError(t, wasmApp.AppCodec().Unmarshal(rsp.Data, &storeCodeResponse)) - - // instantiate contract - initMsg := keeper.HackatomExampleInitMsg{ - Verifier: sender, - Beneficiary: myAddress, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - - msgInstantiate := &types.MsgInstantiateContract{ - Sender: sender.String(), - Admin: sender.String(), - CodeID: storeCodeResponse.CodeID, - Label: "test", - Msg: initMsgBz, - Funds: sdk.Coins{}, - } - rsp, err = wasmApp.MsgServiceRouter().Handler(msgInstantiate)(ctx, msgInstantiate) - require.NoError(t, err) - var instantiateResponse types.MsgInstantiateContractResponse - require.NoError(t, wasmApp.AppCodec().Unmarshal(rsp.Data, &instantiateResponse)) - - // when - msgSudoContract := &types.MsgSudoContract{ - Authority: spec.addr, - Msg: stealMsgBz, - Contract: instantiateResponse.Address, - } - _, err = wasmApp.MsgServiceRouter().Handler(msgSudoContract)(ctx, msgSudoContract) - - // then - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestStoreAndInstantiateContract(t *testing.T) { - wasmApp := app.Setup(t) - ctx := wasmApp.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) - - var ( - myAddress sdk.AccAddress = make([]byte, types.ContractAddrLen) - authority = wasmApp.WasmKeeper.GetAuthority() - ) - - specs := map[string]struct { - addr string - permission *types.AccessConfig - expErr bool - }{ - "authority can store and instantiate a contract when permission is nobody": { - addr: authority, - permission: &types.AllowNobody, - expErr: false, - }, - "other address cannot store and instantiate a contract when permission is nobody": { - addr: myAddress.String(), - permission: &types.AllowNobody, - expErr: true, - }, - "authority can store and instantiate a contract when permission is everybody": { - addr: authority, - permission: &types.AllowEverybody, - expErr: false, - }, - "other address can store and instantiate a contract when permission is everybody": { - addr: myAddress.String(), - permission: &types.AllowEverybody, - expErr: false, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - // when - msg := &types.MsgStoreAndInstantiateContract{ - Authority: spec.addr, - WASMByteCode: wasmContract, - InstantiatePermission: spec.permission, - Admin: myAddress.String(), - UnpinCode: false, - Label: "test", - Msg: []byte(`{}`), - Funds: sdk.Coins{}, - } - _, err := wasmApp.MsgServiceRouter().Handler(msg)(ctx, msg) - - // then - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestUpdateAdmin(t *testing.T) { - wasmApp := app.Setup(t) - ctx := wasmApp.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) - - var ( - myAddress sdk.AccAddress = make([]byte, types.ContractAddrLen) - authority = wasmApp.WasmKeeper.GetAuthority() - _, _, otherAddr = testdata.KeyTestPubAddr() - ) - - specs := map[string]struct { - addr string - expErr bool - }{ - "authority can update admin": { - addr: authority, - expErr: false, - }, - "admin can update admin": { - addr: myAddress.String(), - expErr: false, - }, - "other address cannot update admin": { - addr: otherAddr.String(), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - _, _, newAdmin := testdata.KeyTestPubAddr() - - // setup - msg := &types.MsgStoreAndInstantiateContract{ - Authority: spec.addr, - WASMByteCode: wasmContract, - InstantiatePermission: &types.AllowEverybody, - Admin: myAddress.String(), - UnpinCode: false, - Label: "test", - Msg: []byte(`{}`), - Funds: sdk.Coins{}, - } - rsp, err := wasmApp.MsgServiceRouter().Handler(msg)(ctx, msg) - require.NoError(t, err) - var storeAndInstantiateResponse types.MsgStoreAndInstantiateContractResponse - require.NoError(t, wasmApp.AppCodec().Unmarshal(rsp.Data, &storeAndInstantiateResponse)) - - // when - msgUpdateAdmin := &types.MsgUpdateAdmin{ - Sender: spec.addr, - NewAdmin: newAdmin.String(), - Contract: storeAndInstantiateResponse.Address, - } - _, err = wasmApp.MsgServiceRouter().Handler(msgUpdateAdmin)(ctx, msgUpdateAdmin) - - // then - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestClearAdmin(t *testing.T) { - wasmApp := app.Setup(t) - ctx := wasmApp.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) - - var ( - myAddress sdk.AccAddress = make([]byte, types.ContractAddrLen) - authority = wasmApp.WasmKeeper.GetAuthority() - _, _, otherAddr = testdata.KeyTestPubAddr() - ) - - specs := map[string]struct { - addr string - expErr bool - }{ - "authority can clear admin": { - addr: authority, - expErr: false, - }, - "admin can clear admin": { - addr: myAddress.String(), - expErr: false, - }, - "other address cannot clear admin": { - addr: otherAddr.String(), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - // setup - msg := &types.MsgStoreAndInstantiateContract{ - Authority: spec.addr, - WASMByteCode: wasmContract, - InstantiatePermission: &types.AllowEverybody, - Admin: myAddress.String(), - UnpinCode: false, - Label: "test", - Msg: []byte(`{}`), - Funds: sdk.Coins{}, - } - rsp, err := wasmApp.MsgServiceRouter().Handler(msg)(ctx, msg) - require.NoError(t, err) - var storeAndInstantiateResponse types.MsgStoreAndInstantiateContractResponse - require.NoError(t, wasmApp.AppCodec().Unmarshal(rsp.Data, &storeAndInstantiateResponse)) - - // when - msgClearAdmin := &types.MsgClearAdmin{ - Sender: spec.addr, - Contract: storeAndInstantiateResponse.Address, - } - _, err = wasmApp.MsgServiceRouter().Handler(msgClearAdmin)(ctx, msgClearAdmin) - - // then - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestMigrateContract(t *testing.T) { - wasmApp := app.Setup(t) - ctx := wasmApp.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) - - var ( - myAddress sdk.AccAddress = make([]byte, types.ContractAddrLen) - authority = wasmApp.WasmKeeper.GetAuthority() - _, _, otherAddr = testdata.KeyTestPubAddr() - ) - - specs := map[string]struct { - addr string - expErr bool - }{ - "authority can migrate a contract": { - addr: authority, - expErr: false, - }, - "admin can migrate a contract": { - addr: myAddress.String(), - expErr: false, - }, - "other address cannot migrate a contract": { - addr: otherAddr.String(), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - // setup - _, _, sender := testdata.KeyTestPubAddr() - msg := types.MsgStoreCodeFixture(func(m *types.MsgStoreCode) { - m.WASMByteCode = hackatomContract - m.Sender = sender.String() - }) - - // store code - rsp, err := wasmApp.MsgServiceRouter().Handler(msg)(ctx, msg) - require.NoError(t, err) - var storeCodeResponse types.MsgStoreCodeResponse - require.NoError(t, wasmApp.AppCodec().Unmarshal(rsp.Data, &storeCodeResponse)) - - // instantiate contract - initMsg := keeper.HackatomExampleInitMsg{ - Verifier: sender, - Beneficiary: myAddress, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - - msgInstantiate := &types.MsgInstantiateContract{ - Sender: sender.String(), - Admin: myAddress.String(), - CodeID: storeCodeResponse.CodeID, - Label: "test", - Msg: initMsgBz, - Funds: sdk.Coins{}, - } - rsp, err = wasmApp.MsgServiceRouter().Handler(msgInstantiate)(ctx, msgInstantiate) - require.NoError(t, err) - var instantiateResponse types.MsgInstantiateContractResponse - require.NoError(t, wasmApp.AppCodec().Unmarshal(rsp.Data, &instantiateResponse)) - - // when - migMsg := struct { - Verifier sdk.AccAddress `json:"verifier"` - }{Verifier: myAddress} - migMsgBz, err := json.Marshal(migMsg) - require.NoError(t, err) - msgMigrateContract := &types.MsgMigrateContract{ - Sender: spec.addr, - Msg: migMsgBz, - Contract: instantiateResponse.Address, - CodeID: storeCodeResponse.CodeID, - } - _, err = wasmApp.MsgServiceRouter().Handler(msgMigrateContract)(ctx, msgMigrateContract) - - // then - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestInstantiateContract(t *testing.T) { - wasmApp := app.Setup(t) - ctx := wasmApp.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) - - var ( - myAddress sdk.AccAddress = make([]byte, types.ContractAddrLen) - authority = wasmApp.WasmKeeper.GetAuthority() - ) - - specs := map[string]struct { - addr string - permission *types.AccessConfig - expErr bool - }{ - "authority can instantiate a contract when permission is nobody": { - addr: authority, - permission: &types.AllowNobody, - expErr: false, - }, - "other address cannot instantiate a contract when permission is nobody": { - addr: myAddress.String(), - permission: &types.AllowNobody, - expErr: true, - }, - "authority can instantiate a contract when permission is everybody": { - addr: authority, - permission: &types.AllowEverybody, - expErr: false, - }, - "other address can instantiate a contract when permission is everybody": { - addr: myAddress.String(), - permission: &types.AllowEverybody, - expErr: false, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - // setup - _, _, sender := testdata.KeyTestPubAddr() - msg := types.MsgStoreCodeFixture(func(m *types.MsgStoreCode) { - m.WASMByteCode = wasmContract - m.Sender = sender.String() - m.InstantiatePermission = spec.permission - }) - - // store code - rsp, err := wasmApp.MsgServiceRouter().Handler(msg)(ctx, msg) - require.NoError(t, err) - var result types.MsgStoreCodeResponse - require.NoError(t, wasmApp.AppCodec().Unmarshal(rsp.Data, &result)) - - // when - msgInstantiate := &types.MsgInstantiateContract{ - Sender: spec.addr, - Admin: myAddress.String(), - CodeID: result.CodeID, - Label: "test", - Msg: []byte(`{}`), - Funds: sdk.Coins{}, - } - _, err = wasmApp.MsgServiceRouter().Handler(msgInstantiate)(ctx, msgInstantiate) - - // then - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestInstantiateContract2(t *testing.T) { - wasmApp := app.Setup(t) - ctx := wasmApp.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) - - var ( - myAddress sdk.AccAddress = make([]byte, types.ContractAddrLen) - authority = wasmApp.WasmKeeper.GetAuthority() - ) - - specs := map[string]struct { - addr string - salt string - permission *types.AccessConfig - expErr bool - }{ - "authority can instantiate a contract when permission is nobody": { - addr: authority, - permission: &types.AllowNobody, - salt: "salt1", - expErr: false, - }, - "other address cannot instantiate a contract when permission is nobody": { - addr: myAddress.String(), - permission: &types.AllowNobody, - salt: "salt2", - expErr: true, - }, - "authority can instantiate a contract when permission is everybody": { - addr: authority, - permission: &types.AllowEverybody, - salt: "salt3", - expErr: false, - }, - "other address can instantiate a contract when permission is everybody": { - addr: myAddress.String(), - permission: &types.AllowEverybody, - salt: "salt4", - expErr: false, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - // setup - _, _, sender := testdata.KeyTestPubAddr() - msg := types.MsgStoreCodeFixture(func(m *types.MsgStoreCode) { - m.WASMByteCode = wasmContract - m.Sender = sender.String() - m.InstantiatePermission = spec.permission - }) - - // store code - rsp, err := wasmApp.MsgServiceRouter().Handler(msg)(ctx, msg) - require.NoError(t, err) - var result types.MsgStoreCodeResponse - require.NoError(t, wasmApp.AppCodec().Unmarshal(rsp.Data, &result)) - - // when - msgInstantiate := &types.MsgInstantiateContract2{ - Sender: spec.addr, - Admin: myAddress.String(), - CodeID: result.CodeID, - Label: "label", - Msg: []byte(`{}`), - Funds: sdk.Coins{}, - Salt: []byte(spec.salt), - FixMsg: true, - } - _, err = wasmApp.MsgServiceRouter().Handler(msgInstantiate)(ctx, msgInstantiate) - - // then - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestUpdateInstantiateConfig(t *testing.T) { - wasmApp := app.Setup(t) - ctx := wasmApp.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) - - var ( - creator sdk.AccAddress = make([]byte, types.ContractAddrLen) - authority = wasmApp.WasmKeeper.GetAuthority() - ) - - specs := map[string]struct { - addr string - permission *types.AccessConfig - expErr bool - }{ - "authority can update instantiate config when permission is subset": { - addr: authority, - permission: &types.AllowNobody, - expErr: false, - }, - "creator can update instantiate config when permission is subset": { - addr: creator.String(), - permission: &types.AllowNobody, - expErr: false, - }, - "authority can update instantiate config when permission is not subset": { - addr: authority, - permission: &types.AllowEverybody, - expErr: false, - }, - "creator cannot update instantiate config when permission is not subset": { - addr: creator.String(), - permission: &types.AllowEverybody, - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - // setup - err := wasmApp.WasmKeeper.SetParams(ctx, types.Params{ - CodeUploadAccess: types.AllowEverybody, - InstantiateDefaultPermission: types.AccessTypeNobody, - }) - require.NoError(t, err) - - msg := types.MsgStoreCodeFixture(func(m *types.MsgStoreCode) { - m.WASMByteCode = wasmContract - m.Sender = creator.String() - m.InstantiatePermission = &types.AllowNobody - }) - - // store code - rsp, err := wasmApp.MsgServiceRouter().Handler(msg)(ctx, msg) - require.NoError(t, err) - var result types.MsgStoreCodeResponse - require.NoError(t, wasmApp.AppCodec().Unmarshal(rsp.Data, &result)) - - // when - msgUpdateInstantiateConfig := &types.MsgUpdateInstantiateConfig{ - Sender: spec.addr, - CodeID: result.CodeID, - NewInstantiatePermission: spec.permission, - } - _, err = wasmApp.MsgServiceRouter().Handler(msgUpdateInstantiateConfig)(ctx, msgUpdateInstantiateConfig) - - // then - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} diff --git a/x/wasm/keeper/options.go b/x/wasm/keeper/options.go deleted file mode 100644 index 1ce15c5..0000000 --- a/x/wasm/keeper/options.go +++ /dev/null @@ -1,170 +0,0 @@ -package keeper - -import ( - "fmt" - "reflect" - - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/prometheus/client_golang/prometheus" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -type optsFn func(*Keeper) - -func (f optsFn) apply(keeper *Keeper) { - f(keeper) -} - -// WithWasmEngine is an optional constructor parameter to replace the default wasmVM engine with the -// given one. -func WithWasmEngine(x types.WasmerEngine) Option { - return optsFn(func(k *Keeper) { - k.wasmVM = x - }) -} - -// WithMessageHandler is an optional constructor parameter to set a custom handler for wasmVM messages. -// This option should not be combined with Option `WithMessageEncoders` or `WithMessageHandlerDecorator` -func WithMessageHandler(x Messenger) Option { - return optsFn(func(k *Keeper) { - k.messenger = x - }) -} - -// WithMessageHandlerDecorator is an optional constructor parameter to decorate the wasm handler for wasmVM messages. -// This option should not be combined with Option `WithMessageEncoders` or `WithMessageHandler` -func WithMessageHandlerDecorator(d func(old Messenger) Messenger) Option { - return optsFn(func(k *Keeper) { - k.messenger = d(k.messenger) - }) -} - -// WithQueryHandler is an optional constructor parameter to set custom query handler for wasmVM requests. -// This option should not be combined with Option `WithQueryPlugins` or `WithQueryHandlerDecorator` -func WithQueryHandler(x WasmVMQueryHandler) Option { - return optsFn(func(k *Keeper) { - k.wasmVMQueryHandler = x - }) -} - -// WithQueryHandlerDecorator is an optional constructor parameter to decorate the default wasm query handler for wasmVM requests. -// This option should not be combined with Option `WithQueryPlugins` or `WithQueryHandler` -func WithQueryHandlerDecorator(d func(old WasmVMQueryHandler) WasmVMQueryHandler) Option { - return optsFn(func(k *Keeper) { - k.wasmVMQueryHandler = d(k.wasmVMQueryHandler) - }) -} - -// WithQueryPlugins is an optional constructor parameter to pass custom query plugins for wasmVM requests. -// This option expects the default `QueryHandler` set and should not be combined with Option `WithQueryHandler` or `WithQueryHandlerDecorator`. -func WithQueryPlugins(x *QueryPlugins) Option { - return optsFn(func(k *Keeper) { - q, ok := k.wasmVMQueryHandler.(QueryPlugins) - if !ok { - panic(fmt.Sprintf("Unsupported query handler type: %T", k.wasmVMQueryHandler)) - } - k.wasmVMQueryHandler = q.Merge(x) - }) -} - -// WithMessageEncoders is an optional constructor parameter to pass custom message encoder to the default wasm message handler. -// This option expects the `DefaultMessageHandler` set and should not be combined with Option `WithMessageHandler` or `WithMessageHandlerDecorator`. -func WithMessageEncoders(x *MessageEncoders) Option { - return optsFn(func(k *Keeper) { - q, ok := k.messenger.(*MessageHandlerChain) - if !ok { - panic(fmt.Sprintf("Unsupported message handler type: %T", k.messenger)) - } - s, ok := q.handlers[0].(SDKMessageHandler) - if !ok { - panic(fmt.Sprintf("Unexpected message handler type: %T", q.handlers[0])) - } - e, ok := s.encoders.(MessageEncoders) - if !ok { - panic(fmt.Sprintf("Unsupported encoder type: %T", s.encoders)) - } - s.encoders = e.Merge(x) - q.handlers[0] = s - }) -} - -// WithCoinTransferrer is an optional constructor parameter to set a custom coin transferrer -func WithCoinTransferrer(x CoinTransferrer) Option { - if x == nil { - panic("must not be nil") - } - return optsFn(func(k *Keeper) { - k.bank = x - }) -} - -// WithAccountPruner is an optional constructor parameter to set a custom type that handles balances and data cleanup -// for accounts pruned on contract instantiate -func WithAccountPruner(x AccountPruner) Option { - if x == nil { - panic("must not be nil") - } - return optsFn(func(k *Keeper) { - k.accountPruner = x - }) -} - -func WithVMCacheMetrics(r prometheus.Registerer) Option { - return optsFn(func(k *Keeper) { - NewWasmVMMetricsCollector(k.wasmVM).Register(r) - }) -} - -// WithGasRegister set a new gas register to implement custom gas costs. -// When the "gas multiplier" for wasmvm gas conversion is modified inside the new register, -// make sure to also use `WithApiCosts` option for non default values -func WithGasRegister(x GasRegister) Option { - if x == nil { - panic("must not be nil") - } - return optsFn(func(k *Keeper) { - k.gasRegister = x - }) -} - -// WithAPICosts sets custom api costs. Amounts are in cosmwasm gas Not SDK gas. -func WithAPICosts(human, canonical uint64) Option { - return optsFn(func(_ *Keeper) { - costHumanize = human - costCanonical = canonical - }) -} - -// WithMaxQueryStackSize overwrites the default limit for maximum query stacks -func WithMaxQueryStackSize(m uint32) Option { - return optsFn(func(k *Keeper) { - k.maxQueryStackSize = m - }) -} - -// WithAcceptedAccountTypesOnContractInstantiation sets the accepted account types. Account types of this list won't be overwritten or cause a failure -// when they exist for an address on contract instantiation. -// -// Values should be references and contain the `*authtypes.BaseAccount` as default bank account type. -func WithAcceptedAccountTypesOnContractInstantiation(accts ...authtypes.AccountI) Option { - m := asTypeMap(accts) - return optsFn(func(k *Keeper) { - k.acceptedAccountTypes = m - }) -} - -func asTypeMap(accts []authtypes.AccountI) map[reflect.Type]struct{} { - m := make(map[reflect.Type]struct{}, len(accts)) - for _, a := range accts { - if a == nil { - panic(types.ErrEmpty.Wrap("address")) - } - at := reflect.TypeOf(a) - if _, exists := m[at]; exists { - panic(types.ErrDuplicate.Wrapf("%T", a)) - } - m[at] = struct{}{} - } - return m -} diff --git a/x/wasm/keeper/options_test.go b/x/wasm/keeper/options_test.go deleted file mode 100644 index e2c6142..0000000 --- a/x/wasm/keeper/options_test.go +++ /dev/null @@ -1,114 +0,0 @@ -package keeper - -import ( - "reflect" - "testing" - - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/keeper/wasmtesting" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestConstructorOptions(t *testing.T) { - specs := map[string]struct { - srcOpt Option - verify func(*testing.T, Keeper) - }{ - "wasm engine": { - srcOpt: WithWasmEngine(&wasmtesting.MockWasmer{}), - verify: func(t *testing.T, k Keeper) { - assert.IsType(t, &wasmtesting.MockWasmer{}, k.wasmVM) - }, - }, - "message handler": { - srcOpt: WithMessageHandler(&wasmtesting.MockMessageHandler{}), - verify: func(t *testing.T, k Keeper) { - assert.IsType(t, &wasmtesting.MockMessageHandler{}, k.messenger) - }, - }, - "query plugins": { - srcOpt: WithQueryHandler(&wasmtesting.MockQueryHandler{}), - verify: func(t *testing.T, k Keeper) { - assert.IsType(t, &wasmtesting.MockQueryHandler{}, k.wasmVMQueryHandler) - }, - }, - "message handler decorator": { - srcOpt: WithMessageHandlerDecorator(func(old Messenger) Messenger { - require.IsType(t, &MessageHandlerChain{}, old) - return &wasmtesting.MockMessageHandler{} - }), - verify: func(t *testing.T, k Keeper) { - assert.IsType(t, &wasmtesting.MockMessageHandler{}, k.messenger) - }, - }, - "query plugins decorator": { - srcOpt: WithQueryHandlerDecorator(func(old WasmVMQueryHandler) WasmVMQueryHandler { - require.IsType(t, QueryPlugins{}, old) - return &wasmtesting.MockQueryHandler{} - }), - verify: func(t *testing.T, k Keeper) { - assert.IsType(t, &wasmtesting.MockQueryHandler{}, k.wasmVMQueryHandler) - }, - }, - "coin transferrer": { - srcOpt: WithCoinTransferrer(&wasmtesting.MockCoinTransferrer{}), - verify: func(t *testing.T, k Keeper) { - assert.IsType(t, &wasmtesting.MockCoinTransferrer{}, k.bank) - }, - }, - "costs": { - srcOpt: WithGasRegister(&wasmtesting.MockGasRegister{}), - verify: func(t *testing.T, k Keeper) { - assert.IsType(t, &wasmtesting.MockGasRegister{}, k.gasRegister) - }, - }, - "api costs": { - srcOpt: WithAPICosts(1, 2), - verify: func(t *testing.T, k Keeper) { - t.Cleanup(setAPIDefaults) - assert.Equal(t, uint64(1), costHumanize) - assert.Equal(t, uint64(2), costCanonical) - }, - }, - "max recursion query limit": { - srcOpt: WithMaxQueryStackSize(1), - verify: func(t *testing.T, k Keeper) { - assert.IsType(t, uint32(1), k.maxQueryStackSize) - }, - }, - "accepted account types": { - srcOpt: WithAcceptedAccountTypesOnContractInstantiation(&authtypes.BaseAccount{}, &vestingtypes.ContinuousVestingAccount{}), - verify: func(t *testing.T, k Keeper) { - exp := map[reflect.Type]struct{}{ - reflect.TypeOf(&authtypes.BaseAccount{}): {}, - reflect.TypeOf(&vestingtypes.ContinuousVestingAccount{}): {}, - } - assert.Equal(t, exp, k.acceptedAccountTypes) - }, - }, - "account pruner": { - srcOpt: WithAccountPruner(VestingCoinBurner{}), - verify: func(t *testing.T, k Keeper) { - assert.Equal(t, VestingCoinBurner{}, k.accountPruner) - }, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - k := NewKeeper(nil, nil, authkeeper.AccountKeeper{}, &bankkeeper.BaseKeeper{}, stakingkeeper.Keeper{}, nil, nil, nil, nil, nil, nil, nil, "tempDir", types.DefaultWasmConfig(), AvailableCapabilities, "", spec.srcOpt) - spec.verify(t, k) - }) - } -} - -func setAPIDefaults() { - costHumanize = DefaultGasCostHumanAddress * DefaultGasMultiplier - costCanonical = DefaultGasCostCanonicalAddress * DefaultGasMultiplier -} diff --git a/x/wasm/keeper/proposal_handler.go b/x/wasm/keeper/proposal_handler.go deleted file mode 100644 index 6cc6214..0000000 --- a/x/wasm/keeper/proposal_handler.go +++ /dev/null @@ -1,342 +0,0 @@ -package keeper - -import ( - "bytes" - "encoding/hex" - "fmt" - - errorsmod "cosmossdk.io/errors" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// NewWasmProposalHandler creates a new governance Handler for wasm proposals -// -// Deprecated: Do not use. -func NewWasmProposalHandler(k decoratedKeeper, enabledProposalTypes []types.ProposalType) v1beta1.Handler { - return NewWasmProposalHandlerX(NewGovPermissionKeeper(k), enabledProposalTypes) -} - -// NewWasmProposalHandlerX creates a new governance Handler for wasm proposals -// -// Deprecated: Do not use. -func NewWasmProposalHandlerX(k types.ContractOpsKeeper, enabledProposalTypes []types.ProposalType) v1beta1.Handler { - enabledTypes := make(map[string]struct{}, len(enabledProposalTypes)) - for i := range enabledProposalTypes { - enabledTypes[string(enabledProposalTypes[i])] = struct{}{} - } - return func(ctx sdk.Context, content v1beta1.Content) error { - if content == nil { - return errorsmod.Wrap(sdkerrors.ErrUnknownRequest, "content must not be empty") - } - if _, ok := enabledTypes[content.ProposalType()]; !ok { - return errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "unsupported wasm proposal content type: %q", content.ProposalType()) - } - switch c := content.(type) { - case *types.StoreCodeProposal: - return handleStoreCodeProposal(ctx, k, *c) - case *types.InstantiateContractProposal: - return handleInstantiateProposal(ctx, k, *c) - case *types.InstantiateContract2Proposal: - return handleInstantiate2Proposal(ctx, k, *c) - case *types.MigrateContractProposal: - return handleMigrateProposal(ctx, k, *c) - case *types.SudoContractProposal: - return handleSudoProposal(ctx, k, *c) - case *types.ExecuteContractProposal: - return handleExecuteProposal(ctx, k, *c) - case *types.UpdateAdminProposal: - return handleUpdateAdminProposal(ctx, k, *c) - case *types.ClearAdminProposal: - return handleClearAdminProposal(ctx, k, *c) - case *types.PinCodesProposal: - return handlePinCodesProposal(ctx, k, *c) - case *types.UnpinCodesProposal: - return handleUnpinCodesProposal(ctx, k, *c) - case *types.UpdateInstantiateConfigProposal: - return handleUpdateInstantiateConfigProposal(ctx, k, *c) - case *types.StoreAndInstantiateContractProposal: - return handleStoreAndInstantiateContractProposal(ctx, k, *c) - default: - return errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized wasm proposal content type: %T", c) - } - } -} - -//nolint:staticcheck -func handleStoreCodeProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.StoreCodeProposal) error { - if err := p.ValidateBasic(); err != nil { - return err - } - - runAsAddr, err := sdk.AccAddressFromBech32(p.RunAs) - if err != nil { - return errorsmod.Wrap(err, "run as address") - } - codeID, checksum, err := k.Create(ctx, runAsAddr, p.WASMByteCode, p.InstantiatePermission) - if err != nil { - return err - } - - if len(p.CodeHash) != 0 && !bytes.Equal(checksum, p.CodeHash) { - return fmt.Errorf("code-hash mismatch: %X, checksum: %X", p.CodeHash, checksum) - } - - // if code should not be pinned return earlier - if p.UnpinCode { - return nil - } - return k.PinCode(ctx, codeID) -} - -//nolint:staticcheck -func handleInstantiateProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.InstantiateContractProposal) error { - if err := p.ValidateBasic(); err != nil { - return err - } - runAsAddr, err := sdk.AccAddressFromBech32(p.RunAs) - if err != nil { - return errorsmod.Wrap(err, "run as address") - } - var adminAddr sdk.AccAddress - if p.Admin != "" { - if adminAddr, err = sdk.AccAddressFromBech32(p.Admin); err != nil { - return errorsmod.Wrap(err, "admin") - } - } - - _, data, err := k.Instantiate(ctx, p.CodeID, runAsAddr, adminAddr, p.Msg, p.Label, p.Funds) - if err != nil { - return err - } - - ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypeGovContractResult, - sdk.NewAttribute(types.AttributeKeyResultDataHex, hex.EncodeToString(data)), - )) - return nil -} - -//nolint:staticcheck -func handleInstantiate2Proposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.InstantiateContract2Proposal) error { - // Validatebasic with proposal - if err := p.ValidateBasic(); err != nil { - return err - } - - // Get runAsAddr as AccAddress - runAsAddr, err := sdk.AccAddressFromBech32(p.RunAs) - if err != nil { - return errorsmod.Wrap(err, "run as address") - } - - // Get admin address - var adminAddr sdk.AccAddress - if p.Admin != "" { - if adminAddr, err = sdk.AccAddressFromBech32(p.Admin); err != nil { - return errorsmod.Wrap(err, "admin") - } - } - - _, data, err := k.Instantiate2(ctx, p.CodeID, runAsAddr, adminAddr, p.Msg, p.Label, p.Funds, p.Salt, p.FixMsg) - if err != nil { - return err - } - - ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypeGovContractResult, - sdk.NewAttribute(types.AttributeKeyResultDataHex, hex.EncodeToString(data)), - )) - return nil -} - -//nolint:staticcheck -func handleStoreAndInstantiateContractProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.StoreAndInstantiateContractProposal) error { - if err := p.ValidateBasic(); err != nil { - return err - } - runAsAddr, err := sdk.AccAddressFromBech32(p.RunAs) - if err != nil { - return errorsmod.Wrap(err, "run as address") - } - var adminAddr sdk.AccAddress - if p.Admin != "" { - if adminAddr, err = sdk.AccAddressFromBech32(p.Admin); err != nil { - return errorsmod.Wrap(err, "admin") - } - } - - codeID, checksum, err := k.Create(ctx, runAsAddr, p.WASMByteCode, p.InstantiatePermission) - if err != nil { - return err - } - - if p.CodeHash != nil && !bytes.Equal(checksum, p.CodeHash) { - return errorsmod.Wrap(fmt.Errorf("code-hash mismatch: %X, checksum: %X", p.CodeHash, checksum), "code-hash mismatch") - } - - if !p.UnpinCode { - if err := k.PinCode(ctx, codeID); err != nil { - return err - } - } - - _, data, err := k.Instantiate(ctx, codeID, runAsAddr, adminAddr, p.Msg, p.Label, p.Funds) - if err != nil { - return err - } - - ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypeGovContractResult, - sdk.NewAttribute(types.AttributeKeyResultDataHex, hex.EncodeToString(data)), - )) - return nil -} - -//nolint:staticcheck -func handleMigrateProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.MigrateContractProposal) error { - if err := p.ValidateBasic(); err != nil { - return err - } - - contractAddr, err := sdk.AccAddressFromBech32(p.Contract) - if err != nil { - return errorsmod.Wrap(err, "contract") - } - - // runAs is not used if this is permissioned, so just put any valid address there (second contractAddr) - data, err := k.Migrate(ctx, contractAddr, contractAddr, p.CodeID, p.Msg) - if err != nil { - return err - } - - ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypeGovContractResult, - sdk.NewAttribute(types.AttributeKeyResultDataHex, hex.EncodeToString(data)), - )) - return nil -} - -//nolint:staticcheck -func handleSudoProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.SudoContractProposal) error { - if err := p.ValidateBasic(); err != nil { - return err - } - - contractAddr, err := sdk.AccAddressFromBech32(p.Contract) - if err != nil { - return errorsmod.Wrap(err, "contract") - } - data, err := k.Sudo(ctx, contractAddr, p.Msg) - if err != nil { - return err - } - - ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypeGovContractResult, - sdk.NewAttribute(types.AttributeKeyResultDataHex, hex.EncodeToString(data)), - )) - return nil -} - -//nolint:staticcheck -func handleExecuteProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.ExecuteContractProposal) error { - if err := p.ValidateBasic(); err != nil { - return err - } - - contractAddr, err := sdk.AccAddressFromBech32(p.Contract) - if err != nil { - return errorsmod.Wrap(err, "contract") - } - runAsAddr, err := sdk.AccAddressFromBech32(p.RunAs) - if err != nil { - return errorsmod.Wrap(err, "run as address") - } - data, err := k.Execute(ctx, contractAddr, runAsAddr, p.Msg, p.Funds) - if err != nil { - return err - } - - ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypeGovContractResult, - sdk.NewAttribute(types.AttributeKeyResultDataHex, hex.EncodeToString(data)), - )) - return nil -} - -//nolint:staticcheck -func handleUpdateAdminProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.UpdateAdminProposal) error { - if err := p.ValidateBasic(); err != nil { - return err - } - contractAddr, err := sdk.AccAddressFromBech32(p.Contract) - if err != nil { - return errorsmod.Wrap(err, "contract") - } - newAdminAddr, err := sdk.AccAddressFromBech32(p.NewAdmin) - if err != nil { - return errorsmod.Wrap(err, "run as address") - } - - return k.UpdateContractAdmin(ctx, contractAddr, nil, newAdminAddr) -} - -//nolint:staticcheck -func handleClearAdminProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.ClearAdminProposal) error { - if err := p.ValidateBasic(); err != nil { - return err - } - - contractAddr, err := sdk.AccAddressFromBech32(p.Contract) - if err != nil { - return errorsmod.Wrap(err, "contract") - } - err = k.ClearContractAdmin(ctx, contractAddr, nil) - return err -} - -//nolint:staticcheck -func handlePinCodesProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.PinCodesProposal) error { - if err := p.ValidateBasic(); err != nil { - return err - } - for _, v := range p.CodeIDs { - if err := k.PinCode(ctx, v); err != nil { - return errorsmod.Wrapf(err, "code id: %d", v) - } - } - return nil -} - -//nolint:staticcheck -func handleUnpinCodesProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.UnpinCodesProposal) error { - if err := p.ValidateBasic(); err != nil { - return err - } - for _, v := range p.CodeIDs { - if err := k.UnpinCode(ctx, v); err != nil { - return errorsmod.Wrapf(err, "code id: %d", v) - } - } - return nil -} - -//nolint:staticcheck -func handleUpdateInstantiateConfigProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.UpdateInstantiateConfigProposal) error { - if err := p.ValidateBasic(); err != nil { - return err - } - - var emptyCaller sdk.AccAddress - for _, accessConfigUpdate := range p.AccessConfigUpdates { - if err := k.SetAccessConfig(ctx, accessConfigUpdate.CodeID, emptyCaller, accessConfigUpdate.InstantiatePermission); err != nil { - return errorsmod.Wrapf(err, "code id: %d", accessConfigUpdate.CodeID) - } - } - return nil -} diff --git a/x/wasm/keeper/proposal_integration_test.go b/x/wasm/keeper/proposal_integration_test.go deleted file mode 100644 index 1b8d93d..0000000 --- a/x/wasm/keeper/proposal_integration_test.go +++ /dev/null @@ -1,926 +0,0 @@ -package keeper - -import ( - "bytes" - "encoding/hex" - "encoding/json" - "errors" - "os" - "testing" - - wasmvm "github.com/CosmWasm/wasmvm" - sdk "github.com/cosmos/cosmos-sdk/types" - govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/keeper/wasmtesting" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -const myTestLabel = "testing" - -func TestStoreCodeProposal(t *testing.T) { - parentCtx, keepers := CreateTestInput(t, false, "staking") - wasmKeeper := keepers.WasmKeeper - err := wasmKeeper.SetParams(parentCtx, types.Params{ - CodeUploadAccess: types.AllowNobody, - InstantiateDefaultPermission: types.AccessTypeNobody, - }) - require.NoError(t, err) - rawWasmCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - gzippedWasmCode, err := os.ReadFile("./testdata/hackatom.wasm.gzip") - require.NoError(t, err) - checksum, err := hex.DecodeString("beb3de5e9b93b52e514c74ce87ccddb594b9bcd33b7f1af1bb6da63fc883917b") - require.NoError(t, err) - - specs := map[string]struct { - codeID int64 - code []byte - unpinCode bool - }{ - "upload with pinning (default)": { - unpinCode: false, - code: rawWasmCode, - }, - "upload with code unpin": { - unpinCode: true, - code: rawWasmCode, - }, - "upload with raw wasm code": { - code: rawWasmCode, - }, - "upload with zipped wasm code": { - code: gzippedWasmCode, - }, - } - - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - ctx, _ := parentCtx.CacheContext() - myActorAddress := RandomBech32AccountAddress(t) - - src := types.StoreCodeProposalFixture(func(p *types.StoreCodeProposal) { //nolint:staticcheck // testing a deprecated library - p.RunAs = myActorAddress - p.WASMByteCode = spec.code - p.UnpinCode = spec.unpinCode - p.CodeHash = checksum - }) - - // when - mustSubmitAndExecuteLegacyProposal(t, ctx, src, myActorAddress, keepers) - - // then - cInfo := wasmKeeper.GetCodeInfo(ctx, 1) - require.NotNil(t, cInfo) - assert.Equal(t, myActorAddress, cInfo.Creator) - assert.Equal(t, !spec.unpinCode, wasmKeeper.IsPinnedCode(ctx, 1)) - - storedCode, err := wasmKeeper.GetByteCode(ctx, 1) - require.NoError(t, err) - assert.Equal(t, rawWasmCode, storedCode) - }) - } -} - -func mustSubmitAndExecuteLegacyProposal(t *testing.T, ctx sdk.Context, content v1beta1.Content, myActorAddress string, keepers TestKeepers) { - t.Helper() - govAuthority := keepers.AccountKeeper.GetModuleAddress(govtypes.ModuleName).String() - msgServer := govkeeper.NewMsgServerImpl(keepers.GovKeeper) - // ignore all submit events - contentMsg, err := submitLegacyProposal(t, ctx.WithEventManager(sdk.NewEventManager()), content, myActorAddress, govAuthority, msgServer) - require.NoError(t, err) - - _, err = msgServer.ExecLegacyContent(sdk.WrapSDKContext(ctx), v1.NewMsgExecLegacyContent(contentMsg.Content, govAuthority)) - require.NoError(t, err) -} - -// does not fail on submit proposal -func submitLegacyProposal(t *testing.T, ctx sdk.Context, content v1beta1.Content, myActorAddress string, govAuthority string, msgServer v1.MsgServer) (*v1.MsgExecLegacyContent, error) { - t.Helper() - contentMsg, err := v1.NewLegacyContent(content, govAuthority) - require.NoError(t, err) - - proposal, err := v1.NewMsgSubmitProposal( - []sdk.Msg{contentMsg}, - sdk.Coins{}, - myActorAddress, - "", - "my title", - "my description", - ) - require.NoError(t, err) - - // when stored - _, err = msgServer.SubmitProposal(sdk.WrapSDKContext(ctx), proposal) - return contentMsg, err -} - -func TestInstantiateProposal(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, "staking") - wasmKeeper := keepers.WasmKeeper - err := wasmKeeper.SetParams(ctx, types.Params{ - CodeUploadAccess: types.AllowNobody, - InstantiateDefaultPermission: types.AccessTypeNobody, - }) - require.NoError(t, err) - - wasmCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - - require.NoError(t, wasmKeeper.importCode(ctx, 1, - types.CodeInfoFixture(types.WithSHA256CodeHash(wasmCode)), - wasmCode), - ) - - var ( - oneAddress sdk.AccAddress = bytes.Repeat([]byte{0x1}, types.ContractAddrLen) - otherAddress sdk.AccAddress = bytes.Repeat([]byte{0x2}, types.ContractAddrLen) - ) - src := types.InstantiateContractProposalFixture(func(p *types.InstantiateContractProposal) { //nolint:staticcheck // testing a deprecated library - p.CodeID = firstCodeID - p.RunAs = oneAddress.String() - p.Admin = otherAddress.String() - p.Label = myTestLabel - }) - em := sdk.NewEventManager() - - // when - mustSubmitAndExecuteLegacyProposal(t, ctx.WithEventManager(em), src, oneAddress.String(), keepers) - - // then - contractAddr, err := sdk.AccAddressFromBech32("cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr") - require.NoError(t, err) - - cInfo := wasmKeeper.GetContractInfo(ctx, contractAddr) - require.NotNil(t, cInfo) - assert.Equal(t, uint64(1), cInfo.CodeID) - assert.Equal(t, oneAddress.String(), cInfo.Creator) - assert.Equal(t, otherAddress.String(), cInfo.Admin) - assert.Equal(t, myTestLabel, cInfo.Label) - expHistory := []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeInit, - CodeID: src.CodeID, - Updated: types.NewAbsoluteTxPosition(ctx), - Msg: src.Msg, - }} - assert.Equal(t, expHistory, wasmKeeper.GetContractHistory(ctx, contractAddr)) - // and event - require.Len(t, em.Events(), 3, "%#v", em.Events()) - require.Equal(t, types.EventTypeInstantiate, em.Events()[0].Type) - require.Equal(t, types.WasmModuleEventType, em.Events()[1].Type) - require.Equal(t, types.EventTypeGovContractResult, em.Events()[2].Type) - require.Len(t, em.Events()[2].Attributes, 1) - require.NotEmpty(t, em.Events()[2].Attributes[0]) -} - -func TestInstantiate2Proposal(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, "staking") - wasmKeeper := keepers.WasmKeeper - err := wasmKeeper.SetParams(ctx, types.Params{ - CodeUploadAccess: types.AllowNobody, - InstantiateDefaultPermission: types.AccessTypeNobody, - }) - require.NoError(t, err) - - wasmCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - - codeInfo := types.CodeInfoFixture(types.WithSHA256CodeHash(wasmCode)) - err = wasmKeeper.importCode(ctx, 1, codeInfo, wasmCode) - require.NoError(t, err) - - var ( - oneAddress sdk.AccAddress = bytes.Repeat([]byte{0x1}, types.ContractAddrLen) - otherAddress sdk.AccAddress = bytes.Repeat([]byte{0x2}, types.ContractAddrLen) - label = "label" - salt = []byte("mySalt") - ) - src := types.InstantiateContract2ProposalFixture(func(p *types.InstantiateContract2Proposal) { //nolint:staticcheck // testing a deprecated library - p.CodeID = firstCodeID - p.RunAs = oneAddress.String() - p.Admin = otherAddress.String() - p.Label = label - p.Salt = salt - }) - contractAddress := BuildContractAddressPredictable(codeInfo.CodeHash, oneAddress, salt, []byte{}) - - em := sdk.NewEventManager() - - // when - mustSubmitAndExecuteLegacyProposal(t, ctx.WithEventManager(em), src, oneAddress.String(), keepers) - - cInfo := wasmKeeper.GetContractInfo(ctx, contractAddress) - require.NotNil(t, cInfo) - - assert.Equal(t, uint64(1), cInfo.CodeID) - assert.Equal(t, oneAddress.String(), cInfo.Creator) - assert.Equal(t, otherAddress.String(), cInfo.Admin) - assert.Equal(t, "label", cInfo.Label) - expHistory := []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeInit, - CodeID: src.CodeID, - Updated: types.NewAbsoluteTxPosition(ctx), - Msg: src.Msg, - }} - assert.Equal(t, expHistory, wasmKeeper.GetContractHistory(ctx, contractAddress)) - // and event - require.Len(t, em.Events(), 3, prettyEvents(t, em.Events())) - require.Equal(t, types.EventTypeInstantiate, em.Events()[0].Type) - require.Equal(t, types.WasmModuleEventType, em.Events()[1].Type) - require.Equal(t, types.EventTypeGovContractResult, em.Events()[2].Type) - require.Len(t, em.Events()[2].Attributes, 1) - require.NotEmpty(t, em.Events()[2].Attributes[0]) -} - -func TestInstantiateProposal_NoAdmin(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, "staking") - wasmKeeper := keepers.WasmKeeper - err := wasmKeeper.SetParams(ctx, types.Params{ - CodeUploadAccess: types.AllowNobody, - InstantiateDefaultPermission: types.AccessTypeNobody, - }) - require.NoError(t, err) - - wasmCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - - require.NoError(t, wasmKeeper.importCode(ctx, 1, - types.CodeInfoFixture(types.WithSHA256CodeHash(wasmCode)), - wasmCode), - ) - - var oneAddress sdk.AccAddress = bytes.Repeat([]byte{0x1}, types.ContractAddrLen) - - specs := map[string]struct { - srcAdmin string - expErr bool - }{ - "empty admin": { - srcAdmin: "", - }, - "invalid admin": { - srcAdmin: "invalid", - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - src := types.InstantiateContractProposalFixture(func(p *types.InstantiateContractProposal) { //nolint:staticcheck // testing a deprecated library - p.CodeID = firstCodeID - p.RunAs = oneAddress.String() - p.Admin = spec.srcAdmin - p.Label = myTestLabel - }) - govAuthority := keepers.AccountKeeper.GetModuleAddress(govtypes.ModuleName).String() - msgServer := govkeeper.NewMsgServerImpl(keepers.GovKeeper) - // when - contentMsg, gotErr := submitLegacyProposal(t, ctx, src, oneAddress.String(), govAuthority, msgServer) - // then - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - // and when - em := sdk.NewEventManager() - _, err = msgServer.ExecLegacyContent(sdk.WrapSDKContext(ctx.WithEventManager(em)), v1.NewMsgExecLegacyContent(contentMsg.Content, govAuthority)) - // then - require.NoError(t, err) - contractAddr, err := sdk.AccAddressFromBech32("cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr") - require.NoError(t, err) - - cInfo := wasmKeeper.GetContractInfo(ctx, contractAddr) - require.NotNil(t, cInfo) - assert.Equal(t, uint64(1), cInfo.CodeID) - assert.Equal(t, oneAddress.String(), cInfo.Creator) - assert.Equal(t, "", cInfo.Admin) - assert.Equal(t, myTestLabel, cInfo.Label) - expHistory := []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeInit, - CodeID: src.CodeID, - Updated: types.NewAbsoluteTxPosition(ctx), - Msg: src.Msg, - }} - assert.Equal(t, expHistory, wasmKeeper.GetContractHistory(ctx, contractAddr)) - // and event - require.Len(t, em.Events(), 3, "%#v", em.Events()) - require.Equal(t, types.EventTypeInstantiate, em.Events()[0].Type) - require.Equal(t, types.WasmModuleEventType, em.Events()[1].Type) - require.Equal(t, types.EventTypeGovContractResult, em.Events()[2].Type) - require.Len(t, em.Events()[2].Attributes, 1) - require.NotEmpty(t, em.Events()[2].Attributes[0]) - }) - } -} - -func TestStoreAndInstantiateContractProposal(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, "staking") - wasmKeeper := keepers.WasmKeeper - err := wasmKeeper.SetParams(ctx, types.Params{ - CodeUploadAccess: types.AllowNobody, - InstantiateDefaultPermission: types.AccessTypeNobody, - }) - require.NoError(t, err) - - wasmCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - - checksum, err := hex.DecodeString("beb3de5e9b93b52e514c74ce87ccddb594b9bcd33b7f1af1bb6da63fc883917b") - require.NoError(t, err) - - var ( - oneAddress sdk.AccAddress = bytes.Repeat([]byte{0x1}, types.ContractAddrLen) - otherAddress sdk.AccAddress = bytes.Repeat([]byte{0x2}, types.ContractAddrLen) - ) - - src := types.StoreAndInstantiateContractProposalFixture(func(p *types.StoreAndInstantiateContractProposal) { //nolint:staticcheck // testing a deprecated library - p.WASMByteCode = wasmCode - p.RunAs = oneAddress.String() - p.Admin = otherAddress.String() - p.Label = myTestLabel - p.CodeHash = checksum - }) - em := sdk.NewEventManager() - - // when - mustSubmitAndExecuteLegacyProposal(t, ctx.WithEventManager(em), src, oneAddress.String(), keepers) - - // then - contractAddr, err := sdk.AccAddressFromBech32("cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr") - require.NoError(t, err) - - cInfo := wasmKeeper.GetContractInfo(ctx, contractAddr) - require.NotNil(t, cInfo) - assert.Equal(t, oneAddress.String(), cInfo.Creator) - assert.Equal(t, otherAddress.String(), cInfo.Admin) - assert.Equal(t, myTestLabel, cInfo.Label) - expHistory := []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeInit, - CodeID: cInfo.CodeID, - Updated: types.NewAbsoluteTxPosition(ctx), - Msg: src.Msg, - }} - assert.Equal(t, expHistory, wasmKeeper.GetContractHistory(ctx, contractAddr)) - // and event - require.Len(t, em.Events(), 5, "%#v", em.Events()) - require.Equal(t, types.EventTypeStoreCode, em.Events()[0].Type) - require.Equal(t, types.EventTypePinCode, em.Events()[1].Type) - require.Equal(t, types.EventTypeInstantiate, em.Events()[2].Type) - require.Equal(t, types.WasmModuleEventType, em.Events()[3].Type) - require.Equal(t, types.EventTypeGovContractResult, em.Events()[4].Type) - require.Len(t, em.Events()[4].Attributes, 1) - require.NotEmpty(t, em.Events()[4].Attributes[0]) -} - -func TestMigrateProposal(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, "staking") - wasmKeeper := keepers.WasmKeeper - err := wasmKeeper.SetParams(ctx, types.Params{ - CodeUploadAccess: types.AllowNobody, - InstantiateDefaultPermission: types.AccessTypeNobody, - }) - require.NoError(t, err) - - wasmCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - - codeInfoFixture := types.CodeInfoFixture(types.WithSHA256CodeHash(wasmCode)) - require.NoError(t, wasmKeeper.importCode(ctx, 1, codeInfoFixture, wasmCode)) - require.NoError(t, wasmKeeper.importCode(ctx, 2, codeInfoFixture, wasmCode)) - - var ( - anyAddress = DeterministicAccountAddress(t, 1) - otherAddress = DeterministicAccountAddress(t, 2) - contractAddr = BuildContractAddressClassic(1, 1) - ) - - contractInfo := types.ContractInfoFixture(func(c *types.ContractInfo) { - c.Label = myTestLabel - c.Admin = anyAddress.String() - c.Created = types.NewAbsoluteTxPosition(ctx) - }) - entries := []types.ContractCodeHistoryEntry{ - {Operation: types.ContractCodeHistoryOperationTypeInit, CodeID: 1, Updated: contractInfo.Created}, - } - key, err := hex.DecodeString("636F6E666967") - require.NoError(t, err) - m := types.Model{Key: key, Value: []byte(`{"verifier":"AAAAAAAAAAAAAAAAAAAAAAAAAAA=","beneficiary":"AAAAAAAAAAAAAAAAAAAAAAAAAAA=","funder":"AQEBAQEBAQEBAQEBAQEBAQEBAQE="}`)} - require.NoError(t, wasmKeeper.importContract(ctx, contractAddr, &contractInfo, []types.Model{m}, entries)) - - migMsg := struct { - Verifier sdk.AccAddress `json:"verifier"` - }{Verifier: otherAddress} - migMsgBz, err := json.Marshal(migMsg) - require.NoError(t, err) - - src := &types.MigrateContractProposal{ //nolint:staticcheck // testing a deprecated library - Title: "Foo", - Description: "Bar", - CodeID: 2, - Contract: contractAddr.String(), - Msg: migMsgBz, - } - - em := sdk.NewEventManager() - - // when - mustSubmitAndExecuteLegacyProposal(t, ctx.WithEventManager(em), src, anyAddress.String(), keepers) - - // then - require.NoError(t, err) - cInfo := wasmKeeper.GetContractInfo(ctx, contractAddr) - require.NotNil(t, cInfo) - assert.Equal(t, uint64(2), cInfo.CodeID) - assert.Equal(t, anyAddress.String(), cInfo.Admin) - assert.Equal(t, myTestLabel, cInfo.Label) - expHistory := []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeInit, - CodeID: firstCodeID, - Updated: types.NewAbsoluteTxPosition(ctx), - }, { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: src.CodeID, - Updated: types.NewAbsoluteTxPosition(ctx), - Msg: src.Msg, - }} - assert.Equal(t, expHistory, wasmKeeper.GetContractHistory(ctx, contractAddr)) - // and events emitted - require.Len(t, em.Events(), 2) - assert.Equal(t, types.EventTypeMigrate, em.Events()[0].Type) - require.Equal(t, types.EventTypeGovContractResult, em.Events()[1].Type) - require.Len(t, em.Events()[1].Attributes, 1) - assert.Equal(t, types.AttributeKeyResultDataHex, em.Events()[1].Attributes[0].Key) -} - -func TestExecuteProposal(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, "staking") - bankKeeper := keepers.BankKeeper - - exampleContract := InstantiateHackatomExampleContract(t, ctx, keepers) - contractAddr := exampleContract.Contract - - // check balance - bal := bankKeeper.GetBalance(ctx, contractAddr, "denom") - require.Equal(t, bal.Amount, sdk.NewInt(100)) - - releaseMsg := struct { - Release struct{} `json:"release"` - }{} - releaseMsgBz, err := json.Marshal(releaseMsg) - require.NoError(t, err) - - // try with runAs that doesn't have pemission - badSrc := &types.ExecuteContractProposal{ //nolint:staticcheck // testing a deprecated library - Title: "First", - Description: "Beneficiary has no permission to run", - Contract: contractAddr.String(), - Msg: releaseMsgBz, - RunAs: exampleContract.BeneficiaryAddr.String(), - } - - // fails on store - this doesn't have permission - govAuthority := keepers.AccountKeeper.GetModuleAddress(govtypes.ModuleName).String() - msgServer := govkeeper.NewMsgServerImpl(keepers.GovKeeper) - _, err = submitLegacyProposal(t, ctx, badSrc, exampleContract.BeneficiaryAddr.String(), govAuthority, msgServer) - require.Error(t, err) - - // balance should not change - bal = bankKeeper.GetBalance(ctx, contractAddr, "denom") - require.Equal(t, bal.Amount, sdk.NewInt(100)) - - // try again with the proper run-as - src := &types.ExecuteContractProposal{ //nolint:staticcheck // testing a deprecated library - Title: "Second", - Description: "Verifier can execute", - Contract: contractAddr.String(), - Msg: releaseMsgBz, - RunAs: exampleContract.VerifierAddr.String(), - } - - em := sdk.NewEventManager() - - // when - mustSubmitAndExecuteLegacyProposal(t, ctx.WithEventManager(em), src, exampleContract.BeneficiaryAddr.String(), keepers) - - // balance should be empty (proper release) - bal = bankKeeper.GetBalance(ctx, contractAddr, "denom") - require.Equal(t, bal.Amount, sdk.NewInt(0)) -} - -func TestSudoProposal(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, "staking") - bankKeeper := keepers.BankKeeper - - exampleContract := InstantiateHackatomExampleContract(t, ctx, keepers) - contractAddr := exampleContract.Contract - _, anyAddr := keyPubAddr() - - // check balance - bal := bankKeeper.GetBalance(ctx, contractAddr, "denom") - require.Equal(t, bal.Amount, sdk.NewInt(100)) - bal = bankKeeper.GetBalance(ctx, anyAddr, "denom") - require.Equal(t, bal.Amount, sdk.NewInt(0)) - - type StealMsg struct { - Recipient string `json:"recipient"` - Amount []sdk.Coin `json:"amount"` - } - stealMsg := struct { - Steal StealMsg `json:"steal_funds"` - }{Steal: StealMsg{ - Recipient: anyAddr.String(), - Amount: []sdk.Coin{sdk.NewInt64Coin("denom", 75)}, - }} - stealMsgBz, err := json.Marshal(stealMsg) - require.NoError(t, err) - - // sudo can do anything - src := &types.SudoContractProposal{ //nolint:staticcheck // testing a deprecated library - Title: "Sudo", - Description: "Steal funds for the verifier", - Contract: contractAddr.String(), - Msg: stealMsgBz, - } - - em := sdk.NewEventManager() - - // when - mustSubmitAndExecuteLegacyProposal(t, ctx.WithEventManager(em), src, exampleContract.BeneficiaryAddr.String(), keepers) - - // balance should be empty (and verifier richer) - bal = bankKeeper.GetBalance(ctx, contractAddr, "denom") - require.Equal(t, bal.Amount, sdk.NewInt(25)) - bal = bankKeeper.GetBalance(ctx, anyAddr, "denom") - require.Equal(t, bal.Amount, sdk.NewInt(75)) -} - -func TestAdminProposals(t *testing.T) { - var ( - otherAddress sdk.AccAddress = bytes.Repeat([]byte{0x2}, types.ContractAddrLen) - contractAddr = BuildContractAddressClassic(1, 1) - ) - wasmCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - - specs := map[string]struct { - state types.ContractInfo - srcProposal v1beta1.Content - expAdmin sdk.AccAddress - }{ - "update with different admin": { - state: types.ContractInfoFixture(), - srcProposal: &types.UpdateAdminProposal{ //nolint:staticcheck // testing a deprecated library - Title: "Foo", - Description: "Bar", - Contract: contractAddr.String(), - NewAdmin: otherAddress.String(), - }, - expAdmin: otherAddress, - }, - "update with old admin empty": { - state: types.ContractInfoFixture(func(info *types.ContractInfo) { - info.Admin = "" - }), - srcProposal: &types.UpdateAdminProposal{ //nolint:staticcheck // testing a deprecated library - Title: "Foo", - Description: "Bar", - Contract: contractAddr.String(), - NewAdmin: otherAddress.String(), - }, - expAdmin: otherAddress, - }, - "clear admin": { - state: types.ContractInfoFixture(), - srcProposal: &types.ClearAdminProposal{ //nolint:staticcheck // testing a deprecated library - Title: "Foo", - Description: "Bar", - Contract: contractAddr.String(), - }, - expAdmin: nil, - }, - "clear with old admin empty": { - state: types.ContractInfoFixture(func(info *types.ContractInfo) { - info.Admin = "" - }), - srcProposal: &types.ClearAdminProposal{ //nolint:staticcheck // testing a deprecated library - Title: "Foo", - Description: "Bar", - Contract: contractAddr.String(), - }, - expAdmin: nil, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, "staking") - wasmKeeper := keepers.WasmKeeper - err := wasmKeeper.SetParams(ctx, types.Params{ - CodeUploadAccess: types.AllowNobody, - InstantiateDefaultPermission: types.AccessTypeNobody, - }) - require.NoError(t, err) - - codeInfo := types.CodeInfoFixture(types.WithSHA256CodeHash(wasmCode)) - require.NoError(t, wasmKeeper.importCode(ctx, 1, codeInfo, wasmCode)) - - entries := []types.ContractCodeHistoryEntry{ - { - Operation: types.ContractCodeHistoryOperationTypeInit, - CodeID: 1, - Updated: spec.state.Created, - }, - } - - require.NoError(t, wasmKeeper.importContract(ctx, contractAddr, &spec.state, []types.Model{}, entries)) - - // when - mustSubmitAndExecuteLegacyProposal(t, ctx, spec.srcProposal, otherAddress.String(), keepers) - - // then - cInfo := wasmKeeper.GetContractInfo(ctx, contractAddr) - require.NotNil(t, cInfo) - assert.Equal(t, spec.expAdmin.String(), cInfo.Admin) - }) - } -} - -func TestPinCodesProposal(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, "staking") - wasmKeeper := keepers.WasmKeeper - - mock := wasmtesting.MockWasmer{ - CreateFn: wasmtesting.NoOpCreateFn, - AnalyzeCodeFn: wasmtesting.WithoutIBCAnalyzeFn, - } - var ( - hackatom = StoreHackatomExampleContract(t, ctx, keepers) - hackatomDuplicate = StoreHackatomExampleContract(t, ctx, keepers) - otherContract = StoreRandomContract(t, ctx, keepers, &mock) - gotPinnedChecksums []wasmvm.Checksum - ) - checksumCollector := func(checksum wasmvm.Checksum) error { - gotPinnedChecksums = append(gotPinnedChecksums, checksum) - return nil - } - specs := map[string]struct { - srcCodeIDs []uint64 - mockFn func(checksum wasmvm.Checksum) error - expPinned []wasmvm.Checksum - expErr bool - }{ - "pin one": { - srcCodeIDs: []uint64{hackatom.CodeID}, - mockFn: checksumCollector, - }, - "pin multiple": { - srcCodeIDs: []uint64{hackatom.CodeID, otherContract.CodeID}, - mockFn: checksumCollector, - }, - "pin same code id": { - srcCodeIDs: []uint64{hackatom.CodeID, hackatomDuplicate.CodeID}, - mockFn: checksumCollector, - }, - "pin non existing code id": { - srcCodeIDs: []uint64{999}, - mockFn: checksumCollector, - expErr: true, - }, - "pin empty code id list": { - srcCodeIDs: []uint64{}, - mockFn: checksumCollector, - expErr: true, - }, - "wasmvm failed with error": { - srcCodeIDs: []uint64{hackatom.CodeID}, - mockFn: func(_ wasmvm.Checksum) error { - return errors.New("test, ignore") - }, - expErr: true, - }, - } - parentCtx := ctx - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - myActorAddress := RandomBech32AccountAddress(t) - gotPinnedChecksums = nil - ctx, _ := parentCtx.CacheContext() - mock.PinFn = spec.mockFn - proposal := &types.PinCodesProposal{ //nolint:staticcheck // testing a deprecated library - Title: "Foo", - Description: "Bar", - CodeIDs: spec.srcCodeIDs, - } - - govAuthority := keepers.AccountKeeper.GetModuleAddress(govtypes.ModuleName).String() - msgServer := govkeeper.NewMsgServerImpl(keepers.GovKeeper) - - // when - contentMsg, gotErr := submitLegacyProposal(t, ctx, proposal, myActorAddress, govAuthority, msgServer) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - - // and proposal execute - _, err := msgServer.ExecLegacyContent(sdk.WrapSDKContext(ctx), v1.NewMsgExecLegacyContent(contentMsg.Content, govAuthority)) - require.NoError(t, err) - - // then - for i := range spec.srcCodeIDs { - c := wasmKeeper.GetCodeInfo(ctx, spec.srcCodeIDs[i]) - require.Equal(t, wasmvm.Checksum(c.CodeHash), gotPinnedChecksums[i]) - } - }) - } -} - -func TestUnpinCodesProposal(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, "staking") - wasmKeeper := keepers.WasmKeeper - - mock := wasmtesting.MockWasmer{ - CreateFn: wasmtesting.NoOpCreateFn, - AnalyzeCodeFn: wasmtesting.WithoutIBCAnalyzeFn, - } - var ( - hackatom = StoreHackatomExampleContract(t, ctx, keepers) - hackatomDuplicate = StoreHackatomExampleContract(t, ctx, keepers) - otherContract = StoreRandomContract(t, ctx, keepers, &mock) - gotUnpinnedChecksums []wasmvm.Checksum - ) - checksumCollector := func(checksum wasmvm.Checksum) error { - gotUnpinnedChecksums = append(gotUnpinnedChecksums, checksum) - return nil - } - specs := map[string]struct { - srcCodeIDs []uint64 - mockFn func(checksum wasmvm.Checksum) error - expUnpinned []wasmvm.Checksum - expErr bool - }{ - "unpin one": { - srcCodeIDs: []uint64{hackatom.CodeID}, - mockFn: checksumCollector, - }, - "unpin multiple": { - srcCodeIDs: []uint64{hackatom.CodeID, otherContract.CodeID}, - mockFn: checksumCollector, - }, - "unpin same code id": { - srcCodeIDs: []uint64{hackatom.CodeID, hackatomDuplicate.CodeID}, - mockFn: checksumCollector, - }, - "unpin non existing code id": { - srcCodeIDs: []uint64{999}, - mockFn: checksumCollector, - expErr: true, - }, - "unpin empty code id list": { - srcCodeIDs: []uint64{}, - mockFn: checksumCollector, - expErr: true, - }, - "wasmvm failed with error": { - srcCodeIDs: []uint64{hackatom.CodeID}, - mockFn: func(_ wasmvm.Checksum) error { - return errors.New("test, ignore") - }, - expErr: true, - }, - } - parentCtx := ctx - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - gotUnpinnedChecksums = nil - ctx, _ := parentCtx.CacheContext() - mock.UnpinFn = spec.mockFn - proposal := &types.UnpinCodesProposal{ //nolint:staticcheck // testing a deprecated library - Title: "Foo", - Description: "Bar", - CodeIDs: spec.srcCodeIDs, - } - - govAuthority := keepers.AccountKeeper.GetModuleAddress(govtypes.ModuleName).String() - msgServer := govkeeper.NewMsgServerImpl(keepers.GovKeeper) - - // when - contentMsg, gotErr := submitLegacyProposal(t, ctx, proposal, RandomBech32AccountAddress(t), govAuthority, msgServer) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - - // and proposal execute - _, err := msgServer.ExecLegacyContent(sdk.WrapSDKContext(ctx), v1.NewMsgExecLegacyContent(contentMsg.Content, govAuthority)) - require.NoError(t, err) - - // then - for i := range spec.srcCodeIDs { - c := wasmKeeper.GetCodeInfo(ctx, spec.srcCodeIDs[i]) - require.Equal(t, wasmvm.Checksum(c.CodeHash), gotUnpinnedChecksums[i]) - } - }) - } -} - -func TestUpdateInstantiateConfigProposal(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, "staking") - wasmKeeper := keepers.WasmKeeper - - mock := wasmtesting.MockWasmer{ - CreateFn: wasmtesting.NoOpCreateFn, - AnalyzeCodeFn: wasmtesting.WithoutIBCAnalyzeFn, - } - anyAddress, err := sdk.AccAddressFromBech32("cosmos100dejzacpanrldpjjwksjm62shqhyss44jf5xz") - require.NoError(t, err) - - withAddressAccessConfig := types.AccessTypeAnyOfAddresses.With(anyAddress) - var ( - nobody = StoreRandomContractWithAccessConfig(t, ctx, keepers, &mock, &types.AllowNobody) - everybody = StoreRandomContractWithAccessConfig(t, ctx, keepers, &mock, &types.AllowEverybody) - withAddress = StoreRandomContractWithAccessConfig(t, ctx, keepers, &mock, &withAddressAccessConfig) - ) - - specs := map[string]struct { - accessConfigUpdates []types.AccessConfigUpdate - expErr bool - }{ - "update one": { - accessConfigUpdates: []types.AccessConfigUpdate{ - {CodeID: nobody.CodeID, InstantiatePermission: types.AllowEverybody}, - }, - }, - "update multiple": { - accessConfigUpdates: []types.AccessConfigUpdate{ - {CodeID: everybody.CodeID, InstantiatePermission: types.AllowNobody}, - {CodeID: nobody.CodeID, InstantiatePermission: withAddressAccessConfig}, - {CodeID: withAddress.CodeID, InstantiatePermission: types.AllowEverybody}, - }, - }, - "update same code id": { - accessConfigUpdates: []types.AccessConfigUpdate{ - {CodeID: everybody.CodeID, InstantiatePermission: types.AllowNobody}, - {CodeID: everybody.CodeID, InstantiatePermission: types.AllowEverybody}, - }, - expErr: true, - }, - "update non existing code id": { - accessConfigUpdates: []types.AccessConfigUpdate{ - {CodeID: 100, InstantiatePermission: types.AllowNobody}, - {CodeID: everybody.CodeID, InstantiatePermission: types.AllowEverybody}, - }, - expErr: true, - }, - "update empty list": { - accessConfigUpdates: make([]types.AccessConfigUpdate, 0), - expErr: true, - }, - } - parentCtx := ctx - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - ctx, _ := parentCtx.CacheContext() - - updates := make([]types.AccessConfigUpdate, 0) - for _, cu := range spec.accessConfigUpdates { - updates = append(updates, types.AccessConfigUpdate{ - CodeID: cu.CodeID, - InstantiatePermission: cu.InstantiatePermission, - }) - } - - govAuthority := keepers.AccountKeeper.GetModuleAddress(govtypes.ModuleName).String() - msgServer := govkeeper.NewMsgServerImpl(keepers.GovKeeper) - proposal := &types.UpdateInstantiateConfigProposal{ //nolint:staticcheck // testing a deprecated library - Title: "Foo", - Description: "Bar", - AccessConfigUpdates: updates, - } - - // when - contentMsg, gotErr := submitLegacyProposal(t, ctx, proposal, RandomBech32AccountAddress(t), govAuthority, msgServer) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - - // and proposal execute - _, err := msgServer.ExecLegacyContent(sdk.WrapSDKContext(ctx), v1.NewMsgExecLegacyContent(contentMsg.Content, govAuthority)) - require.NoError(t, err) - - // then - for i := range spec.accessConfigUpdates { - c := wasmKeeper.GetCodeInfo(ctx, spec.accessConfigUpdates[i].CodeID) - require.Equal(t, spec.accessConfigUpdates[i].InstantiatePermission, c.InstantiateConfig) - } - }) - } -} diff --git a/x/wasm/keeper/querier.go b/x/wasm/keeper/querier.go deleted file mode 100644 index ae90461..0000000 --- a/x/wasm/keeper/querier.go +++ /dev/null @@ -1,347 +0,0 @@ -package keeper - -import ( - "context" - "encoding/binary" - "runtime/debug" - - errorsmod "cosmossdk.io/errors" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store/prefix" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/types/query" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -var _ types.QueryServer = &GrpcQuerier{} - -type GrpcQuerier struct { - cdc codec.Codec - storeKey storetypes.StoreKey - keeper types.ViewKeeper - queryGasLimit sdk.Gas -} - -// NewGrpcQuerier constructor -func NewGrpcQuerier(cdc codec.Codec, storeKey storetypes.StoreKey, keeper types.ViewKeeper, queryGasLimit sdk.Gas) *GrpcQuerier { - return &GrpcQuerier{cdc: cdc, storeKey: storeKey, keeper: keeper, queryGasLimit: queryGasLimit} -} - -func (q GrpcQuerier) ContractInfo(c context.Context, req *types.QueryContractInfoRequest) (*types.QueryContractInfoResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - contractAddr, err := sdk.AccAddressFromBech32(req.Address) - if err != nil { - return nil, err - } - rsp, err := queryContractInfo(sdk.UnwrapSDKContext(c), contractAddr, q.keeper) - switch { - case err != nil: - return nil, err - case rsp == nil: - return nil, types.ErrNotFound - } - return rsp, nil -} - -func (q GrpcQuerier) ContractHistory(c context.Context, req *types.QueryContractHistoryRequest) (*types.QueryContractHistoryResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - contractAddr, err := sdk.AccAddressFromBech32(req.Address) - if err != nil { - return nil, err - } - - ctx := sdk.UnwrapSDKContext(c) - r := make([]types.ContractCodeHistoryEntry, 0) - - prefixStore := prefix.NewStore(ctx.KVStore(q.storeKey), types.GetContractCodeHistoryElementPrefix(contractAddr)) - pageRes, err := query.FilteredPaginate(prefixStore, req.Pagination, func(key []byte, value []byte, accumulate bool) (bool, error) { - if accumulate { - var e types.ContractCodeHistoryEntry - if err := q.cdc.Unmarshal(value, &e); err != nil { - return false, err - } - r = append(r, e) - } - return true, nil - }) - if err != nil { - return nil, err - } - return &types.QueryContractHistoryResponse{ - Entries: r, - Pagination: pageRes, - }, nil -} - -// ContractsByCode lists all smart contracts for a code id -func (q GrpcQuerier) ContractsByCode(c context.Context, req *types.QueryContractsByCodeRequest) (*types.QueryContractsByCodeResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - if req.CodeId == 0 { - return nil, errorsmod.Wrap(types.ErrInvalid, "code id") - } - ctx := sdk.UnwrapSDKContext(c) - r := make([]string, 0) - - prefixStore := prefix.NewStore(ctx.KVStore(q.storeKey), types.GetContractByCodeIDSecondaryIndexPrefix(req.CodeId)) - pageRes, err := query.FilteredPaginate(prefixStore, req.Pagination, func(key []byte, value []byte, accumulate bool) (bool, error) { - if accumulate { - var contractAddr sdk.AccAddress = key[types.AbsoluteTxPositionLen:] - r = append(r, contractAddr.String()) - } - return true, nil - }) - if err != nil { - return nil, err - } - return &types.QueryContractsByCodeResponse{ - Contracts: r, - Pagination: pageRes, - }, nil -} - -func (q GrpcQuerier) AllContractState(c context.Context, req *types.QueryAllContractStateRequest) (*types.QueryAllContractStateResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - contractAddr, err := sdk.AccAddressFromBech32(req.Address) - if err != nil { - return nil, err - } - ctx := sdk.UnwrapSDKContext(c) - if !q.keeper.HasContractInfo(ctx, contractAddr) { - return nil, types.ErrNotFound - } - - r := make([]types.Model, 0) - prefixStore := prefix.NewStore(ctx.KVStore(q.storeKey), types.GetContractStorePrefix(contractAddr)) - pageRes, err := query.FilteredPaginate(prefixStore, req.Pagination, func(key []byte, value []byte, accumulate bool) (bool, error) { - if accumulate { - r = append(r, types.Model{ - Key: key, - Value: value, - }) - } - return true, nil - }) - if err != nil { - return nil, err - } - return &types.QueryAllContractStateResponse{ - Models: r, - Pagination: pageRes, - }, nil -} - -func (q GrpcQuerier) RawContractState(c context.Context, req *types.QueryRawContractStateRequest) (*types.QueryRawContractStateResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - ctx := sdk.UnwrapSDKContext(c) - - contractAddr, err := sdk.AccAddressFromBech32(req.Address) - if err != nil { - return nil, err - } - - if !q.keeper.HasContractInfo(ctx, contractAddr) { - return nil, types.ErrNotFound - } - rsp := q.keeper.QueryRaw(ctx, contractAddr, req.QueryData) - return &types.QueryRawContractStateResponse{Data: rsp}, nil -} - -func (q GrpcQuerier) SmartContractState(c context.Context, req *types.QuerySmartContractStateRequest) (rsp *types.QuerySmartContractStateResponse, err error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - if err := req.QueryData.ValidateBasic(); err != nil { - return nil, status.Error(codes.InvalidArgument, "invalid query data") - } - contractAddr, err := sdk.AccAddressFromBech32(req.Address) - if err != nil { - return nil, err - } - ctx := sdk.UnwrapSDKContext(c).WithGasMeter(sdk.NewGasMeter(q.queryGasLimit)) - // recover from out-of-gas panic - defer func() { - if r := recover(); r != nil { - switch rType := r.(type) { - case sdk.ErrorOutOfGas: - err = errorsmod.Wrapf(sdkerrors.ErrOutOfGas, - "out of gas in location: %v; gasWanted: %d, gasUsed: %d", - rType.Descriptor, ctx.GasMeter().Limit(), ctx.GasMeter().GasConsumed(), - ) - default: - err = sdkerrors.ErrPanic - } - rsp = nil - moduleLogger(ctx). - Debug("smart query contract", - "error", "recovering panic", - "contract-address", req.Address, - "stacktrace", string(debug.Stack())) - } - }() - - bz, err := q.keeper.QuerySmart(ctx, contractAddr, req.QueryData) - switch { - case err != nil: - return nil, err - case bz == nil: - return nil, types.ErrNotFound - } - return &types.QuerySmartContractStateResponse{Data: bz}, nil -} - -func (q GrpcQuerier) Code(c context.Context, req *types.QueryCodeRequest) (*types.QueryCodeResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - if req.CodeId == 0 { - return nil, errorsmod.Wrap(types.ErrInvalid, "code id") - } - rsp, err := queryCode(sdk.UnwrapSDKContext(c), req.CodeId, q.keeper) - switch { - case err != nil: - return nil, err - case rsp == nil: - return nil, types.ErrNotFound - } - return &types.QueryCodeResponse{ - CodeInfoResponse: rsp.CodeInfoResponse, - Data: rsp.Data, - }, nil -} - -func (q GrpcQuerier) Codes(c context.Context, req *types.QueryCodesRequest) (*types.QueryCodesResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - ctx := sdk.UnwrapSDKContext(c) - r := make([]types.CodeInfoResponse, 0) - prefixStore := prefix.NewStore(ctx.KVStore(q.storeKey), types.CodeKeyPrefix) - pageRes, err := query.FilteredPaginate(prefixStore, req.Pagination, func(key []byte, value []byte, accumulate bool) (bool, error) { - if accumulate { - var c types.CodeInfo - if err := q.cdc.Unmarshal(value, &c); err != nil { - return false, err - } - r = append(r, types.CodeInfoResponse{ - CodeID: binary.BigEndian.Uint64(key), - Creator: c.Creator, - DataHash: c.CodeHash, - InstantiatePermission: c.InstantiateConfig, - }) - } - return true, nil - }) - if err != nil { - return nil, err - } - return &types.QueryCodesResponse{CodeInfos: r, Pagination: pageRes}, nil -} - -func queryContractInfo(ctx sdk.Context, addr sdk.AccAddress, keeper types.ViewKeeper) (*types.QueryContractInfoResponse, error) { - info := keeper.GetContractInfo(ctx, addr) - if info == nil { - return nil, types.ErrNotFound - } - return &types.QueryContractInfoResponse{ - Address: addr.String(), - ContractInfo: *info, - }, nil -} - -func queryCode(ctx sdk.Context, codeID uint64, keeper types.ViewKeeper) (*types.QueryCodeResponse, error) { - if codeID == 0 { - return nil, nil - } - res := keeper.GetCodeInfo(ctx, codeID) - if res == nil { - // nil, nil leads to 404 in rest handler - return nil, nil - } - info := types.CodeInfoResponse{ - CodeID: codeID, - Creator: res.Creator, - DataHash: res.CodeHash, - InstantiatePermission: res.InstantiateConfig, - } - - code, err := keeper.GetByteCode(ctx, codeID) - if err != nil { - return nil, errorsmod.Wrap(err, "loading wasm code") - } - - return &types.QueryCodeResponse{CodeInfoResponse: &info, Data: code}, nil -} - -func (q GrpcQuerier) PinnedCodes(c context.Context, req *types.QueryPinnedCodesRequest) (*types.QueryPinnedCodesResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - ctx := sdk.UnwrapSDKContext(c) - r := make([]uint64, 0) - - prefixStore := prefix.NewStore(ctx.KVStore(q.storeKey), types.PinnedCodeIndexPrefix) - pageRes, err := query.FilteredPaginate(prefixStore, req.Pagination, func(key []byte, _ []byte, accumulate bool) (bool, error) { - if accumulate { - r = append(r, sdk.BigEndianToUint64(key)) - } - return true, nil - }) - if err != nil { - return nil, err - } - return &types.QueryPinnedCodesResponse{ - CodeIDs: r, - Pagination: pageRes, - }, nil -} - -// Params returns params of the module. -func (q GrpcQuerier) Params(c context.Context, _ *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { - ctx := sdk.UnwrapSDKContext(c) - params := q.keeper.GetParams(ctx) - return &types.QueryParamsResponse{Params: params}, nil -} - -func (q GrpcQuerier) ContractsByCreator(c context.Context, req *types.QueryContractsByCreatorRequest) (*types.QueryContractsByCreatorResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - ctx := sdk.UnwrapSDKContext(c) - contracts := make([]string, 0) - - creatorAddress, err := sdk.AccAddressFromBech32(req.CreatorAddress) - if err != nil { - return nil, err - } - prefixStore := prefix.NewStore(ctx.KVStore(q.storeKey), types.GetContractsByCreatorPrefix(creatorAddress)) - pageRes, err := query.FilteredPaginate(prefixStore, req.Pagination, func(key []byte, _ []byte, accumulate bool) (bool, error) { - if accumulate { - accAddres := sdk.AccAddress(key[types.AbsoluteTxPositionLen:]) - contracts = append(contracts, accAddres.String()) - } - return true, nil - }) - if err != nil { - return nil, err - } - - return &types.QueryContractsByCreatorResponse{ - ContractAddresses: contracts, - Pagination: pageRes, - }, nil -} diff --git a/x/wasm/keeper/querier_test.go b/x/wasm/keeper/querier_test.go deleted file mode 100644 index 31cd190..0000000 --- a/x/wasm/keeper/querier_test.go +++ /dev/null @@ -1,919 +0,0 @@ -package keeper - -import ( - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "os" - "testing" - "time" - - errorsmod "cosmossdk.io/errors" - wasmvm "github.com/CosmWasm/wasmvm" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/cometbft/cometbft/libs/log" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/types/query" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - "github.com/terpnetwork/terp-core/x/wasm/keeper/wasmtesting" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestQueryAllContractState(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.WasmKeeper - - exampleContract := InstantiateHackatomExampleContract(t, ctx, keepers) - contractAddr := exampleContract.Contract - contractModel := []types.Model{ - {Key: []byte{0x0, 0x1}, Value: []byte(`{"count":8}`)}, - {Key: []byte("foo"), Value: []byte(`"bar"`)}, - } - require.NoError(t, keeper.importContractState(ctx, contractAddr, contractModel)) - - q := Querier(keeper) - specs := map[string]struct { - srcQuery *types.QueryAllContractStateRequest - expModelContains []types.Model - expModelContainsNot []types.Model - expErr *errorsmod.Error - }{ - "query all": { - srcQuery: &types.QueryAllContractStateRequest{Address: contractAddr.String()}, - expModelContains: contractModel, - }, - "query all with unknown address": { - srcQuery: &types.QueryAllContractStateRequest{Address: RandomBech32AccountAddress(t)}, - expErr: types.ErrNotFound, - }, - "with pagination offset": { - srcQuery: &types.QueryAllContractStateRequest{ - Address: contractAddr.String(), - Pagination: &query.PageRequest{ - Offset: 1, - }, - }, - expModelContains: []types.Model{ - {Key: []byte("foo"), Value: []byte(`"bar"`)}, - }, - expModelContainsNot: []types.Model{ - {Key: []byte{0x0, 0x1}, Value: []byte(`{"count":8}`)}, - }, - }, - "with pagination limit": { - srcQuery: &types.QueryAllContractStateRequest{ - Address: contractAddr.String(), - Pagination: &query.PageRequest{ - Limit: 1, - }, - }, - expModelContains: []types.Model{ - {Key: []byte{0x0, 0x1}, Value: []byte(`{"count":8}`)}, - }, - expModelContainsNot: []types.Model{ - {Key: []byte("foo"), Value: []byte(`"bar"`)}, - }, - }, - "with pagination next key": { - srcQuery: &types.QueryAllContractStateRequest{ - Address: contractAddr.String(), - Pagination: &query.PageRequest{ - Key: fromBase64("Y29uZmln"), - }, - }, - expModelContains: []types.Model{ - {Key: []byte("foo"), Value: []byte(`"bar"`)}, - }, - expModelContainsNot: []types.Model{ - {Key: []byte{0x0, 0x1}, Value: []byte(`{"count":8}`)}, - }, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - got, err := q.AllContractState(sdk.WrapSDKContext(ctx), spec.srcQuery) - require.True(t, spec.expErr.Is(err), err) - if spec.expErr != nil { - return - } - for _, exp := range spec.expModelContains { - assert.Contains(t, got.Models, exp) - } - for _, exp := range spec.expModelContainsNot { - assert.NotContains(t, got.Models, exp) - } - }) - } -} - -func TestQuerySmartContractState(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.WasmKeeper - - exampleContract := InstantiateHackatomExampleContract(t, ctx, keepers) - contractAddr := exampleContract.Contract.String() - - q := Querier(keeper) - specs := map[string]struct { - srcAddr sdk.AccAddress - srcQuery *types.QuerySmartContractStateRequest - expResp string - expErr error - }{ - "query smart": { - srcQuery: &types.QuerySmartContractStateRequest{Address: contractAddr, QueryData: []byte(`{"verifier":{}}`)}, - expResp: fmt.Sprintf(`{"verifier":"%s"}`, exampleContract.VerifierAddr.String()), - }, - "query smart invalid request": { - srcQuery: &types.QuerySmartContractStateRequest{Address: contractAddr, QueryData: []byte(`{"raw":{"key":"config"}}`)}, - expErr: types.ErrQueryFailed, - }, - "query smart with invalid json": { - srcQuery: &types.QuerySmartContractStateRequest{Address: contractAddr, QueryData: []byte(`not a json string`)}, - expErr: status.Error(codes.InvalidArgument, "invalid query data"), - }, - "query smart with unknown address": { - srcQuery: &types.QuerySmartContractStateRequest{Address: RandomBech32AccountAddress(t), QueryData: []byte(`{"verifier":{}}`)}, - expErr: types.ErrNotFound, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - got, err := q.SmartContractState(sdk.WrapSDKContext(ctx), spec.srcQuery) - require.True(t, errors.Is(err, spec.expErr), "but got %+v", err) - if spec.expErr != nil { - return - } - assert.JSONEq(t, string(got.Data), spec.expResp) - }) - } -} - -func TestQuerySmartContractPanics(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - contractAddr := BuildContractAddressClassic(1, 1) - keepers.WasmKeeper.storeCodeInfo(ctx, 1, types.CodeInfo{}) - keepers.WasmKeeper.storeContractInfo(ctx, contractAddr, &types.ContractInfo{ - CodeID: 1, - Created: types.NewAbsoluteTxPosition(ctx), - }) - ctx = ctx.WithGasMeter(sdk.NewGasMeter(DefaultInstanceCost)).WithLogger(log.TestingLogger()) - - specs := map[string]struct { - doInContract func() - expErr *errorsmod.Error - }{ - "out of gas": { - doInContract: func() { - ctx.GasMeter().ConsumeGas(ctx.GasMeter().Limit()+1, "test - consume more than limit") - }, - expErr: sdkErrors.ErrOutOfGas, - }, - "other panic": { - doInContract: func() { - panic("my panic") - }, - expErr: sdkErrors.ErrPanic, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - keepers.WasmKeeper.wasmVM = &wasmtesting.MockWasmer{QueryFn: func(checksum wasmvm.Checksum, env wasmvmtypes.Env, queryMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) ([]byte, uint64, error) { - spec.doInContract() - return nil, 0, nil - }} - // when - q := Querier(keepers.WasmKeeper) - got, err := q.SmartContractState(sdk.WrapSDKContext(ctx), &types.QuerySmartContractStateRequest{ - Address: contractAddr.String(), - QueryData: types.RawContractMessage("{}"), - }) - require.True(t, spec.expErr.Is(err), "got error: %+v", err) - assert.Nil(t, got) - }) - } -} - -func TestQueryRawContractState(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.WasmKeeper - - exampleContract := InstantiateHackatomExampleContract(t, ctx, keepers) - contractAddr := exampleContract.Contract.String() - contractModel := []types.Model{ - {Key: []byte("foo"), Value: []byte(`"bar"`)}, - {Key: []byte{0x0, 0x1}, Value: []byte(`{"count":8}`)}, - } - require.NoError(t, keeper.importContractState(ctx, exampleContract.Contract, contractModel)) - - q := Querier(keeper) - specs := map[string]struct { - srcQuery *types.QueryRawContractStateRequest - expData []byte - expErr *errorsmod.Error - }{ - "query raw key": { - srcQuery: &types.QueryRawContractStateRequest{Address: contractAddr, QueryData: []byte("foo")}, - expData: []byte(`"bar"`), - }, - "query raw contract binary key": { - srcQuery: &types.QueryRawContractStateRequest{Address: contractAddr, QueryData: []byte{0x0, 0x1}}, - expData: []byte(`{"count":8}`), - }, - "query non-existent raw key": { - srcQuery: &types.QueryRawContractStateRequest{Address: contractAddr, QueryData: []byte("not existing key")}, - expData: nil, - }, - "query empty raw key": { - srcQuery: &types.QueryRawContractStateRequest{Address: contractAddr, QueryData: []byte("")}, - expData: nil, - }, - "query nil raw key": { - srcQuery: &types.QueryRawContractStateRequest{Address: contractAddr}, - expData: nil, - }, - "query raw with unknown address": { - srcQuery: &types.QueryRawContractStateRequest{Address: RandomBech32AccountAddress(t), QueryData: []byte("foo")}, - expErr: types.ErrNotFound, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - got, err := q.RawContractState(sdk.WrapSDKContext(ctx), spec.srcQuery) - require.True(t, spec.expErr.Is(err), err) - if spec.expErr != nil { - return - } - assert.Equal(t, spec.expData, got.Data) - }) - } -} - -func TestQueryContractListByCodeOrdering(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.WasmKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 1000000)) - topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 500)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - anyAddr := keepers.Faucet.NewFundedRandomAccount(ctx, topUp...) - - wasmCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - - codeID, _, err := keepers.ContractKeeper.Create(ctx, creator, wasmCode, nil) - require.NoError(t, err) - - _, bob := keyPubAddr() - initMsg := HackatomExampleInitMsg{ - Verifier: anyAddr, - Beneficiary: bob, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - - // manage some realistic block settings - var h int64 = 10 - setBlock := func(ctx sdk.Context, height int64) sdk.Context { - ctx = ctx.WithBlockHeight(height) - meter := sdk.NewGasMeter(1000000) - ctx = ctx.WithGasMeter(meter) - ctx = ctx.WithBlockGasMeter(meter) - return ctx - } - - // create 10 contracts with real block/gas setup - for i := 0; i < 10; i++ { - // 3 tx per block, so we ensure both comparisons work - if i%3 == 0 { - ctx = setBlock(ctx, h) - h++ - } - _, _, err = keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, initMsgBz, fmt.Sprintf("contract %d", i), topUp) - require.NoError(t, err) - } - - // query and check the results are properly sorted - q := Querier(keeper) - res, err := q.ContractsByCode(sdk.WrapSDKContext(ctx), &types.QueryContractsByCodeRequest{CodeId: codeID}) - require.NoError(t, err) - - require.Equal(t, 10, len(res.Contracts)) - - for _, contractAddr := range res.Contracts { - assert.NotEmpty(t, contractAddr) - } -} - -func TestQueryContractHistory(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.WasmKeeper - - var ( - myContractBech32Addr = RandomBech32AccountAddress(t) - otherBech32Addr = RandomBech32AccountAddress(t) - ) - - specs := map[string]struct { - srcHistory []types.ContractCodeHistoryEntry - req types.QueryContractHistoryRequest - expContent []types.ContractCodeHistoryEntry - }{ - "response with internal fields cleared": { - srcHistory: []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeGenesis, - CodeID: firstCodeID, - Updated: &types.AbsoluteTxPosition{BlockHeight: 1, TxIndex: 2}, - Msg: []byte(`"init message"`), - }}, - req: types.QueryContractHistoryRequest{Address: myContractBech32Addr}, - expContent: []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeGenesis, - CodeID: firstCodeID, - Msg: []byte(`"init message"`), - Updated: &types.AbsoluteTxPosition{BlockHeight: 1, TxIndex: 2}, - }}, - }, - "response with multiple entries": { - srcHistory: []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeInit, - CodeID: firstCodeID, - Updated: &types.AbsoluteTxPosition{BlockHeight: 1, TxIndex: 2}, - Msg: []byte(`"init message"`), - }, { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 2, - Updated: &types.AbsoluteTxPosition{BlockHeight: 3, TxIndex: 4}, - Msg: []byte(`"migrate message 1"`), - }, { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 3, - Updated: &types.AbsoluteTxPosition{BlockHeight: 5, TxIndex: 6}, - Msg: []byte(`"migrate message 2"`), - }}, - req: types.QueryContractHistoryRequest{Address: myContractBech32Addr}, - expContent: []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeInit, - CodeID: firstCodeID, - Msg: []byte(`"init message"`), - Updated: &types.AbsoluteTxPosition{BlockHeight: 1, TxIndex: 2}, - }, { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 2, - Msg: []byte(`"migrate message 1"`), - Updated: &types.AbsoluteTxPosition{BlockHeight: 3, TxIndex: 4}, - }, { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 3, - Msg: []byte(`"migrate message 2"`), - Updated: &types.AbsoluteTxPosition{BlockHeight: 5, TxIndex: 6}, - }}, - }, - "with pagination offset": { - srcHistory: []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeInit, - CodeID: firstCodeID, - Updated: &types.AbsoluteTxPosition{BlockHeight: 1, TxIndex: 2}, - Msg: []byte(`"init message"`), - }, { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 2, - Updated: &types.AbsoluteTxPosition{BlockHeight: 3, TxIndex: 4}, - Msg: []byte(`"migrate message 1"`), - }}, - req: types.QueryContractHistoryRequest{ - Address: myContractBech32Addr, - Pagination: &query.PageRequest{ - Offset: 1, - }, - }, - expContent: []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 2, - Msg: []byte(`"migrate message 1"`), - Updated: &types.AbsoluteTxPosition{BlockHeight: 3, TxIndex: 4}, - }}, - }, - "with pagination limit": { - srcHistory: []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeInit, - CodeID: firstCodeID, - Updated: &types.AbsoluteTxPosition{BlockHeight: 1, TxIndex: 2}, - Msg: []byte(`"init message"`), - }, { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 2, - Updated: &types.AbsoluteTxPosition{BlockHeight: 3, TxIndex: 4}, - Msg: []byte(`"migrate message 1"`), - }}, - req: types.QueryContractHistoryRequest{ - Address: myContractBech32Addr, - Pagination: &query.PageRequest{ - Limit: 1, - }, - }, - expContent: []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeInit, - CodeID: firstCodeID, - Msg: []byte(`"init message"`), - Updated: &types.AbsoluteTxPosition{BlockHeight: 1, TxIndex: 2}, - }}, - }, - "unknown contract address": { - req: types.QueryContractHistoryRequest{Address: otherBech32Addr}, - srcHistory: []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeGenesis, - CodeID: firstCodeID, - Updated: types.NewAbsoluteTxPosition(ctx), - Msg: []byte(`"init message"`), - }}, - expContent: nil, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - xCtx, _ := ctx.CacheContext() - - cAddr, _ := sdk.AccAddressFromBech32(myContractBech32Addr) - keeper.appendToContractHistory(xCtx, cAddr, spec.srcHistory...) - - // when - q := Querier(keeper) - got, err := q.ContractHistory(sdk.WrapSDKContext(xCtx), &spec.req) - - // then - if spec.expContent == nil { - require.Error(t, types.ErrEmpty) - return - } - require.NoError(t, err) - assert.Equal(t, spec.expContent, got.Entries) - }) - } -} - -func TestQueryCodeList(t *testing.T) { - wasmCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.WasmKeeper - - specs := map[string]struct { - storedCodeIDs []uint64 - req types.QueryCodesRequest - expCodeIDs []uint64 - }{ - "none": {}, - "no gaps": { - storedCodeIDs: []uint64{1, 2, 3}, - expCodeIDs: []uint64{1, 2, 3}, - }, - "with gaps": { - storedCodeIDs: []uint64{2, 4, 6}, - expCodeIDs: []uint64{2, 4, 6}, - }, - "with pagination offset": { - storedCodeIDs: []uint64{1, 2, 3}, - req: types.QueryCodesRequest{ - Pagination: &query.PageRequest{ - Offset: 1, - }, - }, - expCodeIDs: []uint64{2, 3}, - }, - "with pagination limit": { - storedCodeIDs: []uint64{1, 2, 3}, - req: types.QueryCodesRequest{ - Pagination: &query.PageRequest{ - Limit: 2, - }, - }, - expCodeIDs: []uint64{1, 2}, - }, - "with pagination next key": { - storedCodeIDs: []uint64{1, 2, 3}, - req: types.QueryCodesRequest{ - Pagination: &query.PageRequest{ - Key: fromBase64("AAAAAAAAAAI="), - }, - }, - expCodeIDs: []uint64{2, 3}, - }, - } - - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - xCtx, _ := ctx.CacheContext() - - for _, codeID := range spec.storedCodeIDs { - require.NoError(t, keeper.importCode(xCtx, codeID, - types.CodeInfoFixture(types.WithSHA256CodeHash(wasmCode)), - wasmCode), - ) - } - // when - q := Querier(keeper) - got, err := q.Codes(sdk.WrapSDKContext(xCtx), &spec.req) - - // then - require.NoError(t, err) - require.NotNil(t, got.CodeInfos) - require.Len(t, got.CodeInfos, len(spec.expCodeIDs)) - for i, exp := range spec.expCodeIDs { - assert.EqualValues(t, exp, got.CodeInfos[i].CodeID) - } - }) - } -} - -func TestQueryContractInfo(t *testing.T) { - var ( - contractAddr = RandomAccountAddress(t) - anyDate = time.Now().UTC() - ) - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - // register an example extension. must be protobuf - keepers.EncodingConfig.InterfaceRegistry.RegisterImplementations( - (*types.ContractInfoExtension)(nil), - &govv1beta1.Proposal{}, - ) - govv1beta1.RegisterInterfaces(keepers.EncodingConfig.InterfaceRegistry) - - k := keepers.WasmKeeper - querier := NewGrpcQuerier(k.cdc, k.storeKey, k, k.queryGasLimit) - myExtension := func(info *types.ContractInfo) { - // abuse gov proposal as a random protobuf extension with an Any type - myExt, err := govv1beta1.NewProposal(&govv1beta1.TextProposal{Title: "foo", Description: "bar"}, 1, anyDate, anyDate) - require.NoError(t, err) - myExt.TotalDeposit = nil - err = info.SetExtension(&myExt) - require.NoError(t, err) - } - specs := map[string]struct { - src *types.QueryContractInfoRequest - stored types.ContractInfo - expRsp *types.QueryContractInfoResponse - expErr bool - }{ - "found": { - src: &types.QueryContractInfoRequest{Address: contractAddr.String()}, - stored: types.ContractInfoFixture(), - expRsp: &types.QueryContractInfoResponse{ - Address: contractAddr.String(), - ContractInfo: types.ContractInfoFixture(), - }, - }, - "with extension": { - src: &types.QueryContractInfoRequest{Address: contractAddr.String()}, - stored: types.ContractInfoFixture(myExtension), - expRsp: &types.QueryContractInfoResponse{ - Address: contractAddr.String(), - ContractInfo: types.ContractInfoFixture(myExtension), - }, - }, - "not found": { - src: &types.QueryContractInfoRequest{Address: RandomBech32AccountAddress(t)}, - stored: types.ContractInfoFixture(), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - xCtx, _ := ctx.CacheContext() - k.storeContractInfo(xCtx, contractAddr, &spec.stored) - // when - gotRsp, gotErr := querier.ContractInfo(sdk.WrapSDKContext(xCtx), spec.src) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - assert.Equal(t, spec.expRsp, gotRsp) - }) - } -} - -func TestQueryPinnedCodes(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.WasmKeeper - - exampleContract1 := InstantiateHackatomExampleContract(t, ctx, keepers) - exampleContract2 := InstantiateIBCReflectContract(t, ctx, keepers) - require.NoError(t, keeper.pinCode(ctx, exampleContract1.CodeID)) - require.NoError(t, keeper.pinCode(ctx, exampleContract2.CodeID)) - - q := Querier(keeper) - specs := map[string]struct { - srcQuery *types.QueryPinnedCodesRequest - expCodeIDs []uint64 - expErr *errorsmod.Error - }{ - "query all": { - srcQuery: &types.QueryPinnedCodesRequest{}, - expCodeIDs: []uint64{exampleContract1.CodeID, exampleContract2.CodeID}, - }, - "with pagination offset": { - srcQuery: &types.QueryPinnedCodesRequest{ - Pagination: &query.PageRequest{ - Offset: 1, - }, - }, - expCodeIDs: []uint64{exampleContract2.CodeID}, - }, - "with pagination limit": { - srcQuery: &types.QueryPinnedCodesRequest{ - Pagination: &query.PageRequest{ - Limit: 1, - }, - }, - expCodeIDs: []uint64{exampleContract1.CodeID}, - }, - "with pagination next key": { - srcQuery: &types.QueryPinnedCodesRequest{ - Pagination: &query.PageRequest{ - Key: fromBase64("AAAAAAAAAAM="), - }, - }, - expCodeIDs: []uint64{exampleContract2.CodeID}, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - got, err := q.PinnedCodes(sdk.WrapSDKContext(ctx), spec.srcQuery) - require.True(t, spec.expErr.Is(err), err) - if spec.expErr != nil { - return - } - require.NotNil(t, got) - assert.Equal(t, spec.expCodeIDs, got.CodeIDs) - }) - } -} - -func TestQueryParams(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.WasmKeeper - - q := Querier(keeper) - - paramsResponse, err := q.Params(sdk.WrapSDKContext(ctx), &types.QueryParamsRequest{}) - require.NoError(t, err) - require.NotNil(t, paramsResponse) - - defaultParams := types.DefaultParams() - - require.Equal(t, paramsResponse.Params.CodeUploadAccess, defaultParams.CodeUploadAccess) - require.Equal(t, paramsResponse.Params.InstantiateDefaultPermission, defaultParams.InstantiateDefaultPermission) - - err = keeper.SetParams(ctx, types.Params{ - CodeUploadAccess: types.AllowNobody, - InstantiateDefaultPermission: types.AccessTypeNobody, - }) - require.NoError(t, err) - - paramsResponse, err = q.Params(sdk.WrapSDKContext(ctx), &types.QueryParamsRequest{}) - require.NoError(t, err) - require.NotNil(t, paramsResponse) - - require.Equal(t, paramsResponse.Params.CodeUploadAccess, types.AllowNobody) - require.Equal(t, paramsResponse.Params.InstantiateDefaultPermission, types.AccessTypeNobody) -} - -func TestQueryCodeInfo(t *testing.T) { - wasmCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.WasmKeeper - - anyAddress, err := sdk.AccAddressFromBech32("cosmos100dejzacpanrldpjjwksjm62shqhyss44jf5xz") - require.NoError(t, err) - specs := map[string]struct { - codeID uint64 - accessConfig types.AccessConfig - }{ - "everybody": { - codeID: 1, - accessConfig: types.AllowEverybody, - }, - "nobody": { - codeID: 10, - accessConfig: types.AllowNobody, - }, - "with_address": { - codeID: 20, - accessConfig: types.AccessTypeOnlyAddress.With(anyAddress), - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - codeInfo := types.CodeInfoFixture(types.WithSHA256CodeHash(wasmCode)) - codeInfo.InstantiateConfig = spec.accessConfig - require.NoError(t, keeper.importCode(ctx, spec.codeID, - codeInfo, - wasmCode), - ) - - q := Querier(keeper) - got, err := q.Code(sdk.WrapSDKContext(ctx), &types.QueryCodeRequest{ - CodeId: spec.codeID, - }) - require.NoError(t, err) - expectedResponse := &types.QueryCodeResponse{ - CodeInfoResponse: &types.CodeInfoResponse{ - CodeID: spec.codeID, - Creator: codeInfo.Creator, - DataHash: codeInfo.CodeHash, - InstantiatePermission: spec.accessConfig, - }, - Data: wasmCode, - } - require.NotNil(t, got.CodeInfoResponse) - require.EqualValues(t, expectedResponse, got) - }) - } -} - -func TestQueryCodeInfoList(t *testing.T) { - wasmCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.WasmKeeper - - anyAddress, err := sdk.AccAddressFromBech32("cosmos100dejzacpanrldpjjwksjm62shqhyss44jf5xz") - require.NoError(t, err) - codeInfoWithConfig := func(accessConfig types.AccessConfig) types.CodeInfo { - codeInfo := types.CodeInfoFixture(types.WithSHA256CodeHash(wasmCode)) - codeInfo.InstantiateConfig = accessConfig - return codeInfo - } - - codes := []struct { - name string - codeID uint64 - codeInfo types.CodeInfo - }{ - { - name: "everybody", - codeID: 1, - codeInfo: codeInfoWithConfig(types.AllowEverybody), - }, - { - codeID: 10, - name: "nobody", - codeInfo: codeInfoWithConfig(types.AllowNobody), - }, - { - name: "with_address", - codeID: 20, - codeInfo: codeInfoWithConfig(types.AccessTypeOnlyAddress.With(anyAddress)), - }, - } - - allCodesResponse := make([]types.CodeInfoResponse, 0) - for _, code := range codes { - t.Run(fmt.Sprintf("import_%s", code.name), func(t *testing.T) { - require.NoError(t, keeper.importCode(ctx, code.codeID, - code.codeInfo, - wasmCode), - ) - }) - - allCodesResponse = append(allCodesResponse, types.CodeInfoResponse{ - CodeID: code.codeID, - Creator: code.codeInfo.Creator, - DataHash: code.codeInfo.CodeHash, - InstantiatePermission: code.codeInfo.InstantiateConfig, - }) - } - q := Querier(keeper) - got, err := q.Codes(sdk.WrapSDKContext(ctx), &types.QueryCodesRequest{ - Pagination: &query.PageRequest{ - Limit: 3, - }, - }) - require.NoError(t, err) - require.Len(t, got.CodeInfos, 3) - require.EqualValues(t, allCodesResponse, got.CodeInfos) -} - -func TestQueryContractsByCreatorList(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 1000000)) - topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 500)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - anyAddr := keepers.Faucet.NewFundedRandomAccount(ctx, topUp...) - - wasmCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - - codeID, _, err := keepers.ContractKeeper.Create(ctx, creator, wasmCode, nil) - require.NoError(t, err) - - _, bob := keyPubAddr() - initMsg := HackatomExampleInitMsg{ - Verifier: anyAddr, - Beneficiary: bob, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - - // manage some realistic block settings - var h int64 = 10 - setBlock := func(ctx sdk.Context, height int64) sdk.Context { - ctx = ctx.WithBlockHeight(height) - meter := sdk.NewGasMeter(1000000) - ctx = ctx.WithGasMeter(meter) - ctx = ctx.WithBlockGasMeter(meter) - return ctx - } - - var allExpecedContracts []string - // create 10 contracts with real block/gas setup - for i := 0; i < 10; i++ { - ctx = setBlock(ctx, h) - h++ - contract, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, initMsgBz, fmt.Sprintf("contract %d", i), topUp) - allExpecedContracts = append(allExpecedContracts, contract.String()) - require.NoError(t, err) - } - - specs := map[string]struct { - srcQuery *types.QueryContractsByCreatorRequest - expContractAddr []string - expErr error - }{ - "query all": { - srcQuery: &types.QueryContractsByCreatorRequest{ - CreatorAddress: creator.String(), - }, - expContractAddr: allExpecedContracts, - expErr: nil, - }, - "with pagination offset": { - srcQuery: &types.QueryContractsByCreatorRequest{ - CreatorAddress: creator.String(), - Pagination: &query.PageRequest{ - Offset: 1, - }, - }, - expContractAddr: allExpecedContracts[1:], - expErr: nil, - }, - "with pagination limit": { - srcQuery: &types.QueryContractsByCreatorRequest{ - CreatorAddress: creator.String(), - Pagination: &query.PageRequest{ - Limit: 1, - }, - }, - expContractAddr: allExpecedContracts[0:1], - expErr: nil, - }, - "nil creator": { - srcQuery: &types.QueryContractsByCreatorRequest{ - Pagination: &query.PageRequest{}, - }, - expContractAddr: allExpecedContracts, - expErr: errors.New("empty address string is not allowed"), - }, - "nil req": { - srcQuery: nil, - expContractAddr: allExpecedContracts, - expErr: status.Error(codes.InvalidArgument, "empty request"), - }, - } - - q := Querier(keepers.WasmKeeper) - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - got, err := q.ContractsByCreator(sdk.WrapSDKContext(ctx), spec.srcQuery) - - if spec.expErr != nil { - require.Equal(t, spec.expErr, err) - return - } - require.NoError(t, err) - require.NotNil(t, got) - assert.Equal(t, spec.expContractAddr, got.ContractAddresses) - }) - } -} - -func fromBase64(s string) []byte { - r, err := base64.StdEncoding.DecodeString(s) - if err != nil { - panic(err) - } - return r -} diff --git a/x/wasm/keeper/query_plugins.go b/x/wasm/keeper/query_plugins.go deleted file mode 100644 index b85c582..0000000 --- a/x/wasm/keeper/query_plugins.go +++ /dev/null @@ -1,614 +0,0 @@ -package keeper - -import ( - "encoding/json" - "errors" - "fmt" - - errorsmod "cosmossdk.io/errors" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -type QueryHandler struct { - Ctx sdk.Context - Plugins WasmVMQueryHandler - Caller sdk.AccAddress - gasRegister GasRegister -} - -func NewQueryHandler(ctx sdk.Context, vmQueryHandler WasmVMQueryHandler, caller sdk.AccAddress, gasRegister GasRegister) QueryHandler { - return QueryHandler{ - Ctx: ctx, - Plugins: vmQueryHandler, - Caller: caller, - gasRegister: gasRegister, - } -} - -type GRPCQueryRouter interface { - Route(path string) baseapp.GRPCQueryHandler -} - -// -- end baseapp interfaces -- - -var _ wasmvmtypes.Querier = QueryHandler{} - -func (q QueryHandler) Query(request wasmvmtypes.QueryRequest, gasLimit uint64) ([]byte, error) { - // set a limit for a subCtx - sdkGas := q.gasRegister.FromWasmVMGas(gasLimit) - // discard all changes/ events in subCtx by not committing the cached context - subCtx, _ := q.Ctx.WithGasMeter(sdk.NewGasMeter(sdkGas)).CacheContext() - - // make sure we charge the higher level context even on panic - defer func() { - q.Ctx.GasMeter().ConsumeGas(subCtx.GasMeter().GasConsumed(), "contract sub-query") - }() - - res, err := q.Plugins.HandleQuery(subCtx, q.Caller, request) - if err == nil { - // short-circuit, the rest is dealing with handling existing errors - return res, nil - } - - // special mappings to wasmvm system error (which are not redacted) - var wasmvmErr types.WasmVMErrorable - if ok := errors.As(err, &wasmvmErr); ok { - err = wasmvmErr.ToWasmVMError() - } - - // Issue #759 - we don't return error string for worries of non-determinism - return nil, redactError(err) -} - -func (q QueryHandler) GasConsumed() uint64 { - return q.Ctx.GasMeter().GasConsumed() -} - -type CustomQuerier func(ctx sdk.Context, request json.RawMessage) ([]byte, error) - -type QueryPlugins struct { - Bank func(ctx sdk.Context, request *wasmvmtypes.BankQuery) ([]byte, error) - Custom CustomQuerier - IBC func(ctx sdk.Context, caller sdk.AccAddress, request *wasmvmtypes.IBCQuery) ([]byte, error) - Staking func(ctx sdk.Context, request *wasmvmtypes.StakingQuery) ([]byte, error) - Stargate func(ctx sdk.Context, request *wasmvmtypes.StargateQuery) ([]byte, error) - Wasm func(ctx sdk.Context, request *wasmvmtypes.WasmQuery) ([]byte, error) -} - -type contractMetaDataSource interface { - GetContractInfo(ctx sdk.Context, contractAddress sdk.AccAddress) *types.ContractInfo -} - -type wasmQueryKeeper interface { - contractMetaDataSource - GetCodeInfo(ctx sdk.Context, codeID uint64) *types.CodeInfo - QueryRaw(ctx sdk.Context, contractAddress sdk.AccAddress, key []byte) []byte - QuerySmart(ctx sdk.Context, contractAddr sdk.AccAddress, req []byte) ([]byte, error) - IsPinnedCode(ctx sdk.Context, codeID uint64) bool -} - -func DefaultQueryPlugins( - bank types.BankViewKeeper, - staking types.StakingKeeper, - distKeeper types.DistributionKeeper, - channelKeeper types.ChannelKeeper, - wasm wasmQueryKeeper, -) QueryPlugins { - return QueryPlugins{ - Bank: BankQuerier(bank), - Custom: NoCustomQuerier, - IBC: IBCQuerier(wasm, channelKeeper), - Staking: StakingQuerier(staking, distKeeper), - Stargate: RejectStargateQuerier(), - Wasm: WasmQuerier(wasm), - } -} - -func (e QueryPlugins) Merge(o *QueryPlugins) QueryPlugins { - // only update if this is non-nil and then only set values - if o == nil { - return e - } - if o.Bank != nil { - e.Bank = o.Bank - } - if o.Custom != nil { - e.Custom = o.Custom - } - if o.IBC != nil { - e.IBC = o.IBC - } - if o.Staking != nil { - e.Staking = o.Staking - } - if o.Stargate != nil { - e.Stargate = o.Stargate - } - if o.Wasm != nil { - e.Wasm = o.Wasm - } - return e -} - -// HandleQuery executes the requested query -func (e QueryPlugins) HandleQuery(ctx sdk.Context, caller sdk.AccAddress, request wasmvmtypes.QueryRequest) ([]byte, error) { - // do the query - if request.Bank != nil { - return e.Bank(ctx, request.Bank) - } - if request.Custom != nil { - return e.Custom(ctx, request.Custom) - } - if request.IBC != nil { - return e.IBC(ctx, caller, request.IBC) - } - if request.Staking != nil { - return e.Staking(ctx, request.Staking) - } - if request.Stargate != nil { - return e.Stargate(ctx, request.Stargate) - } - if request.Wasm != nil { - return e.Wasm(ctx, request.Wasm) - } - return nil, wasmvmtypes.Unknown{} -} - -func BankQuerier(bankKeeper types.BankViewKeeper) func(ctx sdk.Context, request *wasmvmtypes.BankQuery) ([]byte, error) { - return func(ctx sdk.Context, request *wasmvmtypes.BankQuery) ([]byte, error) { - if request.AllBalances != nil { - addr, err := sdk.AccAddressFromBech32(request.AllBalances.Address) - if err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, request.AllBalances.Address) - } - coins := bankKeeper.GetAllBalances(ctx, addr) - res := wasmvmtypes.AllBalancesResponse{ - Amount: ConvertSdkCoinsToWasmCoins(coins), - } - return json.Marshal(res) - } - if request.Balance != nil { - addr, err := sdk.AccAddressFromBech32(request.Balance.Address) - if err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, request.Balance.Address) - } - coin := bankKeeper.GetBalance(ctx, addr, request.Balance.Denom) - res := wasmvmtypes.BalanceResponse{ - Amount: wasmvmtypes.Coin{ - Denom: coin.Denom, - Amount: coin.Amount.String(), - }, - } - return json.Marshal(res) - } - if request.Supply != nil { - coin := bankKeeper.GetSupply(ctx, request.Supply.Denom) - res := wasmvmtypes.SupplyResponse{ - Amount: wasmvmtypes.Coin{ - Denom: coin.Denom, - Amount: coin.Amount.String(), - }, - } - return json.Marshal(res) - } - return nil, wasmvmtypes.UnsupportedRequest{Kind: "unknown BankQuery variant"} - } -} - -func NoCustomQuerier(sdk.Context, json.RawMessage) ([]byte, error) { - return nil, wasmvmtypes.UnsupportedRequest{Kind: "custom"} -} - -func IBCQuerier(wasm contractMetaDataSource, channelKeeper types.ChannelKeeper) func(ctx sdk.Context, caller sdk.AccAddress, request *wasmvmtypes.IBCQuery) ([]byte, error) { - return func(ctx sdk.Context, caller sdk.AccAddress, request *wasmvmtypes.IBCQuery) ([]byte, error) { - if request.PortID != nil { - contractInfo := wasm.GetContractInfo(ctx, caller) - res := wasmvmtypes.PortIDResponse{ - PortID: contractInfo.IBCPortID, - } - return json.Marshal(res) - } - if request.ListChannels != nil { - portID := request.ListChannels.PortID - channels := make(wasmvmtypes.IBCChannels, 0) - channelKeeper.IterateChannels(ctx, func(ch channeltypes.IdentifiedChannel) bool { - // it must match the port and be in open state - if (portID == "" || portID == ch.PortId) && ch.State == channeltypes.OPEN { - newChan := wasmvmtypes.IBCChannel{ - Endpoint: wasmvmtypes.IBCEndpoint{ - PortID: ch.PortId, - ChannelID: ch.ChannelId, - }, - CounterpartyEndpoint: wasmvmtypes.IBCEndpoint{ - PortID: ch.Counterparty.PortId, - ChannelID: ch.Counterparty.ChannelId, - }, - Order: ch.Ordering.String(), - Version: ch.Version, - ConnectionID: ch.ConnectionHops[0], - } - channels = append(channels, newChan) - } - return false - }) - res := wasmvmtypes.ListChannelsResponse{ - Channels: channels, - } - return json.Marshal(res) - } - if request.Channel != nil { - channelID := request.Channel.ChannelID - portID := request.Channel.PortID - if portID == "" { - contractInfo := wasm.GetContractInfo(ctx, caller) - portID = contractInfo.IBCPortID - } - got, found := channelKeeper.GetChannel(ctx, portID, channelID) - var channel *wasmvmtypes.IBCChannel - // it must be in open state - if found && got.State == channeltypes.OPEN { - channel = &wasmvmtypes.IBCChannel{ - Endpoint: wasmvmtypes.IBCEndpoint{ - PortID: portID, - ChannelID: channelID, - }, - CounterpartyEndpoint: wasmvmtypes.IBCEndpoint{ - PortID: got.Counterparty.PortId, - ChannelID: got.Counterparty.ChannelId, - }, - Order: got.Ordering.String(), - Version: got.Version, - ConnectionID: got.ConnectionHops[0], - } - } - res := wasmvmtypes.ChannelResponse{ - Channel: channel, - } - return json.Marshal(res) - } - return nil, wasmvmtypes.UnsupportedRequest{Kind: "unknown IBCQuery variant"} - } -} - -// RejectStargateQuerier rejects all stargate queries -func RejectStargateQuerier() func(ctx sdk.Context, request *wasmvmtypes.StargateQuery) ([]byte, error) { - return func(ctx sdk.Context, request *wasmvmtypes.StargateQuery) ([]byte, error) { - return nil, wasmvmtypes.UnsupportedRequest{Kind: "Stargate queries are disabled"} - } -} - -// AcceptedStargateQueries define accepted Stargate queries as a map with path as key and response type as value. -// For example: -// acceptList["/cosmos.auth.v1beta1.Query/Account"]= &authtypes.QueryAccountResponse{} -type AcceptedStargateQueries map[string]codec.ProtoMarshaler - -// AcceptListStargateQuerier supports a preconfigured set of stargate queries only. -// All arguments must be non nil. -// -// Warning: Chains need to test and maintain their accept list carefully. -// There were critical consensus breaking issues in the past with non-deterministic behaviour in the SDK. -// -// This queries can be set via WithQueryPlugins option in the wasm keeper constructor: -// WithQueryPlugins(&QueryPlugins{Stargate: AcceptListStargateQuerier(acceptList, queryRouter, codec)}) -func AcceptListStargateQuerier(acceptList AcceptedStargateQueries, queryRouter GRPCQueryRouter, codec codec.Codec) func(ctx sdk.Context, request *wasmvmtypes.StargateQuery) ([]byte, error) { - return func(ctx sdk.Context, request *wasmvmtypes.StargateQuery) ([]byte, error) { - protoResponse, accepted := acceptList[request.Path] - if !accepted { - return nil, wasmvmtypes.UnsupportedRequest{Kind: fmt.Sprintf("'%s' path is not allowed from the contract", request.Path)} - } - - route := queryRouter.Route(request.Path) - if route == nil { - return nil, wasmvmtypes.UnsupportedRequest{Kind: fmt.Sprintf("No route to query '%s'", request.Path)} - } - - res, err := route(ctx, abci.RequestQuery{ - Data: request.Data, - Path: request.Path, - }) - if err != nil { - return nil, err - } - - return ConvertProtoToJSONMarshal(codec, protoResponse, res.Value) - } -} - -func StakingQuerier(keeper types.StakingKeeper, distKeeper types.DistributionKeeper) func(ctx sdk.Context, request *wasmvmtypes.StakingQuery) ([]byte, error) { - return func(ctx sdk.Context, request *wasmvmtypes.StakingQuery) ([]byte, error) { - if request.BondedDenom != nil { - denom := keeper.BondDenom(ctx) - res := wasmvmtypes.BondedDenomResponse{ - Denom: denom, - } - return json.Marshal(res) - } - if request.AllValidators != nil { - validators := keeper.GetBondedValidatorsByPower(ctx) - // validators := keeper.GetAllValidators(ctx) - wasmVals := make([]wasmvmtypes.Validator, len(validators)) - for i, v := range validators { - wasmVals[i] = wasmvmtypes.Validator{ - Address: v.OperatorAddress, - Commission: v.Commission.Rate.String(), - MaxCommission: v.Commission.MaxRate.String(), - MaxChangeRate: v.Commission.MaxChangeRate.String(), - } - } - res := wasmvmtypes.AllValidatorsResponse{ - Validators: wasmVals, - } - return json.Marshal(res) - } - if request.Validator != nil { - valAddr, err := sdk.ValAddressFromBech32(request.Validator.Address) - if err != nil { - return nil, err - } - v, found := keeper.GetValidator(ctx, valAddr) - res := wasmvmtypes.ValidatorResponse{} - if found { - res.Validator = &wasmvmtypes.Validator{ - Address: v.OperatorAddress, - Commission: v.Commission.Rate.String(), - MaxCommission: v.Commission.MaxRate.String(), - MaxChangeRate: v.Commission.MaxChangeRate.String(), - } - } - return json.Marshal(res) - } - if request.AllDelegations != nil { - delegator, err := sdk.AccAddressFromBech32(request.AllDelegations.Delegator) - if err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, request.AllDelegations.Delegator) - } - sdkDels := keeper.GetAllDelegatorDelegations(ctx, delegator) - delegations, err := sdkToDelegations(ctx, keeper, sdkDels) - if err != nil { - return nil, err - } - res := wasmvmtypes.AllDelegationsResponse{ - Delegations: delegations, - } - return json.Marshal(res) - } - if request.Delegation != nil { - delegator, err := sdk.AccAddressFromBech32(request.Delegation.Delegator) - if err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, request.Delegation.Delegator) - } - validator, err := sdk.ValAddressFromBech32(request.Delegation.Validator) - if err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, request.Delegation.Validator) - } - - var res wasmvmtypes.DelegationResponse - d, found := keeper.GetDelegation(ctx, delegator, validator) - if found { - res.Delegation, err = sdkToFullDelegation(ctx, keeper, distKeeper, d) - if err != nil { - return nil, err - } - } - return json.Marshal(res) - } - return nil, wasmvmtypes.UnsupportedRequest{Kind: "unknown Staking variant"} - } -} - -func sdkToDelegations(ctx sdk.Context, keeper types.StakingKeeper, delegations []stakingtypes.Delegation) (wasmvmtypes.Delegations, error) { - result := make([]wasmvmtypes.Delegation, len(delegations)) - bondDenom := keeper.BondDenom(ctx) - - for i, d := range delegations { - delAddr, err := sdk.AccAddressFromBech32(d.DelegatorAddress) - if err != nil { - return nil, errorsmod.Wrap(err, "delegator address") - } - valAddr, err := sdk.ValAddressFromBech32(d.ValidatorAddress) - if err != nil { - return nil, errorsmod.Wrap(err, "validator address") - } - - // shares to amount logic comes from here: - // https://github.com/cosmos/cosmos-sdk/blob/v0.38.3/x/staking/keeper/querier.go#L404 - val, found := keeper.GetValidator(ctx, valAddr) - if !found { - return nil, errorsmod.Wrap(stakingtypes.ErrNoValidatorFound, "can't load validator for delegation") - } - amount := sdk.NewCoin(bondDenom, val.TokensFromShares(d.Shares).TruncateInt()) - - result[i] = wasmvmtypes.Delegation{ - Delegator: delAddr.String(), - Validator: valAddr.String(), - Amount: ConvertSdkCoinToWasmCoin(amount), - } - } - return result, nil -} - -func sdkToFullDelegation(ctx sdk.Context, keeper types.StakingKeeper, distKeeper types.DistributionKeeper, delegation stakingtypes.Delegation) (*wasmvmtypes.FullDelegation, error) { - delAddr, err := sdk.AccAddressFromBech32(delegation.DelegatorAddress) - if err != nil { - return nil, errorsmod.Wrap(err, "delegator address") - } - valAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress) - if err != nil { - return nil, errorsmod.Wrap(err, "validator address") - } - val, found := keeper.GetValidator(ctx, valAddr) - if !found { - return nil, errorsmod.Wrap(stakingtypes.ErrNoValidatorFound, "can't load validator for delegation") - } - bondDenom := keeper.BondDenom(ctx) - amount := sdk.NewCoin(bondDenom, val.TokensFromShares(delegation.Shares).TruncateInt()) - - delegationCoins := ConvertSdkCoinToWasmCoin(amount) - - // FIXME: this is very rough but better than nothing... - // https://github.com/CosmWasm/wasmd/issues/282 - // if this (val, delegate) pair is receiving a redelegation, it cannot redelegate more - // otherwise, it can redelegate the full amount - // (there are cases of partial funds redelegated, but this is a start) - redelegateCoins := wasmvmtypes.NewCoin(0, bondDenom) - if !keeper.HasReceivingRedelegation(ctx, delAddr, valAddr) { - redelegateCoins = delegationCoins - } - - // FIXME: make a cleaner way to do this (modify the sdk) - // we need the info from `distKeeper.calculateDelegationRewards()`, but it is not public - // neither is `queryDelegationRewards(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper)` - // so we go through the front door of the querier.... - accRewards, err := getAccumulatedRewards(ctx, distKeeper, delegation) - if err != nil { - return nil, err - } - - return &wasmvmtypes.FullDelegation{ - Delegator: delAddr.String(), - Validator: valAddr.String(), - Amount: delegationCoins, - AccumulatedRewards: accRewards, - CanRedelegate: redelegateCoins, - }, nil -} - -// FIXME: simplify this enormously when -// https://github.com/cosmos/cosmos-sdk/issues/7466 is merged -func getAccumulatedRewards(ctx sdk.Context, distKeeper types.DistributionKeeper, delegation stakingtypes.Delegation) ([]wasmvmtypes.Coin, error) { - // Try to get *delegator* reward info! - params := distributiontypes.QueryDelegationRewardsRequest{ - DelegatorAddress: delegation.DelegatorAddress, - ValidatorAddress: delegation.ValidatorAddress, - } - cache, _ := ctx.CacheContext() - qres, err := distKeeper.DelegationRewards(sdk.WrapSDKContext(cache), ¶ms) - if err != nil { - return nil, err - } - - // now we have it, convert it into wasmvm types - rewards := make([]wasmvmtypes.Coin, len(qres.Rewards)) - for i, r := range qres.Rewards { - rewards[i] = wasmvmtypes.Coin{ - Denom: r.Denom, - Amount: r.Amount.TruncateInt().String(), - } - } - return rewards, nil -} - -func WasmQuerier(k wasmQueryKeeper) func(ctx sdk.Context, request *wasmvmtypes.WasmQuery) ([]byte, error) { - return func(ctx sdk.Context, request *wasmvmtypes.WasmQuery) ([]byte, error) { - switch { - case request.Smart != nil: - addr, err := sdk.AccAddressFromBech32(request.Smart.ContractAddr) - if err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, request.Smart.ContractAddr) - } - msg := types.RawContractMessage(request.Smart.Msg) - if err := msg.ValidateBasic(); err != nil { - return nil, errorsmod.Wrap(err, "json msg") - } - return k.QuerySmart(ctx, addr, msg) - case request.Raw != nil: - addr, err := sdk.AccAddressFromBech32(request.Raw.ContractAddr) - if err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, request.Raw.ContractAddr) - } - return k.QueryRaw(ctx, addr, request.Raw.Key), nil - case request.ContractInfo != nil: - contractAddr := request.ContractInfo.ContractAddr - addr, err := sdk.AccAddressFromBech32(contractAddr) - if err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, contractAddr) - } - info := k.GetContractInfo(ctx, addr) - if info == nil { - return nil, types.ErrNoSuchContractFn(contractAddr). - Wrapf("address %s", contractAddr) - } - res := wasmvmtypes.ContractInfoResponse{ - CodeID: info.CodeID, - Creator: info.Creator, - Admin: info.Admin, - Pinned: k.IsPinnedCode(ctx, info.CodeID), - IBCPort: info.IBCPortID, - } - return json.Marshal(res) - case request.CodeInfo != nil: - if request.CodeInfo.CodeID == 0 { - return nil, types.ErrEmpty.Wrap("code id") - } - info := k.GetCodeInfo(ctx, request.CodeInfo.CodeID) - if info == nil { - return nil, types.ErrNoSuchCodeFn(request.CodeInfo.CodeID). - Wrapf("code id %d", request.CodeInfo.CodeID) - } - - res := wasmvmtypes.CodeInfoResponse{ - CodeID: request.CodeInfo.CodeID, - Creator: info.Creator, - Checksum: info.CodeHash, - } - return json.Marshal(res) - } - return nil, wasmvmtypes.UnsupportedRequest{Kind: "unknown WasmQuery variant"} - } -} - -// ConvertSdkCoinsToWasmCoins covert sdk type to wasmvm coins type -func ConvertSdkCoinsToWasmCoins(coins []sdk.Coin) wasmvmtypes.Coins { - converted := make(wasmvmtypes.Coins, len(coins)) - for i, c := range coins { - converted[i] = ConvertSdkCoinToWasmCoin(c) - } - return converted -} - -// ConvertSdkCoinToWasmCoin covert sdk type to wasmvm coin type -func ConvertSdkCoinToWasmCoin(coin sdk.Coin) wasmvmtypes.Coin { - return wasmvmtypes.Coin{ - Denom: coin.Denom, - Amount: coin.Amount.String(), - } -} - -// ConvertProtoToJSONMarshal unmarshals the given bytes into a proto message and then marshals it to json. -// This is done so that clients calling stargate queries do not need to define their own proto unmarshalers, -// being able to use response directly by json marshalling, which is supported in cosmwasm. -func ConvertProtoToJSONMarshal(cdc codec.Codec, protoResponse codec.ProtoMarshaler, bz []byte) ([]byte, error) { - // unmarshal binary into stargate response data structure - err := cdc.Unmarshal(bz, protoResponse) - if err != nil { - return nil, errorsmod.Wrap(err, "to proto") - } - - bz, err = cdc.MarshalJSON(protoResponse) - if err != nil { - return nil, errorsmod.Wrap(err, "to json") - } - - protoResponse.Reset() - return bz, nil -} - -var _ WasmVMQueryHandler = WasmVMQueryHandlerFn(nil) - -// WasmVMQueryHandlerFn is a helper to construct a function based query handler. -type WasmVMQueryHandlerFn func(ctx sdk.Context, caller sdk.AccAddress, request wasmvmtypes.QueryRequest) ([]byte, error) - -// HandleQuery delegates call into wrapped WasmVMQueryHandlerFn -func (w WasmVMQueryHandlerFn) HandleQuery(ctx sdk.Context, caller sdk.AccAddress, request wasmvmtypes.QueryRequest) ([]byte, error) { - return w(ctx, caller, request) -} diff --git a/x/wasm/keeper/query_plugins_test.go b/x/wasm/keeper/query_plugins_test.go deleted file mode 100644 index f90b926..0000000 --- a/x/wasm/keeper/query_plugins_test.go +++ /dev/null @@ -1,851 +0,0 @@ -package keeper_test - -import ( - "encoding/hex" - "encoding/json" - "fmt" - "testing" - "time" - - errorsmod "cosmossdk.io/errors" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - dbm "github.com/cometbft/cometbft-db" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - "github.com/cosmos/cosmos-sdk/store" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/query" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/cosmos/gogoproto/proto" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/app" - "github.com/terpnetwork/terp-core/x/wasm/keeper" - "github.com/terpnetwork/terp-core/x/wasm/keeper/wasmtesting" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestIBCQuerier(t *testing.T) { - myExampleChannels := []channeltypes.IdentifiedChannel{ - // this is returned - { - State: channeltypes.OPEN, - Ordering: channeltypes.ORDERED, - Counterparty: channeltypes.Counterparty{ - PortId: "counterPartyPortID", - ChannelId: "counterPartyChannelID", - }, - ConnectionHops: []string{"one"}, - Version: "v1", - PortId: "myPortID", - ChannelId: "myChannelID", - }, - // this is filtered out - { - State: channeltypes.INIT, - Ordering: channeltypes.UNORDERED, - Counterparty: channeltypes.Counterparty{ - PortId: "foobar", - }, - ConnectionHops: []string{"one"}, - Version: "initversion", - PortId: "initPortID", - ChannelId: "initChannelID", - }, - // this is returned - { - State: channeltypes.OPEN, - Ordering: channeltypes.UNORDERED, - Counterparty: channeltypes.Counterparty{ - PortId: "otherCounterPartyPortID", - ChannelId: "otherCounterPartyChannelID", - }, - ConnectionHops: []string{"other", "second"}, - Version: "otherVersion", - PortId: "otherPortID", - ChannelId: "otherChannelID", - }, - // this is filtered out - { - State: channeltypes.CLOSED, - Ordering: channeltypes.ORDERED, - Counterparty: channeltypes.Counterparty{ - PortId: "super", - ChannelId: "duper", - }, - ConnectionHops: []string{"no-more"}, - Version: "closedVersion", - PortId: "closedPortID", - ChannelId: "closedChannelID", - }, - } - specs := map[string]struct { - srcQuery *wasmvmtypes.IBCQuery - wasmKeeper *mockWasmQueryKeeper - channelKeeper *wasmtesting.MockChannelKeeper - expJSONResult string - expErr *errorsmod.Error - }{ - "query port id": { - srcQuery: &wasmvmtypes.IBCQuery{ - PortID: &wasmvmtypes.PortIDQuery{}, - }, - wasmKeeper: &mockWasmQueryKeeper{ - GetContractInfoFn: func(ctx sdk.Context, contractAddress sdk.AccAddress) *types.ContractInfo { - return &types.ContractInfo{IBCPortID: "myIBCPortID"} - }, - }, - channelKeeper: &wasmtesting.MockChannelKeeper{}, - expJSONResult: `{"port_id":"myIBCPortID"}`, - }, - "query list channels - all": { - srcQuery: &wasmvmtypes.IBCQuery{ - ListChannels: &wasmvmtypes.ListChannelsQuery{}, - }, - channelKeeper: &wasmtesting.MockChannelKeeper{ - IterateChannelsFn: wasmtesting.MockChannelKeeperIterator(myExampleChannels), - }, - expJSONResult: `{ - "channels": [ - { - "endpoint": { - "port_id": "myPortID", - "channel_id": "myChannelID" - }, - "counterparty_endpoint": { - "port_id": "counterPartyPortID", - "channel_id": "counterPartyChannelID" - }, - "order": "ORDER_ORDERED", - "version": "v1", - "connection_id": "one" - }, - { - "endpoint": { - "port_id": "otherPortID", - "channel_id": "otherChannelID" - }, - "counterparty_endpoint": { - "port_id": "otherCounterPartyPortID", - "channel_id": "otherCounterPartyChannelID" - }, - "order": "ORDER_UNORDERED", - "version": "otherVersion", - "connection_id": "other" - } - ] -}`, - }, - "query list channels - filtered": { - srcQuery: &wasmvmtypes.IBCQuery{ - ListChannels: &wasmvmtypes.ListChannelsQuery{ - PortID: "otherPortID", - }, - }, - channelKeeper: &wasmtesting.MockChannelKeeper{ - IterateChannelsFn: wasmtesting.MockChannelKeeperIterator(myExampleChannels), - }, - expJSONResult: `{ - "channels": [ - { - "endpoint": { - "port_id": "otherPortID", - "channel_id": "otherChannelID" - }, - "counterparty_endpoint": { - "port_id": "otherCounterPartyPortID", - "channel_id": "otherCounterPartyChannelID" - }, - "order": "ORDER_UNORDERED", - "version": "otherVersion", - "connection_id": "other" - } - ] -}`, - }, - "query list channels - filtered empty": { - srcQuery: &wasmvmtypes.IBCQuery{ - ListChannels: &wasmvmtypes.ListChannelsQuery{ - PortID: "none-existing", - }, - }, - channelKeeper: &wasmtesting.MockChannelKeeper{ - IterateChannelsFn: wasmtesting.MockChannelKeeperIterator(myExampleChannels), - }, - expJSONResult: `{"channels": []}`, - }, - "query channel": { - srcQuery: &wasmvmtypes.IBCQuery{ - Channel: &wasmvmtypes.ChannelQuery{ - PortID: "myQueryPortID", - ChannelID: "myQueryChannelID", - }, - }, - channelKeeper: &wasmtesting.MockChannelKeeper{ - GetChannelFn: func(ctx sdk.Context, srcPort, srcChan string) (channel channeltypes.Channel, found bool) { - return channeltypes.Channel{ - State: channeltypes.OPEN, - Ordering: channeltypes.UNORDERED, - Counterparty: channeltypes.Counterparty{ - PortId: "counterPartyPortID", - ChannelId: "otherCounterPartyChannelID", - }, - ConnectionHops: []string{"one"}, - Version: "version", - }, true - }, - }, - expJSONResult: `{ - "channel": { - "endpoint": { - "port_id": "myQueryPortID", - "channel_id": "myQueryChannelID" - }, - "counterparty_endpoint": { - "port_id": "counterPartyPortID", - "channel_id": "otherCounterPartyChannelID" - }, - "order": "ORDER_UNORDERED", - "version": "version", - "connection_id": "one" - } -}`, - }, - "query channel - without port set": { - srcQuery: &wasmvmtypes.IBCQuery{ - Channel: &wasmvmtypes.ChannelQuery{ - ChannelID: "myQueryChannelID", - }, - }, - wasmKeeper: &mockWasmQueryKeeper{ - GetContractInfoFn: func(ctx sdk.Context, contractAddress sdk.AccAddress) *types.ContractInfo { - return &types.ContractInfo{IBCPortID: "myLoadedPortID"} - }, - }, - channelKeeper: &wasmtesting.MockChannelKeeper{ - GetChannelFn: func(ctx sdk.Context, srcPort, srcChan string) (channel channeltypes.Channel, found bool) { - return channeltypes.Channel{ - State: channeltypes.OPEN, - Ordering: channeltypes.UNORDERED, - Counterparty: channeltypes.Counterparty{ - PortId: "counterPartyPortID", - ChannelId: "otherCounterPartyChannelID", - }, - ConnectionHops: []string{"one"}, - Version: "version", - }, true - }, - }, - expJSONResult: `{ - "channel": { - "endpoint": { - "port_id": "myLoadedPortID", - "channel_id": "myQueryChannelID" - }, - "counterparty_endpoint": { - "port_id": "counterPartyPortID", - "channel_id": "otherCounterPartyChannelID" - }, - "order": "ORDER_UNORDERED", - "version": "version", - "connection_id": "one" - } -}`, - }, - "query channel in init state": { - srcQuery: &wasmvmtypes.IBCQuery{ - Channel: &wasmvmtypes.ChannelQuery{ - PortID: "myQueryPortID", - ChannelID: "myQueryChannelID", - }, - }, - channelKeeper: &wasmtesting.MockChannelKeeper{ - GetChannelFn: func(ctx sdk.Context, srcPort, srcChan string) (channel channeltypes.Channel, found bool) { - return channeltypes.Channel{ - State: channeltypes.INIT, - Ordering: channeltypes.UNORDERED, - Counterparty: channeltypes.Counterparty{ - PortId: "foobar", - }, - ConnectionHops: []string{"one"}, - Version: "initversion", - }, true - }, - }, - expJSONResult: "{}", - }, - "query channel in closed state": { - srcQuery: &wasmvmtypes.IBCQuery{ - Channel: &wasmvmtypes.ChannelQuery{ - PortID: "myQueryPortID", - ChannelID: "myQueryChannelID", - }, - }, - channelKeeper: &wasmtesting.MockChannelKeeper{ - GetChannelFn: func(ctx sdk.Context, srcPort, srcChan string) (channel channeltypes.Channel, found bool) { - return channeltypes.Channel{ - State: channeltypes.CLOSED, - Ordering: channeltypes.ORDERED, - Counterparty: channeltypes.Counterparty{ - PortId: "super", - ChannelId: "duper", - }, - ConnectionHops: []string{"no-more"}, - Version: "closedVersion", - }, true - }, - }, - expJSONResult: "{}", - }, - "query channel - empty result": { - srcQuery: &wasmvmtypes.IBCQuery{ - Channel: &wasmvmtypes.ChannelQuery{ - PortID: "myQueryPortID", - ChannelID: "myQueryChannelID", - }, - }, - channelKeeper: &wasmtesting.MockChannelKeeper{ - GetChannelFn: func(ctx sdk.Context, srcPort, srcChan string) (channel channeltypes.Channel, found bool) { - return channeltypes.Channel{}, false - }, - }, - expJSONResult: "{}", - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - h := keeper.IBCQuerier(spec.wasmKeeper, spec.channelKeeper) - gotResult, gotErr := h(sdk.Context{}, keeper.RandomAccountAddress(t), spec.srcQuery) - require.True(t, spec.expErr.Is(gotErr), "exp %v but got %#+v", spec.expErr, gotErr) - if spec.expErr != nil { - return - } - assert.JSONEq(t, spec.expJSONResult, string(gotResult), string(gotResult)) - }) - } -} - -func TestBankQuerierBalance(t *testing.T) { - mock := bankKeeperMock{GetBalanceFn: func(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin { - return sdk.NewCoin(denom, sdk.NewInt(1)) - }} - - ctx := sdk.Context{} - q := keeper.BankQuerier(mock) - gotBz, gotErr := q(ctx, &wasmvmtypes.BankQuery{ - Balance: &wasmvmtypes.BalanceQuery{ - Address: keeper.RandomBech32AccountAddress(t), - Denom: "ALX", - }, - }) - require.NoError(t, gotErr) - var got wasmvmtypes.BalanceResponse - require.NoError(t, json.Unmarshal(gotBz, &got)) - exp := wasmvmtypes.BalanceResponse{ - Amount: wasmvmtypes.Coin{ - Denom: "ALX", - Amount: "1", - }, - } - assert.Equal(t, exp, got) -} - -func TestContractInfoWasmQuerier(t *testing.T) { - myValidContractAddr := keeper.RandomBech32AccountAddress(t) - myCreatorAddr := keeper.RandomBech32AccountAddress(t) - myAdminAddr := keeper.RandomBech32AccountAddress(t) - var ctx sdk.Context - - specs := map[string]struct { - req *wasmvmtypes.WasmQuery - mock mockWasmQueryKeeper - expRes wasmvmtypes.ContractInfoResponse - expErr bool - }{ - "all good": { - req: &wasmvmtypes.WasmQuery{ - ContractInfo: &wasmvmtypes.ContractInfoQuery{ContractAddr: myValidContractAddr}, - }, - mock: mockWasmQueryKeeper{ - GetContractInfoFn: func(ctx sdk.Context, contractAddress sdk.AccAddress) *types.ContractInfo { - val := types.ContractInfoFixture(func(i *types.ContractInfo) { - i.Admin, i.Creator, i.IBCPortID = myAdminAddr, myCreatorAddr, "myIBCPort" - }) - return &val - }, - IsPinnedCodeFn: func(ctx sdk.Context, codeID uint64) bool { return true }, - }, - expRes: wasmvmtypes.ContractInfoResponse{ - CodeID: 1, - Creator: myCreatorAddr, - Admin: myAdminAddr, - Pinned: true, - IBCPort: "myIBCPort", - }, - }, - "invalid addr": { - req: &wasmvmtypes.WasmQuery{ - ContractInfo: &wasmvmtypes.ContractInfoQuery{ContractAddr: "not a valid addr"}, - }, - expErr: true, - }, - "unknown addr": { - req: &wasmvmtypes.WasmQuery{ - ContractInfo: &wasmvmtypes.ContractInfoQuery{ContractAddr: myValidContractAddr}, - }, - mock: mockWasmQueryKeeper{GetContractInfoFn: func(ctx sdk.Context, contractAddress sdk.AccAddress) *types.ContractInfo { - return nil - }}, - expErr: true, - }, - "not pinned": { - req: &wasmvmtypes.WasmQuery{ - ContractInfo: &wasmvmtypes.ContractInfoQuery{ContractAddr: myValidContractAddr}, - }, - mock: mockWasmQueryKeeper{ - GetContractInfoFn: func(ctx sdk.Context, contractAddress sdk.AccAddress) *types.ContractInfo { - val := types.ContractInfoFixture(func(i *types.ContractInfo) { - i.Admin, i.Creator = myAdminAddr, myCreatorAddr - }) - return &val - }, - IsPinnedCodeFn: func(ctx sdk.Context, codeID uint64) bool { return false }, - }, - expRes: wasmvmtypes.ContractInfoResponse{ - CodeID: 1, - Creator: myCreatorAddr, - Admin: myAdminAddr, - Pinned: false, - }, - }, - "without admin": { - req: &wasmvmtypes.WasmQuery{ - ContractInfo: &wasmvmtypes.ContractInfoQuery{ContractAddr: myValidContractAddr}, - }, - mock: mockWasmQueryKeeper{ - GetContractInfoFn: func(ctx sdk.Context, contractAddress sdk.AccAddress) *types.ContractInfo { - val := types.ContractInfoFixture(func(i *types.ContractInfo) { - i.Creator = myCreatorAddr - }) - return &val - }, - IsPinnedCodeFn: func(ctx sdk.Context, codeID uint64) bool { return true }, - }, - expRes: wasmvmtypes.ContractInfoResponse{ - CodeID: 1, - Creator: myCreatorAddr, - Pinned: true, - }, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - q := keeper.WasmQuerier(spec.mock) - gotBz, gotErr := q(ctx, spec.req) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - var gotRes wasmvmtypes.ContractInfoResponse - require.NoError(t, json.Unmarshal(gotBz, &gotRes)) - assert.Equal(t, spec.expRes, gotRes) - }) - } -} - -func TestCodeInfoWasmQuerier(t *testing.T) { - myCreatorAddr := keeper.RandomBech32AccountAddress(t) - var ctx sdk.Context - - myRawChecksum := []byte("myHash78901234567890123456789012") - specs := map[string]struct { - req *wasmvmtypes.WasmQuery - mock mockWasmQueryKeeper - expRes wasmvmtypes.CodeInfoResponse - expErr bool - }{ - "all good": { - req: &wasmvmtypes.WasmQuery{ - CodeInfo: &wasmvmtypes.CodeInfoQuery{CodeID: 1}, - }, - mock: mockWasmQueryKeeper{ - GetCodeInfoFn: func(ctx sdk.Context, codeID uint64) *types.CodeInfo { - return &types.CodeInfo{ - CodeHash: myRawChecksum, - Creator: myCreatorAddr, - InstantiateConfig: types.AccessConfig{ - Permission: types.AccessTypeNobody, - Addresses: []string{myCreatorAddr}, - }, - } - }, - }, - expRes: wasmvmtypes.CodeInfoResponse{ - CodeID: 1, - Creator: myCreatorAddr, - Checksum: myRawChecksum, - }, - }, - "empty code id": { - req: &wasmvmtypes.WasmQuery{ - CodeInfo: &wasmvmtypes.CodeInfoQuery{}, - }, - expErr: true, - }, - "unknown code id": { - req: &wasmvmtypes.WasmQuery{ - CodeInfo: &wasmvmtypes.CodeInfoQuery{CodeID: 1}, - }, - mock: mockWasmQueryKeeper{ - GetCodeInfoFn: func(ctx sdk.Context, codeID uint64) *types.CodeInfo { - return nil - }, - }, - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - q := keeper.WasmQuerier(spec.mock) - gotBz, gotErr := q(ctx, spec.req) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - var gotRes wasmvmtypes.CodeInfoResponse - require.NoError(t, json.Unmarshal(gotBz, &gotRes), string(gotBz)) - assert.Equal(t, spec.expRes, gotRes) - }) - } -} - -func TestQueryErrors(t *testing.T) { - specs := map[string]struct { - src error - expErr error - }{ - "no error": {}, - "no such contract": { - src: types.ErrNoSuchContractFn("contract-addr"), - expErr: wasmvmtypes.NoSuchContract{Addr: "contract-addr"}, - }, - "no such contract - wrapped": { - src: errorsmod.Wrap(types.ErrNoSuchContractFn("contract-addr"), "my additional data"), - expErr: wasmvmtypes.NoSuchContract{Addr: "contract-addr"}, - }, - "no such code": { - src: types.ErrNoSuchCodeFn(123), - expErr: wasmvmtypes.NoSuchCode{CodeID: 123}, - }, - "no such code - wrapped": { - src: errorsmod.Wrap(types.ErrNoSuchCodeFn(123), "my additional data"), - expErr: wasmvmtypes.NoSuchCode{CodeID: 123}, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - mock := keeper.WasmVMQueryHandlerFn(func(ctx sdk.Context, caller sdk.AccAddress, request wasmvmtypes.QueryRequest) ([]byte, error) { - return nil, spec.src - }) - ctx := sdk.Context{}.WithGasMeter(sdk.NewInfiniteGasMeter()).WithMultiStore(store.NewCommitMultiStore(dbm.NewMemDB())) - q := keeper.NewQueryHandler(ctx, mock, sdk.AccAddress{}, keeper.NewDefaultWasmGasRegister()) - _, gotErr := q.Query(wasmvmtypes.QueryRequest{}, 1) - assert.Equal(t, spec.expErr, gotErr) - }) - } -} - -func TestAcceptListStargateQuerier(t *testing.T) { - wasmApp := app.SetupWithEmptyStore(t) - ctx := wasmApp.NewUncachedContext(false, tmproto.Header{ChainID: "foo", Height: 1, Time: time.Now()}) - err := wasmApp.StakingKeeper.SetParams(ctx, stakingtypes.DefaultParams()) - require.NoError(t, err) - - addrs := app.AddTestAddrsIncremental(wasmApp, ctx, 2, sdk.NewInt(1_000_000)) - accepted := keeper.AcceptedStargateQueries{ - "/cosmos.auth.v1beta1.Query/Account": &authtypes.QueryAccountResponse{}, - "/no/route/to/this": &authtypes.QueryAccountResponse{}, - } - - marshal := func(pb proto.Message) []byte { - b, err := proto.Marshal(pb) - require.NoError(t, err) - return b - } - - specs := map[string]struct { - req *wasmvmtypes.StargateQuery - expErr bool - expResp string - }{ - "in accept list - success result": { - req: &wasmvmtypes.StargateQuery{ - Path: "/cosmos.auth.v1beta1.Query/Account", - Data: marshal(&authtypes.QueryAccountRequest{Address: addrs[0].String()}), - }, - expResp: fmt.Sprintf(`{"account":{"@type":"/cosmos.auth.v1beta1.BaseAccount","address":%q,"pub_key":null,"account_number":"1","sequence":"0"}}`, addrs[0].String()), - }, - "in accept list - error result": { - req: &wasmvmtypes.StargateQuery{ - Path: "/cosmos.auth.v1beta1.Query/Account", - Data: marshal(&authtypes.QueryAccountRequest{Address: sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address()).String()}), - }, - expErr: true, - }, - "not in accept list": { - req: &wasmvmtypes.StargateQuery{ - Path: "/cosmos.bank.v1beta1.Query/AllBalances", - Data: marshal(&banktypes.QueryAllBalancesRequest{Address: addrs[0].String()}), - }, - expErr: true, - }, - "unknown route": { - req: &wasmvmtypes.StargateQuery{ - Path: "/no/route/to/this", - Data: marshal(&banktypes.QueryAllBalancesRequest{Address: addrs[0].String()}), - }, - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - q := keeper.AcceptListStargateQuerier(accepted, wasmApp.GRPCQueryRouter(), wasmApp.AppCodec()) - gotBz, gotErr := q(ctx, spec.req) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - assert.JSONEq(t, spec.expResp, string(gotBz), string(gotBz)) - }) - } -} - -type mockWasmQueryKeeper struct { - GetContractInfoFn func(ctx sdk.Context, contractAddress sdk.AccAddress) *types.ContractInfo - QueryRawFn func(ctx sdk.Context, contractAddress sdk.AccAddress, key []byte) []byte - QuerySmartFn func(ctx sdk.Context, contractAddr sdk.AccAddress, req types.RawContractMessage) ([]byte, error) - IsPinnedCodeFn func(ctx sdk.Context, codeID uint64) bool - GetCodeInfoFn func(ctx sdk.Context, codeID uint64) *types.CodeInfo -} - -func (m mockWasmQueryKeeper) GetContractInfo(ctx sdk.Context, contractAddress sdk.AccAddress) *types.ContractInfo { - if m.GetContractInfoFn == nil { - panic("not expected to be called") - } - return m.GetContractInfoFn(ctx, contractAddress) -} - -func (m mockWasmQueryKeeper) QueryRaw(ctx sdk.Context, contractAddress sdk.AccAddress, key []byte) []byte { - if m.QueryRawFn == nil { - panic("not expected to be called") - } - return m.QueryRawFn(ctx, contractAddress, key) -} - -func (m mockWasmQueryKeeper) QuerySmart(ctx sdk.Context, contractAddr sdk.AccAddress, req []byte) ([]byte, error) { - if m.QuerySmartFn == nil { - panic("not expected to be called") - } - return m.QuerySmartFn(ctx, contractAddr, req) -} - -func (m mockWasmQueryKeeper) IsPinnedCode(ctx sdk.Context, codeID uint64) bool { - if m.IsPinnedCodeFn == nil { - panic("not expected to be called") - } - return m.IsPinnedCodeFn(ctx, codeID) -} - -func (m mockWasmQueryKeeper) GetCodeInfo(ctx sdk.Context, codeID uint64) *types.CodeInfo { - if m.GetCodeInfoFn == nil { - panic("not expected to be called") - } - return m.GetCodeInfoFn(ctx, codeID) -} - -type bankKeeperMock struct { - GetSupplyFn func(ctx sdk.Context, denom string) sdk.Coin - GetBalanceFn func(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin - GetAllBalancesFn func(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins -} - -func (m bankKeeperMock) GetSupply(ctx sdk.Context, denom string) sdk.Coin { - if m.GetSupplyFn == nil { - panic("not expected to be called") - } - return m.GetSupplyFn(ctx, denom) -} - -func (m bankKeeperMock) GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin { - if m.GetBalanceFn == nil { - panic("not expected to be called") - } - return m.GetBalanceFn(ctx, addr, denom) -} - -func (m bankKeeperMock) GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins { - if m.GetAllBalancesFn == nil { - panic("not expected to be called") - } - return m.GetAllBalancesFn(ctx, addr) -} - -func TestConvertProtoToJSONMarshal(t *testing.T) { - testCases := []struct { - name string - queryPath string - protoResponseStruct codec.ProtoMarshaler - originalResponse string - expectedProtoResponse codec.ProtoMarshaler - expectedError bool - }{ - { - name: "successful conversion from proto response to json marshalled response", - queryPath: "/cosmos.bank.v1beta1.Query/AllBalances", - originalResponse: "0a090a036261721202333012050a03666f6f", - protoResponseStruct: &banktypes.QueryAllBalancesResponse{}, - expectedProtoResponse: &banktypes.QueryAllBalancesResponse{ - Balances: sdk.NewCoins(sdk.NewCoin("bar", sdk.NewInt(30))), - Pagination: &query.PageResponse{ - NextKey: []byte("foo"), - }, - }, - }, - { - name: "invalid proto response struct", - queryPath: "/cosmos.bank.v1beta1.Query/AllBalances", - originalResponse: "0a090a036261721202333012050a03666f6f", - protoResponseStruct: &authtypes.QueryAccountResponse{}, - expectedError: true, - }, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("Case %s", tc.name), func(t *testing.T) { - originalVersionBz, err := hex.DecodeString(tc.originalResponse) - require.NoError(t, err) - appCodec := app.MakeEncodingConfig().Marshaler - - jsonMarshalledResponse, err := keeper.ConvertProtoToJSONMarshal(appCodec, tc.protoResponseStruct, originalVersionBz) - if tc.expectedError { - require.Error(t, err) - return - } - require.NoError(t, err) - - // check response by json marshalling proto response into json response manually - jsonMarshalExpectedResponse, err := appCodec.MarshalJSON(tc.expectedProtoResponse) - require.NoError(t, err) - require.JSONEq(t, string(jsonMarshalledResponse), string(jsonMarshalExpectedResponse)) - }) - } -} - -func TestResetProtoMarshalerAfterJsonMarshal(t *testing.T) { - appCodec := app.MakeEncodingConfig().Marshaler - - protoMarshaler := &banktypes.QueryAllBalancesResponse{} - expected := appCodec.MustMarshalJSON(&banktypes.QueryAllBalancesResponse{ - Balances: sdk.NewCoins(sdk.NewCoin("bar", sdk.NewInt(30))), - Pagination: &query.PageResponse{ - NextKey: []byte("foo"), - }, - }) - - bz, err := hex.DecodeString("0a090a036261721202333012050a03666f6f") - require.NoError(t, err) - - // first marshal - response, err := keeper.ConvertProtoToJSONMarshal(appCodec, protoMarshaler, bz) - require.NoError(t, err) - require.Equal(t, expected, response) - - // second marshal - response, err = keeper.ConvertProtoToJSONMarshal(appCodec, protoMarshaler, bz) - require.NoError(t, err) - require.Equal(t, expected, response) -} - -// TestDeterministicJsonMarshal tests that we get deterministic JSON marshalled response upon -// proto struct update in the state machine. -func TestDeterministicJsonMarshal(t *testing.T) { - testCases := []struct { - name string - originalResponse string - updatedResponse string - queryPath string - responseProtoStruct codec.ProtoMarshaler - expectedProto func() codec.ProtoMarshaler - }{ - /** - * - * Origin Response - * 0a530a202f636f736d6f732e617574682e763162657461312e426173654163636f756e74122f0a2d636f736d6f7331346c3268686a6e676c3939367772703935673867646a6871653038326375367a7732706c686b - * - * Updated Response - * 0a530a202f636f736d6f732e617574682e763162657461312e426173654163636f756e74122f0a2d636f736d6f7331646a783375676866736d6b6135386676673076616a6e6533766c72776b7a6a346e6377747271122d636f736d6f7331646a783375676866736d6b6135386676673076616a6e6533766c72776b7a6a346e6377747271 - // Origin proto - message QueryAccountResponse { - // account defines the account of the corresponding address. - google.protobuf.Any account = 1 [(cosmos_proto.accepts_interface) = "AccountI"]; - } - // Updated proto - message QueryAccountResponse { - // account defines the account of the corresponding address. - google.protobuf.Any account = 1 [(cosmos_proto.accepts_interface) = "AccountI"]; - // address is the address to query for. - string address = 2; - } - */ - { - "Query Account", - "0a530a202f636f736d6f732e617574682e763162657461312e426173654163636f756e74122f0a2d636f736d6f733166387578756c746e3873717a687a6e72737a3371373778776171756867727367366a79766679", - "0a530a202f636f736d6f732e617574682e763162657461312e426173654163636f756e74122f0a2d636f736d6f733166387578756c746e3873717a687a6e72737a3371373778776171756867727367366a79766679122d636f736d6f733166387578756c746e3873717a687a6e72737a3371373778776171756867727367366a79766679", - "/cosmos.auth.v1beta1.Query/Account", - &authtypes.QueryAccountResponse{}, - func() codec.ProtoMarshaler { - account := authtypes.BaseAccount{ - Address: "cosmos1f8uxultn8sqzhznrsz3q77xwaquhgrsg6jyvfy", - } - accountResponse, err := codectypes.NewAnyWithValue(&account) - require.NoError(t, err) - return &authtypes.QueryAccountResponse{ - Account: accountResponse, - } - }, - }, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("Case %s", tc.name), func(t *testing.T) { - appCodec := app.MakeEncodingConfig().Marshaler - - originVersionBz, err := hex.DecodeString(tc.originalResponse) - require.NoError(t, err) - jsonMarshalledOriginalBz, err := keeper.ConvertProtoToJSONMarshal(appCodec, tc.responseProtoStruct, originVersionBz) - require.NoError(t, err) - - newVersionBz, err := hex.DecodeString(tc.updatedResponse) - require.NoError(t, err) - jsonMarshalledUpdatedBz, err := keeper.ConvertProtoToJSONMarshal(appCodec, tc.responseProtoStruct, newVersionBz) - require.NoError(t, err) - - // json marshalled bytes should be the same since we use the same proto struct for unmarshalling - require.Equal(t, jsonMarshalledOriginalBz, jsonMarshalledUpdatedBz) - - // raw build also make same result - jsonMarshalExpectedResponse, err := appCodec.MarshalJSON(tc.expectedProto()) - require.NoError(t, err) - require.Equal(t, jsonMarshalledUpdatedBz, jsonMarshalExpectedResponse) - }) - } -} diff --git a/x/wasm/keeper/recurse_test.go b/x/wasm/keeper/recurse_test.go deleted file mode 100644 index d520294..0000000 --- a/x/wasm/keeper/recurse_test.go +++ /dev/null @@ -1,306 +0,0 @@ -package keeper - -import ( - "encoding/json" - "testing" - - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - - "github.com/terpnetwork/terp-core/x/wasm/types" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -type Recurse struct { - Depth uint32 `json:"depth"` - Work uint32 `json:"work"` -} - -type recurseWrapper struct { - Recurse Recurse `json:"recurse"` -} - -func buildRecurseQuery(t *testing.T, msg Recurse) []byte { - wrapper := recurseWrapper{Recurse: msg} - bz, err := json.Marshal(wrapper) - require.NoError(t, err) - return bz -} - -type recurseResponse struct { - Hashed []byte `json:"hashed"` -} - -// number os wasm queries called from a contract -var totalWasmQueryCounter int - -func initRecurseContract(t *testing.T) (contract sdk.AccAddress, ctx sdk.Context, keeper *Keeper) { - countingQuerierDec := func(realWasmQuerier WasmVMQueryHandler) WasmVMQueryHandler { - return WasmVMQueryHandlerFn(func(ctx sdk.Context, caller sdk.AccAddress, request wasmvmtypes.QueryRequest) ([]byte, error) { - totalWasmQueryCounter++ - return realWasmQuerier.HandleQuery(ctx, caller, request) - }) - } - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities, WithQueryHandlerDecorator(countingQuerierDec)) - keeper = keepers.WasmKeeper - exampleContract := InstantiateHackatomExampleContract(t, ctx, keepers) - return exampleContract.Contract, ctx, keeper -} - -func TestGasCostOnQuery(t *testing.T) { - const ( - GasNoWork uint64 = 63_950 - // Note: about 100 SDK gas (10k wasmer gas) for each round of sha256 - GasWork50 uint64 = 64_218 // this is a little shy of 50k gas - to keep an eye on the limit - - GasReturnUnhashed uint64 = 32 - GasReturnHashed uint64 = 27 - ) - - cases := map[string]struct { - gasLimit uint64 - msg Recurse - expectedGas uint64 - }{ - "no recursion, no work": { - gasLimit: 400_000, - msg: Recurse{}, - expectedGas: GasNoWork, - }, - "no recursion, some work": { - gasLimit: 400_000, - msg: Recurse{ - Work: 50, // 50 rounds of sha256 inside the contract - }, - expectedGas: GasWork50, - }, - "recursion 1, no work": { - gasLimit: 400_000, - msg: Recurse{ - Depth: 1, - }, - expectedGas: 2*GasNoWork + GasReturnUnhashed, - }, - "recursion 1, some work": { - gasLimit: 400_000, - msg: Recurse{ - Depth: 1, - Work: 50, - }, - expectedGas: 2*GasWork50 + GasReturnHashed, - }, - "recursion 4, some work": { - gasLimit: 400_000, - msg: Recurse{ - Depth: 4, - Work: 50, - }, - expectedGas: 5*GasWork50 + 4*GasReturnHashed, - }, - } - - contractAddr, ctx, keeper := initRecurseContract(t) - - for name, tc := range cases { - t.Run(name, func(t *testing.T) { - // external limit has no effect (we get a panic if this is enforced) - keeper.queryGasLimit = 1000 - - // make sure we set a limit before calling - ctx = ctx.WithGasMeter(sdk.NewGasMeter(tc.gasLimit)) - require.Equal(t, uint64(0), ctx.GasMeter().GasConsumed()) - - // do the query - recurse := tc.msg - msg := buildRecurseQuery(t, recurse) - data, err := keeper.QuerySmart(ctx, contractAddr, msg) - require.NoError(t, err) - - // check the gas is what we expected - if types.EnableGasVerification { - assert.Equal(t, tc.expectedGas, ctx.GasMeter().GasConsumed()) - } - // assert result is 32 byte sha256 hash (if hashed), or contractAddr if not - var resp recurseResponse - err = json.Unmarshal(data, &resp) - require.NoError(t, err) - if recurse.Work == 0 { - assert.Equal(t, len(contractAddr.String()), len(resp.Hashed)) - } else { - assert.Equal(t, 32, len(resp.Hashed)) - } - }) - } -} - -func TestGasOnExternalQuery(t *testing.T) { - const ( - GasWork50 uint64 = DefaultInstanceCost + 8_464 - ) - - cases := map[string]struct { - gasLimit uint64 - msg Recurse - expOutOfGas bool - }{ - "no recursion, plenty gas": { - gasLimit: 400_000, - msg: Recurse{ - Work: 50, // 50 rounds of sha256 inside the contract - }, - }, - "recursion 4, plenty gas": { - // this uses 244708 gas - gasLimit: 400_000, - msg: Recurse{ - Depth: 4, - Work: 50, - }, - }, - "no recursion, external gas limit": { - gasLimit: 5000, // this is not enough - msg: Recurse{ - Work: 50, - }, - expOutOfGas: true, - }, - "recursion 4, external gas limit": { - // this uses 244708 gas but give less - gasLimit: 4 * GasWork50, - msg: Recurse{ - Depth: 4, - Work: 50, - }, - expOutOfGas: true, - }, - } - - contractAddr, ctx, keeper := initRecurseContract(t) - - for name, tc := range cases { - t.Run(name, func(t *testing.T) { - recurse := tc.msg - msg := buildRecurseQuery(t, recurse) - - querier := NewGrpcQuerier(keeper.cdc, keeper.storeKey, keeper, tc.gasLimit) - req := &types.QuerySmartContractStateRequest{Address: contractAddr.String(), QueryData: msg} - _, gotErr := querier.SmartContractState(sdk.WrapSDKContext(ctx), req) - if tc.expOutOfGas { - require.Error(t, gotErr, sdkerrors.ErrOutOfGas) - return - } - require.NoError(t, gotErr) - }) - } -} - -func TestLimitRecursiveQueryGas(t *testing.T) { - // The point of this test from https://github.com/CosmWasm/cosmwasm/issues/456 - // Basically, if I burn 90% of gas in CPU loop, then query out (to my self) - // the sub-query will have all the original gas (minus the 40k instance charge) - // and can burn 90% and call a sub-contract again... - // This attack would allow us to use far more than the provided gas before - // eventually hitting an OutOfGas panic. - - const ( - // Note: about 100 SDK gas (10k wasmer gas) for each round of sha256 - GasWork2k uint64 = 77_206 // = NewContractInstanceCosts + x // we have 6x gas used in cpu than in the instance - // This is overhead for calling into a sub-contract - GasReturnHashed uint64 = 27 - ) - - cases := map[string]struct { - gasLimit uint64 - msg Recurse - expectQueriesFromContract int - expectedGas uint64 - expectOutOfGas bool - expectError string - }{ - "no recursion, lots of work": { - gasLimit: 4_000_000, - msg: Recurse{ - Depth: 0, - Work: 2000, - }, - expectQueriesFromContract: 0, - expectedGas: GasWork2k, - }, - "recursion 5, lots of work": { - gasLimit: 4_000_000, - msg: Recurse{ - Depth: 5, - Work: 2000, - }, - expectQueriesFromContract: 5, - // FIXME: why -1 ... confused a bit by calculations, seems like rounding issues - expectedGas: GasWork2k + 5*(GasWork2k+GasReturnHashed), - }, - // this is where we expect an error... - // it has enough gas to run 5 times and die on the 6th (5th time dispatching to sub-contract) - // however, if we don't charge the cpu gas before sub-dispatching, we can recurse over 20 times - "deep recursion, should die on 5th level": { - gasLimit: 400_000, - msg: Recurse{ - Depth: 50, - Work: 2000, - }, - expectQueriesFromContract: 5, - expectOutOfGas: true, - }, - "very deep recursion, hits recursion limit": { - gasLimit: 10_000_000, - msg: Recurse{ - Depth: 100, - Work: 2000, - }, - expectQueriesFromContract: 10, - expectOutOfGas: false, - expectError: "query wasm contract failed", // Error we get from the contract instance doing the failing query, not wasmd - expectedGas: 10*(GasWork2k+GasReturnHashed) - 247, - }, - } - - contractAddr, ctx, keeper := initRecurseContract(t) - - for name, tc := range cases { - t.Run(name, func(t *testing.T) { - // reset the counter before test - totalWasmQueryCounter = 0 - - // make sure we set a limit before calling - ctx = ctx.WithGasMeter(sdk.NewGasMeter(tc.gasLimit)) - require.Equal(t, uint64(0), ctx.GasMeter().GasConsumed()) - - // prepare the query - recurse := tc.msg - msg := buildRecurseQuery(t, recurse) - - // if we expect out of gas, make sure this panics - if tc.expectOutOfGas { - require.Panics(t, func() { - _, err := keeper.QuerySmart(ctx, contractAddr, msg) - t.Logf("Got error not panic: %#v", err) - }) - assert.Equal(t, tc.expectQueriesFromContract, totalWasmQueryCounter) - return - } - - // otherwise, we expect a successful call - _, err := keeper.QuerySmart(ctx, contractAddr, msg) - if tc.expectError != "" { - require.ErrorContains(t, err, tc.expectError) - } else { - require.NoError(t, err) - } - if types.EnableGasVerification { - assert.Equal(t, tc.expectedGas, ctx.GasMeter().GasConsumed()) - } - assert.Equal(t, tc.expectQueriesFromContract, totalWasmQueryCounter) - }) - } -} diff --git a/x/wasm/keeper/reflect_test.go b/x/wasm/keeper/reflect_test.go deleted file mode 100644 index 608d705..0000000 --- a/x/wasm/keeper/reflect_test.go +++ /dev/null @@ -1,683 +0,0 @@ -package keeper - -import ( - "encoding/json" - "os" - "strings" - "testing" - - errorsmod "cosmossdk.io/errors" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/cosmos/gogoproto/proto" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/keeper/testdata" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// ReflectInitMsg is {} - -func buildReflectQuery(t *testing.T, query *testdata.ReflectQueryMsg) []byte { - bz, err := json.Marshal(query) - require.NoError(t, err) - return bz -} - -func mustParse(t *testing.T, data []byte, res interface{}) { - err := json.Unmarshal(data, res) - require.NoError(t, err) -} - -const ReflectFeatures = "staking,mask,stargate,cosmwasm_1_1" - -func TestReflectContractSend(t *testing.T) { - cdc := MakeEncodingConfig(t).Marshaler - ctx, keepers := CreateTestInput(t, false, ReflectFeatures, WithMessageEncoders(reflectEncoders(cdc))) - accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.ContractKeeper, keepers.BankKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - _, bob := keyPubAddr() - - // upload reflect code - reflectID, _, err := keeper.Create(ctx, creator, testdata.ReflectContractWasm(), nil) - require.NoError(t, err) - require.Equal(t, uint64(1), reflectID) - - // upload hackatom escrow code - escrowCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - escrowID, _, err := keeper.Create(ctx, creator, escrowCode, nil) - require.NoError(t, err) - require.Equal(t, uint64(2), escrowID) - - // creator instantiates a contract and gives it tokens - reflectStart := sdk.NewCoins(sdk.NewInt64Coin("denom", 40000)) - reflectAddr, _, err := keeper.Instantiate(ctx, reflectID, creator, nil, []byte("{}"), "reflect contract 2", reflectStart) - require.NoError(t, err) - require.NotEmpty(t, reflectAddr) - - // now we set contract as verifier of an escrow - initMsg := HackatomExampleInitMsg{ - Verifier: reflectAddr, - Beneficiary: bob, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - escrowStart := sdk.NewCoins(sdk.NewInt64Coin("denom", 25000)) - escrowAddr, _, err := keeper.Instantiate(ctx, escrowID, creator, nil, initMsgBz, "escrow contract 2", escrowStart) - require.NoError(t, err) - require.NotEmpty(t, escrowAddr) - - // let's make sure all balances make sense - checkAccount(t, ctx, accKeeper, bankKeeper, creator, sdk.NewCoins(sdk.NewInt64Coin("denom", 35000))) // 100k - 40k - 25k - checkAccount(t, ctx, accKeeper, bankKeeper, reflectAddr, reflectStart) - checkAccount(t, ctx, accKeeper, bankKeeper, escrowAddr, escrowStart) - checkAccount(t, ctx, accKeeper, bankKeeper, bob, nil) - - // now for the trick.... we reflect a message through the reflect to call the escrow - // we also send an additional 14k tokens there. - // this should reduce the reflect balance by 14k (to 26k) - // this 14k is added to the escrow, then the entire balance is sent to bob (total: 39k) - approveMsg := []byte(`{"release":{}}`) - msgs := []wasmvmtypes.CosmosMsg{{ - Wasm: &wasmvmtypes.WasmMsg{ - Execute: &wasmvmtypes.ExecuteMsg{ - ContractAddr: escrowAddr.String(), - Msg: approveMsg, - Funds: []wasmvmtypes.Coin{{ - Denom: "denom", - Amount: "14000", - }}, - }, - }, - }} - reflectSend := testdata.ReflectHandleMsg{ - Reflect: &testdata.ReflectPayload{ - Msgs: msgs, - }, - } - reflectSendBz, err := json.Marshal(reflectSend) - require.NoError(t, err) - _, err = keeper.Execute(ctx, reflectAddr, creator, reflectSendBz, nil) - require.NoError(t, err) - - // did this work??? - checkAccount(t, ctx, accKeeper, bankKeeper, creator, sdk.NewCoins(sdk.NewInt64Coin("denom", 35000))) // same as before - checkAccount(t, ctx, accKeeper, bankKeeper, reflectAddr, sdk.NewCoins(sdk.NewInt64Coin("denom", 26000))) // 40k - 14k (from send) - checkAccount(t, ctx, accKeeper, bankKeeper, escrowAddr, sdk.Coins{}) // emptied reserved - checkAccount(t, ctx, accKeeper, bankKeeper, bob, sdk.NewCoins(sdk.NewInt64Coin("denom", 39000))) // all escrow of 25k + 14k -} - -func TestReflectCustomMsg(t *testing.T) { - cdc := MakeEncodingConfig(t).Marshaler - ctx, keepers := CreateTestInput(t, false, ReflectFeatures, WithMessageEncoders(reflectEncoders(cdc)), WithQueryPlugins(reflectPlugins())) - accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.ContractKeeper, keepers.BankKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - bob := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - _, fred := keyPubAddr() - - // upload code - codeID, _, err := keeper.Create(ctx, creator, testdata.ReflectContractWasm(), nil) - require.NoError(t, err) - require.Equal(t, uint64(1), codeID) - - // creator instantiates a contract and gives it tokens - contractStart := sdk.NewCoins(sdk.NewInt64Coin("denom", 40000)) - contractAddr, _, err := keeper.Instantiate(ctx, codeID, creator, nil, []byte("{}"), "reflect contract 1", contractStart) - require.NoError(t, err) - require.NotEmpty(t, contractAddr) - - // set owner to bob - transfer := testdata.ReflectHandleMsg{ - ChangeOwner: &testdata.OwnerPayload{ - Owner: bob, - }, - } - transferBz, err := json.Marshal(transfer) - require.NoError(t, err) - _, err = keeper.Execute(ctx, contractAddr, creator, transferBz, nil) - require.NoError(t, err) - - // check some account values - checkAccount(t, ctx, accKeeper, bankKeeper, contractAddr, contractStart) - checkAccount(t, ctx, accKeeper, bankKeeper, bob, deposit) - checkAccount(t, ctx, accKeeper, bankKeeper, fred, nil) - - // bob can send contract's tokens to fred (using SendMsg) - msgs := []wasmvmtypes.CosmosMsg{{ - Bank: &wasmvmtypes.BankMsg{ - Send: &wasmvmtypes.SendMsg{ - ToAddress: fred.String(), - Amount: []wasmvmtypes.Coin{{ - Denom: "denom", - Amount: "15000", - }}, - }, - }, - }} - reflectSend := testdata.ReflectHandleMsg{ - Reflect: &testdata.ReflectPayload{ - Msgs: msgs, - }, - } - reflectSendBz, err := json.Marshal(reflectSend) - require.NoError(t, err) - _, err = keeper.Execute(ctx, contractAddr, bob, reflectSendBz, nil) - require.NoError(t, err) - - // fred got coins - checkAccount(t, ctx, accKeeper, bankKeeper, fred, sdk.NewCoins(sdk.NewInt64Coin("denom", 15000))) - // contract lost them - checkAccount(t, ctx, accKeeper, bankKeeper, contractAddr, sdk.NewCoins(sdk.NewInt64Coin("denom", 25000))) - checkAccount(t, ctx, accKeeper, bankKeeper, bob, deposit) - - // construct an opaque message - var sdkSendMsg sdk.Msg = &banktypes.MsgSend{ - FromAddress: contractAddr.String(), - ToAddress: fred.String(), - Amount: sdk.NewCoins(sdk.NewInt64Coin("denom", 23000)), - } - opaque, err := toReflectRawMsg(cdc, sdkSendMsg) - require.NoError(t, err) - reflectOpaque := testdata.ReflectHandleMsg{ - Reflect: &testdata.ReflectPayload{ - Msgs: []wasmvmtypes.CosmosMsg{opaque}, - }, - } - reflectOpaqueBz, err := json.Marshal(reflectOpaque) - require.NoError(t, err) - - _, err = keeper.Execute(ctx, contractAddr, bob, reflectOpaqueBz, nil) - require.NoError(t, err) - - // fred got more coins - checkAccount(t, ctx, accKeeper, bankKeeper, fred, sdk.NewCoins(sdk.NewInt64Coin("denom", 38000))) - // contract lost them - checkAccount(t, ctx, accKeeper, bankKeeper, contractAddr, sdk.NewCoins(sdk.NewInt64Coin("denom", 2000))) - checkAccount(t, ctx, accKeeper, bankKeeper, bob, deposit) -} - -func TestMaskReflectCustomQuery(t *testing.T) { - cdc := MakeEncodingConfig(t).Marshaler - ctx, keepers := CreateTestInput(t, false, ReflectFeatures, WithMessageEncoders(reflectEncoders(cdc)), WithQueryPlugins(reflectPlugins())) - keeper := keepers.WasmKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - - // upload code - codeID, _, err := keepers.ContractKeeper.Create(ctx, creator, testdata.ReflectContractWasm(), nil) - require.NoError(t, err) - require.Equal(t, uint64(1), codeID) - - // creator instantiates a contract and gives it tokens - contractStart := sdk.NewCoins(sdk.NewInt64Coin("denom", 40000)) - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, []byte("{}"), "reflect contract 1", contractStart) - require.NoError(t, err) - require.NotEmpty(t, contractAddr) - - // let's perform a normal query of state - ownerQuery := testdata.ReflectQueryMsg{ - Owner: &struct{}{}, - } - ownerQueryBz, err := json.Marshal(ownerQuery) - require.NoError(t, err) - ownerRes, err := keeper.QuerySmart(ctx, contractAddr, ownerQueryBz) - require.NoError(t, err) - var res testdata.OwnerResponse - err = json.Unmarshal(ownerRes, &res) - require.NoError(t, err) - assert.Equal(t, res.Owner, creator.String()) - - // and now making use of the custom querier callbacks - customQuery := testdata.ReflectQueryMsg{ - Capitalized: &testdata.Text{ - Text: "all Caps noW", - }, - } - customQueryBz, err := json.Marshal(customQuery) - require.NoError(t, err) - custom, err := keeper.QuerySmart(ctx, contractAddr, customQueryBz) - require.NoError(t, err) - var resp capitalizedResponse - err = json.Unmarshal(custom, &resp) - require.NoError(t, err) - assert.Equal(t, resp.Text, "ALL CAPS NOW") -} - -func TestReflectStargateQuery(t *testing.T) { - cdc := MakeEncodingConfig(t).Marshaler - ctx, keepers := CreateTestInput(t, false, ReflectFeatures, WithMessageEncoders(reflectEncoders(cdc)), WithQueryPlugins(reflectPlugins())) - keeper := keepers.WasmKeeper - - funds := sdk.NewCoins(sdk.NewInt64Coin("denom", 320000)) - contractStart := sdk.NewCoins(sdk.NewInt64Coin("denom", 40000)) - expectedBalance := funds.Sub(contractStart...) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, funds...) - - // upload code - codeID, _, err := keepers.ContractKeeper.Create(ctx, creator, testdata.ReflectContractWasm(), nil) - require.NoError(t, err) - require.Equal(t, uint64(1), codeID) - - // creator instantiates a contract and gives it tokens - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, []byte("{}"), "reflect contract 1", contractStart) - require.NoError(t, err) - require.NotEmpty(t, contractAddr) - - // first, normal query for the bank balance (to make sure our query is proper) - bankQuery := wasmvmtypes.QueryRequest{ - Bank: &wasmvmtypes.BankQuery{ - AllBalances: &wasmvmtypes.AllBalancesQuery{ - Address: creator.String(), - }, - }, - } - simpleQueryBz, err := json.Marshal(testdata.ReflectQueryMsg{ - Chain: &testdata.ChainQuery{Request: &bankQuery}, - }) - require.NoError(t, err) - simpleRes, err := keeper.QuerySmart(ctx, contractAddr, simpleQueryBz) - require.NoError(t, err) - var simpleChain testdata.ChainResponse - mustParse(t, simpleRes, &simpleChain) - var simpleBalance wasmvmtypes.AllBalancesResponse - mustParse(t, simpleChain.Data, &simpleBalance) - require.Equal(t, len(expectedBalance), len(simpleBalance.Amount)) - assert.Equal(t, simpleBalance.Amount[0].Amount, expectedBalance[0].Amount.String()) - assert.Equal(t, simpleBalance.Amount[0].Denom, expectedBalance[0].Denom) -} - -func TestReflectTotalSupplyQuery(t *testing.T) { - cdc := MakeEncodingConfig(t).Marshaler - ctx, keepers := CreateTestInput(t, false, ReflectFeatures, WithMessageEncoders(reflectEncoders(cdc)), WithQueryPlugins(reflectPlugins())) - keeper := keepers.WasmKeeper - // upload code - codeID := StoreReflectContract(t, ctx, keepers).CodeID - // creator instantiates a contract and gives it tokens - creator := RandomAccountAddress(t) - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, []byte("{}"), "testing", nil) - require.NoError(t, err) - - currentStakeSupply := keepers.BankKeeper.GetSupply(ctx, "stake") - require.NotEmpty(t, currentStakeSupply.Amount) // ensure we have real data - specs := map[string]struct { - denom string - expAmount wasmvmtypes.Coin - }{ - "known denom": { - denom: "stake", - expAmount: ConvertSdkCoinToWasmCoin(currentStakeSupply), - }, - "unknown denom": { - denom: "unknown", - expAmount: wasmvmtypes.Coin{Denom: "unknown", Amount: "0"}, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - // when - queryBz := mustMarshal(t, testdata.ReflectQueryMsg{ - Chain: &testdata.ChainQuery{ - Request: &wasmvmtypes.QueryRequest{ - Bank: &wasmvmtypes.BankQuery{ - Supply: &wasmvmtypes.SupplyQuery{Denom: spec.denom}, - }, - }, - }, - }) - simpleRes, err := keeper.QuerySmart(ctx, contractAddr, queryBz) - - // then - require.NoError(t, err) - var rsp testdata.ChainResponse - mustParse(t, simpleRes, &rsp) - var supplyRsp wasmvmtypes.SupplyResponse - mustParse(t, rsp.Data, &supplyRsp) - assert.Equal(t, spec.expAmount, supplyRsp.Amount, spec.expAmount) - }) - } -} - -func TestReflectInvalidStargateQuery(t *testing.T) { - cdc := MakeEncodingConfig(t).Marshaler - ctx, keepers := CreateTestInput(t, false, ReflectFeatures, WithMessageEncoders(reflectEncoders(cdc)), WithQueryPlugins(reflectPlugins())) - keeper := keepers.WasmKeeper - - funds := sdk.NewCoins(sdk.NewInt64Coin("denom", 320000)) - contractStart := sdk.NewCoins(sdk.NewInt64Coin("denom", 40000)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, funds...) - - // upload code - codeID, _, err := keepers.ContractKeeper.Create(ctx, creator, testdata.ReflectContractWasm(), nil) - require.NoError(t, err) - require.Equal(t, uint64(1), codeID) - - // creator instantiates a contract and gives it tokens - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, []byte("{}"), "reflect contract 1", contractStart) - require.NoError(t, err) - require.NotEmpty(t, contractAddr) - - // now, try to build a protobuf query - protoQuery := banktypes.QueryAllBalancesRequest{ - Address: creator.String(), - } - protoQueryBin, err := proto.Marshal(&protoQuery) - require.NoError(t, err) - - protoRequest := wasmvmtypes.QueryRequest{ - Stargate: &wasmvmtypes.StargateQuery{ - Path: "/cosmos.bank.v1beta1.Query/AllBalances", - Data: protoQueryBin, - }, - } - protoQueryBz, err := json.Marshal(testdata.ReflectQueryMsg{ - Chain: &testdata.ChainQuery{Request: &protoRequest}, - }) - require.NoError(t, err) - - // make a query on the chain, should not be whitelisted - _, err = keeper.QuerySmart(ctx, contractAddr, protoQueryBz) - require.Error(t, err) - require.Contains(t, err.Error(), "Unsupported query") - - // now, try to build a protobuf query - protoRequest = wasmvmtypes.QueryRequest{ - Stargate: &wasmvmtypes.StargateQuery{ - Path: "/cosmos.tx.v1beta1.Service/GetTx", - Data: []byte{}, - }, - } - protoQueryBz, err = json.Marshal(testdata.ReflectQueryMsg{ - Chain: &testdata.ChainQuery{Request: &protoRequest}, - }) - require.NoError(t, err) - - // make a query on the chain, should be blacklisted - _, err = keeper.QuerySmart(ctx, contractAddr, protoQueryBz) - require.Error(t, err) - require.Contains(t, err.Error(), "Unsupported query") - - // and another one - protoRequest = wasmvmtypes.QueryRequest{ - Stargate: &wasmvmtypes.StargateQuery{ - Path: "/cosmos.base.tendermint.v1beta1.Service/GetNodeInfo", - Data: []byte{}, - }, - } - protoQueryBz, err = json.Marshal(testdata.ReflectQueryMsg{ - Chain: &testdata.ChainQuery{Request: &protoRequest}, - }) - require.NoError(t, err) - - // make a query on the chain, should be blacklisted - _, err = keeper.QuerySmart(ctx, contractAddr, protoQueryBz) - require.Error(t, err) - require.Contains(t, err.Error(), "Unsupported query") -} - -type reflectState struct { - Owner string `json:"owner"` -} - -func TestMaskReflectWasmQueries(t *testing.T) { - cdc := MakeEncodingConfig(t).Marshaler - ctx, keepers := CreateTestInput(t, false, ReflectFeatures, WithMessageEncoders(reflectEncoders(cdc)), WithQueryPlugins(reflectPlugins())) - keeper := keepers.WasmKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - - // upload reflect code - reflectID, _, err := keepers.ContractKeeper.Create(ctx, creator, testdata.ReflectContractWasm(), nil) - require.NoError(t, err) - require.Equal(t, uint64(1), reflectID) - - // creator instantiates a contract and gives it tokens - reflectStart := sdk.NewCoins(sdk.NewInt64Coin("denom", 40000)) - reflectAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, reflectID, creator, nil, []byte("{}"), "reflect contract 2", reflectStart) - require.NoError(t, err) - require.NotEmpty(t, reflectAddr) - - // for control, let's make some queries directly on the reflect - ownerQuery := buildReflectQuery(t, &testdata.ReflectQueryMsg{Owner: &struct{}{}}) - res, err := keeper.QuerySmart(ctx, reflectAddr, ownerQuery) - require.NoError(t, err) - var ownerRes testdata.OwnerResponse - mustParse(t, res, &ownerRes) - require.Equal(t, ownerRes.Owner, creator.String()) - - // and a raw query: cosmwasm_storage::Singleton uses 2 byte big-endian length-prefixed to store data - configKey := append([]byte{0, 6}, []byte("config")...) - raw := keeper.QueryRaw(ctx, reflectAddr, configKey) - var stateRes reflectState - mustParse(t, raw, &stateRes) - require.Equal(t, stateRes.Owner, creator.String()) - - // now, let's reflect a smart query into the x/wasm handlers and see if we get the same result - reflectOwnerQuery := testdata.ReflectQueryMsg{Chain: &testdata.ChainQuery{Request: &wasmvmtypes.QueryRequest{Wasm: &wasmvmtypes.WasmQuery{ - Smart: &wasmvmtypes.SmartQuery{ - ContractAddr: reflectAddr.String(), - Msg: ownerQuery, - }, - }}}} - reflectOwnerBin := buildReflectQuery(t, &reflectOwnerQuery) - res, err = keeper.QuerySmart(ctx, reflectAddr, reflectOwnerBin) - require.NoError(t, err) - // first we pull out the data from chain response, before parsing the original response - var reflectRes testdata.ChainResponse - mustParse(t, res, &reflectRes) - var reflectOwnerRes testdata.OwnerResponse - mustParse(t, reflectRes.Data, &reflectOwnerRes) - require.Equal(t, reflectOwnerRes.Owner, creator.String()) - - // and with queryRaw - reflectStateQuery := testdata.ReflectQueryMsg{Chain: &testdata.ChainQuery{Request: &wasmvmtypes.QueryRequest{Wasm: &wasmvmtypes.WasmQuery{ - Raw: &wasmvmtypes.RawQuery{ - ContractAddr: reflectAddr.String(), - Key: configKey, - }, - }}}} - reflectStateBin := buildReflectQuery(t, &reflectStateQuery) - res, err = keeper.QuerySmart(ctx, reflectAddr, reflectStateBin) - require.NoError(t, err) - // first we pull out the data from chain response, before parsing the original response - var reflectRawRes testdata.ChainResponse - mustParse(t, res, &reflectRawRes) - // now, with the raw data, we can parse it into state - var reflectStateRes reflectState - mustParse(t, reflectRawRes.Data, &reflectStateRes) - require.Equal(t, reflectStateRes.Owner, creator.String()) -} - -func TestWasmRawQueryWithNil(t *testing.T) { - cdc := MakeEncodingConfig(t).Marshaler - ctx, keepers := CreateTestInput(t, false, ReflectFeatures, WithMessageEncoders(reflectEncoders(cdc)), WithQueryPlugins(reflectPlugins())) - keeper := keepers.WasmKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - - // upload reflect code - reflectID, _, err := keepers.ContractKeeper.Create(ctx, creator, testdata.ReflectContractWasm(), nil) - require.NoError(t, err) - require.Equal(t, uint64(1), reflectID) - - // creator instantiates a contract and gives it tokens - reflectStart := sdk.NewCoins(sdk.NewInt64Coin("denom", 40000)) - reflectAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, reflectID, creator, nil, []byte("{}"), "reflect contract 2", reflectStart) - require.NoError(t, err) - require.NotEmpty(t, reflectAddr) - - // control: query directly - missingKey := []byte{0, 1, 2, 3, 4} - raw := keeper.QueryRaw(ctx, reflectAddr, missingKey) - require.Nil(t, raw) - - // and with queryRaw - reflectQuery := testdata.ReflectQueryMsg{Chain: &testdata.ChainQuery{Request: &wasmvmtypes.QueryRequest{Wasm: &wasmvmtypes.WasmQuery{ - Raw: &wasmvmtypes.RawQuery{ - ContractAddr: reflectAddr.String(), - Key: missingKey, - }, - }}}} - reflectStateBin := buildReflectQuery(t, &reflectQuery) - res, err := keeper.QuerySmart(ctx, reflectAddr, reflectStateBin) - require.NoError(t, err) - - // first we pull out the data from chain response, before parsing the original response - var reflectRawRes testdata.ChainResponse - mustParse(t, res, &reflectRawRes) - // and make sure there is no data - require.Empty(t, reflectRawRes.Data) - // we get an empty byte slice not nil (if anyone care in go-land) - require.Equal(t, []byte{}, reflectRawRes.Data) -} - -func TestRustPanicIsHandled(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, ReflectFeatures) - keeper := keepers.ContractKeeper - - creator := keepers.Faucet.NewFundedRandomAccount(ctx, sdk.NewCoins(sdk.NewInt64Coin("denom", 100000))...) - - // upload code - codeID, _, err := keeper.Create(ctx, creator, testdata.CyberpunkContractWasm(), nil) - require.NoError(t, err) - require.Equal(t, uint64(1), codeID) - - contractAddr, _, err := keeper.Instantiate(ctx, codeID, creator, nil, []byte("{}"), "cyberpunk contract", nil) - require.NoError(t, err) - require.NotEmpty(t, contractAddr) - - // when panic is triggered - msg := []byte(`{"panic":{}}`) - gotData, err := keeper.Execute(ctx, contractAddr, creator, msg, nil) - require.ErrorIs(t, err, types.ErrExecuteFailed) - assert.Contains(t, err.Error(), "panicked at 'This page intentionally faulted'") - assert.Nil(t, gotData) -} - -func checkAccount(t *testing.T, ctx sdk.Context, accKeeper authkeeper.AccountKeeper, bankKeeper bankkeeper.Keeper, addr sdk.AccAddress, expected sdk.Coins) { - acct := accKeeper.GetAccount(ctx, addr) - if expected == nil { - assert.Nil(t, acct) - } else { - assert.NotNil(t, acct) - if expected.Empty() { - // there is confusion between nil and empty slice... let's just treat them the same - assert.True(t, bankKeeper.GetAllBalances(ctx, acct.GetAddress()).Empty()) - } else { - assert.Equal(t, bankKeeper.GetAllBalances(ctx, acct.GetAddress()), expected) - } - } -} - -/**** Code to support custom messages *****/ - -type reflectCustomMsg struct { - Debug string `json:"debug,omitempty"` - Raw []byte `json:"raw,omitempty"` -} - -// toReflectRawMsg encodes an sdk msg using any type with json encoding. -// Then wraps it as an opaque message -func toReflectRawMsg(cdc codec.Codec, msg sdk.Msg) (wasmvmtypes.CosmosMsg, error) { - codecAny, err := codectypes.NewAnyWithValue(msg) - if err != nil { - return wasmvmtypes.CosmosMsg{}, err - } - rawBz, err := cdc.MarshalJSON(codecAny) - if err != nil { - return wasmvmtypes.CosmosMsg{}, errorsmod.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - customMsg, _ := json.Marshal(reflectCustomMsg{ - Raw: rawBz, - }) - res := wasmvmtypes.CosmosMsg{ - Custom: customMsg, - } - return res, err -} - -// reflectEncoders needs to be registered in test setup to handle custom message callbacks -func reflectEncoders(cdc codec.Codec) *MessageEncoders { - return &MessageEncoders{ - Custom: fromReflectRawMsg(cdc), - } -} - -// fromReflectRawMsg decodes msg.Data to an sdk.Msg using proto Any and json encoding. -// this needs to be registered on the Encoders -func fromReflectRawMsg(cdc codec.Codec) CustomEncoder { - return func(_sender sdk.AccAddress, msg json.RawMessage) ([]sdk.Msg, error) { - var custom reflectCustomMsg - err := json.Unmarshal(msg, &custom) - if err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - if custom.Raw != nil { - var codecAny codectypes.Any - if err := cdc.UnmarshalJSON(custom.Raw, &codecAny); err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - var msg sdk.Msg - if err := cdc.UnpackAny(&codecAny, &msg); err != nil { - return nil, err - } - return []sdk.Msg{msg}, nil - } - if custom.Debug != "" { - return nil, errorsmod.Wrapf(types.ErrInvalidMsg, "Custom Debug: %s", custom.Debug) - } - return nil, errorsmod.Wrap(types.ErrInvalidMsg, "Unknown Custom message variant") - } -} - -type reflectCustomQuery struct { - Ping *struct{} `json:"ping,omitempty"` - Capitalized *testdata.Text `json:"capitalized,omitempty"` -} - -// this is from the go code back to the contract (capitalized or ping) -type customQueryResponse struct { - Msg string `json:"msg"` -} - -// this is from the contract to the go code (capitalized or ping) -type capitalizedResponse struct { - Text string `json:"text"` -} - -// reflectPlugins needs to be registered in test setup to handle custom query callbacks -func reflectPlugins() *QueryPlugins { - return &QueryPlugins{ - Custom: performCustomQuery, - } -} - -func performCustomQuery(_ sdk.Context, request json.RawMessage) ([]byte, error) { - var custom reflectCustomQuery - err := json.Unmarshal(request, &custom) - if err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - if custom.Capitalized != nil { - msg := strings.ToUpper(custom.Capitalized.Text) - return json.Marshal(customQueryResponse{Msg: msg}) - } - if custom.Ping != nil { - return json.Marshal(customQueryResponse{Msg: "pong"}) - } - return nil, errorsmod.Wrap(types.ErrInvalidMsg, "Unknown Custom query variant") -} diff --git a/x/wasm/keeper/relay.go b/x/wasm/keeper/relay.go deleted file mode 100644 index a265179..0000000 --- a/x/wasm/keeper/relay.go +++ /dev/null @@ -1,203 +0,0 @@ -package keeper - -import ( - "time" - - errorsmod "cosmossdk.io/errors" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/cosmos/cosmos-sdk/telemetry" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -var _ types.IBCContractKeeper = (*Keeper)(nil) - -// OnOpenChannel calls the contract to participate in the IBC channel handshake step. -// In the IBC protocol this is either the `Channel Open Init` event on the initiating chain or -// `Channel Open Try` on the counterparty chain. -// Protocol version and channel ordering should be verified for example. -// See https://github.com/cosmos/ics/tree/master/spec/ics-004-channel-and-packet-semantics#channel-lifecycle-management -func (k Keeper) OnOpenChannel( - ctx sdk.Context, - contractAddr sdk.AccAddress, - msg wasmvmtypes.IBCChannelOpenMsg, -) (string, error) { - defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "ibc-open-channel") - _, codeInfo, prefixStore, err := k.contractInstance(ctx, contractAddr) - if err != nil { - return "", err - } - - env := types.NewEnv(ctx, contractAddr) - querier := k.newQueryHandler(ctx, contractAddr) - - gas := k.runtimeGasForContract(ctx) - res, gasUsed, execErr := k.wasmVM.IBCChannelOpen(codeInfo.CodeHash, env, msg, prefixStore, cosmwasmAPI, querier, ctx.GasMeter(), gas, costJSONDeserialization) - k.consumeRuntimeGas(ctx, gasUsed) - if execErr != nil { - return "", errorsmod.Wrap(types.ErrExecuteFailed, execErr.Error()) - } - if res != nil { - return res.Version, nil - } - return "", nil -} - -// OnConnectChannel calls the contract to let it know the IBC channel was established. -// In the IBC protocol this is either the `Channel Open Ack` event on the initiating chain or -// `Channel Open Confirm` on the counterparty chain. -// -// There is an open issue with the [cosmos-sdk](https://github.com/cosmos/cosmos-sdk/issues/8334) -// that the counterparty channelID is empty on the initiating chain -// See https://github.com/cosmos/ics/tree/master/spec/ics-004-channel-and-packet-semantics#channel-lifecycle-management -func (k Keeper) OnConnectChannel( - ctx sdk.Context, - contractAddr sdk.AccAddress, - msg wasmvmtypes.IBCChannelConnectMsg, -) error { - defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "ibc-connect-channel") - contractInfo, codeInfo, prefixStore, err := k.contractInstance(ctx, contractAddr) - if err != nil { - return err - } - - env := types.NewEnv(ctx, contractAddr) - querier := k.newQueryHandler(ctx, contractAddr) - - gas := k.runtimeGasForContract(ctx) - res, gasUsed, execErr := k.wasmVM.IBCChannelConnect(codeInfo.CodeHash, env, msg, prefixStore, cosmwasmAPI, querier, ctx.GasMeter(), gas, costJSONDeserialization) - k.consumeRuntimeGas(ctx, gasUsed) - if execErr != nil { - return errorsmod.Wrap(types.ErrExecuteFailed, execErr.Error()) - } - - return k.handleIBCBasicContractResponse(ctx, contractAddr, contractInfo.IBCPortID, res) -} - -// OnCloseChannel calls the contract to let it know the IBC channel is closed. -// Calling modules MAY atomically execute appropriate application logic in conjunction with calling chanCloseConfirm. -// -// Once closed, channels cannot be reopened and identifiers cannot be reused. Identifier reuse is prevented because -// we want to prevent potential replay of previously sent packets -// See https://github.com/cosmos/ics/tree/master/spec/ics-004-channel-and-packet-semantics#channel-lifecycle-management -func (k Keeper) OnCloseChannel( - ctx sdk.Context, - contractAddr sdk.AccAddress, - msg wasmvmtypes.IBCChannelCloseMsg, -) error { - defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "ibc-close-channel") - - contractInfo, codeInfo, prefixStore, err := k.contractInstance(ctx, contractAddr) - if err != nil { - return err - } - - params := types.NewEnv(ctx, contractAddr) - querier := k.newQueryHandler(ctx, contractAddr) - - gas := k.runtimeGasForContract(ctx) - res, gasUsed, execErr := k.wasmVM.IBCChannelClose(codeInfo.CodeHash, params, msg, prefixStore, cosmwasmAPI, querier, ctx.GasMeter(), gas, costJSONDeserialization) - k.consumeRuntimeGas(ctx, gasUsed) - if execErr != nil { - return errorsmod.Wrap(types.ErrExecuteFailed, execErr.Error()) - } - - return k.handleIBCBasicContractResponse(ctx, contractAddr, contractInfo.IBCPortID, res) -} - -// OnRecvPacket calls the contract to process the incoming IBC packet. The contract fully owns the data processing and -// returns the acknowledgement data for the chain level. This allows custom applications and protocols on top -// of IBC. Although it is recommended to use the standard acknowledgement envelope defined in -// https://github.com/cosmos/ics/tree/master/spec/ics-004-channel-and-packet-semantics#acknowledgement-envelope -// -// For more information see: https://github.com/cosmos/ics/tree/master/spec/ics-004-channel-and-packet-semantics#packet-flow--handling -func (k Keeper) OnRecvPacket( - ctx sdk.Context, - contractAddr sdk.AccAddress, - msg wasmvmtypes.IBCPacketReceiveMsg, -) ([]byte, error) { - defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "ibc-recv-packet") - contractInfo, codeInfo, prefixStore, err := k.contractInstance(ctx, contractAddr) - if err != nil { - return nil, err - } - - env := types.NewEnv(ctx, contractAddr) - querier := k.newQueryHandler(ctx, contractAddr) - - gas := k.runtimeGasForContract(ctx) - res, gasUsed, execErr := k.wasmVM.IBCPacketReceive(codeInfo.CodeHash, env, msg, prefixStore, cosmwasmAPI, querier, ctx.GasMeter(), gas, costJSONDeserialization) - k.consumeRuntimeGas(ctx, gasUsed) - if execErr != nil { - panic(execErr) - } - if res.Err != "" { // handle error case as before https://github.com/CosmWasm/wasmvm/commit/c300106fe5c9426a495f8e10821e00a9330c56c6 - return nil, errorsmod.Wrap(types.ErrExecuteFailed, res.Err) - } - // note submessage reply results can overwrite the `Acknowledgement` data - return k.handleContractResponse(ctx, contractAddr, contractInfo.IBCPortID, res.Ok.Messages, res.Ok.Attributes, res.Ok.Acknowledgement, res.Ok.Events) -} - -// OnAckPacket calls the contract to handle the "acknowledgement" data which can contain success or failure of a packet -// acknowledgement written on the receiving chain for example. This is application level data and fully owned by the -// contract. The use of the standard acknowledgement envelope is recommended: https://github.com/cosmos/ics/tree/master/spec/ics-004-channel-and-packet-semantics#acknowledgement-envelope -// -// On application errors the contract can revert an operation like returning tokens as in ibc-transfer. -// -// For more information see: https://github.com/cosmos/ics/tree/master/spec/ics-004-channel-and-packet-semantics#packet-flow--handling -func (k Keeper) OnAckPacket( - ctx sdk.Context, - contractAddr sdk.AccAddress, - msg wasmvmtypes.IBCPacketAckMsg, -) error { - defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "ibc-ack-packet") - contractInfo, codeInfo, prefixStore, err := k.contractInstance(ctx, contractAddr) - if err != nil { - return err - } - - env := types.NewEnv(ctx, contractAddr) - querier := k.newQueryHandler(ctx, contractAddr) - - gas := k.runtimeGasForContract(ctx) - res, gasUsed, execErr := k.wasmVM.IBCPacketAck(codeInfo.CodeHash, env, msg, prefixStore, cosmwasmAPI, querier, ctx.GasMeter(), gas, costJSONDeserialization) - k.consumeRuntimeGas(ctx, gasUsed) - if execErr != nil { - return errorsmod.Wrap(types.ErrExecuteFailed, execErr.Error()) - } - return k.handleIBCBasicContractResponse(ctx, contractAddr, contractInfo.IBCPortID, res) -} - -// OnTimeoutPacket calls the contract to let it know the packet was never received on the destination chain within -// the timeout boundaries. -// The contract should handle this on the application level and undo the original operation -func (k Keeper) OnTimeoutPacket( - ctx sdk.Context, - contractAddr sdk.AccAddress, - msg wasmvmtypes.IBCPacketTimeoutMsg, -) error { - defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "ibc-timeout-packet") - - contractInfo, codeInfo, prefixStore, err := k.contractInstance(ctx, contractAddr) - if err != nil { - return err - } - - env := types.NewEnv(ctx, contractAddr) - querier := k.newQueryHandler(ctx, contractAddr) - - gas := k.runtimeGasForContract(ctx) - res, gasUsed, execErr := k.wasmVM.IBCPacketTimeout(codeInfo.CodeHash, env, msg, prefixStore, cosmwasmAPI, querier, ctx.GasMeter(), gas, costJSONDeserialization) - k.consumeRuntimeGas(ctx, gasUsed) - if execErr != nil { - return errorsmod.Wrap(types.ErrExecuteFailed, execErr.Error()) - } - - return k.handleIBCBasicContractResponse(ctx, contractAddr, contractInfo.IBCPortID, res) -} - -func (k Keeper) handleIBCBasicContractResponse(ctx sdk.Context, addr sdk.AccAddress, id string, res *wasmvmtypes.IBCBasicResponse) error { - _, err := k.handleContractResponse(ctx, addr, id, res.Messages, res.Attributes, nil, res.Events) - return err -} diff --git a/x/wasm/keeper/relay_test.go b/x/wasm/keeper/relay_test.go deleted file mode 100644 index c9c72ad..0000000 --- a/x/wasm/keeper/relay_test.go +++ /dev/null @@ -1,711 +0,0 @@ -package keeper - -import ( - "encoding/json" - "errors" - "math" - "testing" - - wasmvm "github.com/CosmWasm/wasmvm" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/keeper/wasmtesting" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestOnOpenChannel(t *testing.T) { - var m wasmtesting.MockWasmer - wasmtesting.MakeIBCInstantiable(&m) - messenger := &wasmtesting.MockMessageHandler{} - parentCtx, keepers := CreateTestInput(t, false, AvailableCapabilities, WithMessageHandler(messenger)) - example := SeedNewContractInstance(t, parentCtx, keepers, &m) - const myContractGas = 40 - - specs := map[string]struct { - contractAddr sdk.AccAddress - contractGas sdk.Gas - contractErr error - expGas uint64 - expErr bool - }{ - "consume contract gas": { - contractAddr: example.Contract, - contractGas: myContractGas, - expGas: myContractGas, - }, - "consume max gas": { - contractAddr: example.Contract, - contractGas: math.MaxUint64 / DefaultGasMultiplier, - expGas: math.MaxUint64 / DefaultGasMultiplier, - }, - "consume gas on error": { - contractAddr: example.Contract, - contractGas: myContractGas, - contractErr: errors.New("test, ignore"), - expErr: true, - }, - "unknown contract address": { - contractAddr: RandomAccountAddress(t), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - myChannel := wasmvmtypes.IBCChannel{Version: "my test channel"} - myMsg := wasmvmtypes.IBCChannelOpenMsg{OpenTry: &wasmvmtypes.IBCOpenTry{Channel: myChannel, CounterpartyVersion: "foo"}} - m.IBCChannelOpenFn = func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCChannelOpenMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBC3ChannelOpenResponse, uint64, error) { - assert.Equal(t, myMsg, msg) - return &wasmvmtypes.IBC3ChannelOpenResponse{}, spec.contractGas * DefaultGasMultiplier, spec.contractErr - } - - ctx, _ := parentCtx.CacheContext() - before := ctx.GasMeter().GasConsumed() - - // when - msg := wasmvmtypes.IBCChannelOpenMsg{ - OpenTry: &wasmvmtypes.IBCOpenTry{ - Channel: myChannel, - CounterpartyVersion: "foo", - }, - } - _, err := keepers.WasmKeeper.OnOpenChannel(ctx, spec.contractAddr, msg) - - // then - if spec.expErr { - require.Error(t, err) - return - } - require.NoError(t, err) - // verify gas consumed - const storageCosts = sdk.Gas(2903) - assert.Equal(t, spec.expGas, ctx.GasMeter().GasConsumed()-before-storageCosts) - }) - } -} - -func TestOnConnectChannel(t *testing.T) { - var m wasmtesting.MockWasmer - wasmtesting.MakeIBCInstantiable(&m) - messenger := &wasmtesting.MockMessageHandler{} - parentCtx, keepers := CreateTestInput(t, false, AvailableCapabilities, WithMessageHandler(messenger)) - example := SeedNewContractInstance(t, parentCtx, keepers, &m) - const myContractGas = 40 - - specs := map[string]struct { - contractAddr sdk.AccAddress - contractResp *wasmvmtypes.IBCBasicResponse - contractErr error - overwriteMessenger *wasmtesting.MockMessageHandler - expContractGas sdk.Gas - expErr bool - expEventTypes []string - }{ - "consume contract gas": { - contractAddr: example.Contract, - expContractGas: myContractGas, - contractResp: &wasmvmtypes.IBCBasicResponse{}, - }, - "consume gas on error, ignore events + messages": { - contractAddr: example.Contract, - expContractGas: myContractGas, - contractResp: &wasmvmtypes.IBCBasicResponse{ - Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}}, - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - }, - contractErr: errors.New("test, ignore"), - expErr: true, - }, - "dispatch contract messages on success": { - contractAddr: example.Contract, - expContractGas: myContractGas, - contractResp: &wasmvmtypes.IBCBasicResponse{ - Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}, {ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Custom: json.RawMessage(`{"foo":"bar"}`)}}}, - }, - }, - "emit contract events on success": { - contractAddr: example.Contract, - expContractGas: myContractGas + 10, - contractResp: &wasmvmtypes.IBCBasicResponse{ - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - }, - expEventTypes: []string{types.WasmModuleEventType}, - }, - "messenger errors returned, events stored": { - contractAddr: example.Contract, - expContractGas: myContractGas + 10, - contractResp: &wasmvmtypes.IBCBasicResponse{ - Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}, {ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Custom: json.RawMessage(`{"foo":"bar"}`)}}}, - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - }, - overwriteMessenger: wasmtesting.NewErroringMessageHandler(), - expErr: true, - expEventTypes: []string{types.WasmModuleEventType}, - }, - "unknown contract address": { - contractAddr: RandomAccountAddress(t), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - myChannel := wasmvmtypes.IBCChannel{Version: "my test channel"} - myMsg := wasmvmtypes.IBCChannelConnectMsg{OpenConfirm: &wasmvmtypes.IBCOpenConfirm{Channel: myChannel}} - m.IBCChannelConnectFn = func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCChannelConnectMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - assert.Equal(t, msg, myMsg) - return spec.contractResp, myContractGas * DefaultGasMultiplier, spec.contractErr - } - - ctx, _ := parentCtx.CacheContext() - ctx = ctx.WithEventManager(sdk.NewEventManager()) - - before := ctx.GasMeter().GasConsumed() - msger, capturedMsgs := wasmtesting.NewCapturingMessageHandler() - *messenger = *msger - if spec.overwriteMessenger != nil { - *messenger = *spec.overwriteMessenger - } - - // when - msg := wasmvmtypes.IBCChannelConnectMsg{ - OpenConfirm: &wasmvmtypes.IBCOpenConfirm{ - Channel: myChannel, - }, - } - - err := keepers.WasmKeeper.OnConnectChannel(ctx, spec.contractAddr, msg) - - // then - if spec.expErr { - require.Error(t, err) - assert.Empty(t, capturedMsgs) // no messages captured on error - assert.Equal(t, spec.expEventTypes, stripTypes(ctx.EventManager().Events())) - return - } - require.NoError(t, err) - // verify gas consumed - const storageCosts = sdk.Gas(2903) - assert.Equal(t, spec.expContractGas, ctx.GasMeter().GasConsumed()-before-storageCosts) - // verify msgs dispatched - require.Len(t, *capturedMsgs, len(spec.contractResp.Messages)) - for i, m := range spec.contractResp.Messages { - assert.Equal(t, (*capturedMsgs)[i], m.Msg) - } - assert.Equal(t, spec.expEventTypes, stripTypes(ctx.EventManager().Events())) - }) - } -} - -func TestOnCloseChannel(t *testing.T) { - var m wasmtesting.MockWasmer - wasmtesting.MakeIBCInstantiable(&m) - messenger := &wasmtesting.MockMessageHandler{} - parentCtx, keepers := CreateTestInput(t, false, AvailableCapabilities, WithMessageHandler(messenger)) - example := SeedNewContractInstance(t, parentCtx, keepers, &m) - const myContractGas = 40 - - specs := map[string]struct { - contractAddr sdk.AccAddress - contractResp *wasmvmtypes.IBCBasicResponse - contractErr error - overwriteMessenger *wasmtesting.MockMessageHandler - expContractGas sdk.Gas - expErr bool - expEventTypes []string - }{ - "consume contract gas": { - contractAddr: example.Contract, - expContractGas: myContractGas, - contractResp: &wasmvmtypes.IBCBasicResponse{}, - }, - "consume gas on error, ignore events + messages": { - contractAddr: example.Contract, - expContractGas: myContractGas, - contractResp: &wasmvmtypes.IBCBasicResponse{ - Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}}, - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - }, - contractErr: errors.New("test, ignore"), - expErr: true, - }, - "dispatch contract messages on success": { - contractAddr: example.Contract, - expContractGas: myContractGas, - contractResp: &wasmvmtypes.IBCBasicResponse{ - Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}, {ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Custom: json.RawMessage(`{"foo":"bar"}`)}}}, - }, - }, - "emit contract events on success": { - contractAddr: example.Contract, - expContractGas: myContractGas + 10, - contractResp: &wasmvmtypes.IBCBasicResponse{ - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - }, - expEventTypes: []string{types.WasmModuleEventType}, - }, - "messenger errors returned, events stored": { - contractAddr: example.Contract, - expContractGas: myContractGas + 10, - contractResp: &wasmvmtypes.IBCBasicResponse{ - Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}, {ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Custom: json.RawMessage(`{"foo":"bar"}`)}}}, - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - }, - overwriteMessenger: wasmtesting.NewErroringMessageHandler(), - expErr: true, - expEventTypes: []string{types.WasmModuleEventType}, - }, - "unknown contract address": { - contractAddr: RandomAccountAddress(t), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - myChannel := wasmvmtypes.IBCChannel{Version: "my test channel"} - myMsg := wasmvmtypes.IBCChannelCloseMsg{CloseInit: &wasmvmtypes.IBCCloseInit{Channel: myChannel}} - m.IBCChannelCloseFn = func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCChannelCloseMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - assert.Equal(t, msg, myMsg) - return spec.contractResp, myContractGas * DefaultGasMultiplier, spec.contractErr - } - - ctx, _ := parentCtx.CacheContext() - before := ctx.GasMeter().GasConsumed() - msger, capturedMsgs := wasmtesting.NewCapturingMessageHandler() - *messenger = *msger - - if spec.overwriteMessenger != nil { - *messenger = *spec.overwriteMessenger - } - - // when - msg := wasmvmtypes.IBCChannelCloseMsg{ - CloseInit: &wasmvmtypes.IBCCloseInit{ - Channel: myChannel, - }, - } - err := keepers.WasmKeeper.OnCloseChannel(ctx, spec.contractAddr, msg) - - // then - if spec.expErr { - require.Error(t, err) - assert.Empty(t, capturedMsgs) // no messages captured on error - assert.Equal(t, spec.expEventTypes, stripTypes(ctx.EventManager().Events())) - return - } - require.NoError(t, err) - // verify gas consumed - const storageCosts = sdk.Gas(2903) - assert.Equal(t, spec.expContractGas, ctx.GasMeter().GasConsumed()-before-storageCosts) - // verify msgs dispatched - require.Len(t, *capturedMsgs, len(spec.contractResp.Messages)) - for i, m := range spec.contractResp.Messages { - assert.Equal(t, (*capturedMsgs)[i], m.Msg) - } - assert.Equal(t, spec.expEventTypes, stripTypes(ctx.EventManager().Events())) - }) - } -} - -func TestOnRecvPacket(t *testing.T) { - var m wasmtesting.MockWasmer - wasmtesting.MakeIBCInstantiable(&m) - messenger := &wasmtesting.MockMessageHandler{} - parentCtx, keepers := CreateTestInput(t, false, AvailableCapabilities, WithMessageHandler(messenger)) - example := SeedNewContractInstance(t, parentCtx, keepers, &m) - const myContractGas = 40 - const storageCosts = sdk.Gas(2903) - - specs := map[string]struct { - contractAddr sdk.AccAddress - contractResp *wasmvmtypes.IBCReceiveResponse - contractErr error - overwriteMessenger *wasmtesting.MockMessageHandler - mockReplyFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, reply wasmvmtypes.Reply, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) - expContractGas sdk.Gas - expAck []byte - expErr bool - expPanic bool - expEventTypes []string - }{ - "consume contract gas": { - contractAddr: example.Contract, - expContractGas: myContractGas, - contractResp: &wasmvmtypes.IBCReceiveResponse{ - Acknowledgement: []byte("myAck"), - }, - expAck: []byte("myAck"), - }, - "can return empty ack": { - contractAddr: example.Contract, - expContractGas: myContractGas, - contractResp: &wasmvmtypes.IBCReceiveResponse{}, - }, - "consume gas on error, ignore events + messages": { - contractAddr: example.Contract, - expContractGas: myContractGas, - contractResp: &wasmvmtypes.IBCReceiveResponse{ - Acknowledgement: []byte("myAck"), - Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}}, - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - }, - contractErr: errors.New("test, ignore"), - expPanic: true, - }, - "dispatch contract messages on success": { - contractAddr: example.Contract, - expContractGas: myContractGas, - contractResp: &wasmvmtypes.IBCReceiveResponse{ - Acknowledgement: []byte("myAck"), - Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}, {ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Custom: json.RawMessage(`{"foo":"bar"}`)}}}, - }, - expAck: []byte("myAck"), - }, - "emit contract attributes on success": { - contractAddr: example.Contract, - expContractGas: myContractGas + 10, - contractResp: &wasmvmtypes.IBCReceiveResponse{ - Acknowledgement: []byte("myAck"), - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - }, - expEventTypes: []string{types.WasmModuleEventType}, - expAck: []byte("myAck"), - }, - "emit contract events on success": { - contractAddr: example.Contract, - expContractGas: myContractGas + 46, // charge or custom event as well - contractResp: &wasmvmtypes.IBCReceiveResponse{ - Acknowledgement: []byte("myAck"), - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - Events: []wasmvmtypes.Event{{ - Type: "custom", - Attributes: []wasmvmtypes.EventAttribute{{ - Key: "message", - Value: "to rudi", - }}, - }}, - }, - expEventTypes: []string{types.WasmModuleEventType, "wasm-custom"}, - expAck: []byte("myAck"), - }, - "messenger errors returned, events stored": { - contractAddr: example.Contract, - expContractGas: myContractGas + 10, - contractResp: &wasmvmtypes.IBCReceiveResponse{ - Acknowledgement: []byte("myAck"), - Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}, {ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Custom: json.RawMessage(`{"foo":"bar"}`)}}}, - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - }, - overwriteMessenger: wasmtesting.NewErroringMessageHandler(), - expErr: true, - expEventTypes: []string{types.WasmModuleEventType}, - }, - "submessage reply can overwrite ack data": { - contractAddr: example.Contract, - expContractGas: myContractGas + storageCosts, - contractResp: &wasmvmtypes.IBCReceiveResponse{ - Acknowledgement: []byte("myAck"), - Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyAlways, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}}, - }, - mockReplyFn: func(codeID wasmvm.Checksum, env wasmvmtypes.Env, reply wasmvmtypes.Reply, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - return &wasmvmtypes.Response{Data: []byte("myBetterAck")}, 0, nil - }, - expAck: []byte("myBetterAck"), - expEventTypes: []string{types.EventTypeReply}, - }, - "unknown contract address": { - contractAddr: RandomAccountAddress(t), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - myPacket := wasmvmtypes.IBCPacket{Data: []byte("my data")} - - m.IBCPacketReceiveFn = func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCPacketReceiveMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCReceiveResult, uint64, error) { - assert.Equal(t, myPacket, msg.Packet) - return &wasmvmtypes.IBCReceiveResult{Ok: spec.contractResp}, myContractGas * DefaultGasMultiplier, spec.contractErr - } - if spec.mockReplyFn != nil { - m.ReplyFn = spec.mockReplyFn - h, ok := keepers.WasmKeeper.wasmVMResponseHandler.(*DefaultWasmVMContractResponseHandler) - require.True(t, ok) - h.md = NewMessageDispatcher(messenger, keepers.WasmKeeper) - } - - ctx, _ := parentCtx.CacheContext() - before := ctx.GasMeter().GasConsumed() - - msger, capturedMsgs := wasmtesting.NewCapturingMessageHandler() - *messenger = *msger - - if spec.overwriteMessenger != nil { - *messenger = *spec.overwriteMessenger - } - - // when - msg := wasmvmtypes.IBCPacketReceiveMsg{Packet: myPacket} - if spec.expPanic { - assert.Panics(t, func() { - keepers.WasmKeeper.OnRecvPacket(ctx, spec.contractAddr, msg) //nolint:errcheck // we are checking for a panic here - }) - return - } - gotAck, err := keepers.WasmKeeper.OnRecvPacket(ctx, spec.contractAddr, msg) - - // then - if spec.expErr { - require.Error(t, err) - assert.Empty(t, capturedMsgs) // no messages captured on error - assert.Equal(t, spec.expEventTypes, stripTypes(ctx.EventManager().Events())) - return - } - require.NoError(t, err) - require.Equal(t, spec.expAck, gotAck) - - // verify gas consumed - const storageCosts = sdk.Gas(2903) - assert.Equal(t, spec.expContractGas, ctx.GasMeter().GasConsumed()-before-storageCosts) - // verify msgs dispatched - require.Len(t, *capturedMsgs, len(spec.contractResp.Messages)) - for i, m := range spec.contractResp.Messages { - assert.Equal(t, (*capturedMsgs)[i], m.Msg) - } - assert.Equal(t, spec.expEventTypes, stripTypes(ctx.EventManager().Events())) - }) - } -} - -func TestOnAckPacket(t *testing.T) { - var m wasmtesting.MockWasmer - wasmtesting.MakeIBCInstantiable(&m) - messenger := &wasmtesting.MockMessageHandler{} - parentCtx, keepers := CreateTestInput(t, false, AvailableCapabilities, WithMessageHandler(messenger)) - example := SeedNewContractInstance(t, parentCtx, keepers, &m) - const myContractGas = 40 - - specs := map[string]struct { - contractAddr sdk.AccAddress - contractResp *wasmvmtypes.IBCBasicResponse - contractErr error - overwriteMessenger *wasmtesting.MockMessageHandler - expContractGas sdk.Gas - expErr bool - expEventTypes []string - }{ - "consume contract gas": { - contractAddr: example.Contract, - expContractGas: myContractGas, - contractResp: &wasmvmtypes.IBCBasicResponse{}, - }, - "consume gas on error, ignore events + messages": { - contractAddr: example.Contract, - expContractGas: myContractGas, - contractResp: &wasmvmtypes.IBCBasicResponse{ - Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}}, - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - }, - contractErr: errors.New("test, ignore"), - expErr: true, - }, - "dispatch contract messages on success": { - contractAddr: example.Contract, - expContractGas: myContractGas, - contractResp: &wasmvmtypes.IBCBasicResponse{ - Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}, {ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Custom: json.RawMessage(`{"foo":"bar"}`)}}}, - }, - }, - "emit contract events on success": { - contractAddr: example.Contract, - expContractGas: myContractGas + 10, - contractResp: &wasmvmtypes.IBCBasicResponse{ - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - }, - expEventTypes: []string{types.WasmModuleEventType}, - }, - "messenger errors returned, events stored": { - contractAddr: example.Contract, - expContractGas: myContractGas + 10, - contractResp: &wasmvmtypes.IBCBasicResponse{ - Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}, {ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Custom: json.RawMessage(`{"foo":"bar"}`)}}}, - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - }, - overwriteMessenger: wasmtesting.NewErroringMessageHandler(), - expErr: true, - expEventTypes: []string{types.WasmModuleEventType}, - }, - "unknown contract address": { - contractAddr: RandomAccountAddress(t), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - myAck := wasmvmtypes.IBCPacketAckMsg{Acknowledgement: wasmvmtypes.IBCAcknowledgement{Data: []byte("myAck")}} - m.IBCPacketAckFn = func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCPacketAckMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - assert.Equal(t, myAck, msg) - return spec.contractResp, myContractGas * DefaultGasMultiplier, spec.contractErr - } - - ctx, _ := parentCtx.CacheContext() - before := ctx.GasMeter().GasConsumed() - msger, capturedMsgs := wasmtesting.NewCapturingMessageHandler() - *messenger = *msger - - if spec.overwriteMessenger != nil { - *messenger = *spec.overwriteMessenger - } - - // when - err := keepers.WasmKeeper.OnAckPacket(ctx, spec.contractAddr, myAck) - - // then - - if spec.expErr { - require.Error(t, err) - assert.Empty(t, capturedMsgs) // no messages captured on error - assert.Equal(t, spec.expEventTypes, stripTypes(ctx.EventManager().Events())) - return - } - require.NoError(t, err) - // verify gas consumed - const storageCosts = sdk.Gas(2903) - assert.Equal(t, spec.expContractGas, ctx.GasMeter().GasConsumed()-before-storageCosts) - // verify msgs dispatched - require.Len(t, *capturedMsgs, len(spec.contractResp.Messages)) - for i, m := range spec.contractResp.Messages { - assert.Equal(t, (*capturedMsgs)[i], m.Msg) - } - assert.Equal(t, spec.expEventTypes, stripTypes(ctx.EventManager().Events())) - }) - } -} - -func TestOnTimeoutPacket(t *testing.T) { - var m wasmtesting.MockWasmer - wasmtesting.MakeIBCInstantiable(&m) - messenger := &wasmtesting.MockMessageHandler{} - parentCtx, keepers := CreateTestInput(t, false, AvailableCapabilities, WithMessageHandler(messenger)) - example := SeedNewContractInstance(t, parentCtx, keepers, &m) - const myContractGas = 40 - - specs := map[string]struct { - contractAddr sdk.AccAddress - contractResp *wasmvmtypes.IBCBasicResponse - contractErr error - overwriteMessenger *wasmtesting.MockMessageHandler - expContractGas sdk.Gas - expErr bool - expEventTypes []string - }{ - "consume contract gas": { - contractAddr: example.Contract, - expContractGas: myContractGas, - contractResp: &wasmvmtypes.IBCBasicResponse{}, - }, - "consume gas on error, ignore events + messages": { - contractAddr: example.Contract, - expContractGas: myContractGas, - contractResp: &wasmvmtypes.IBCBasicResponse{ - Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}}, - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - }, - contractErr: errors.New("test, ignore"), - expErr: true, - }, - "dispatch contract messages on success": { - contractAddr: example.Contract, - expContractGas: myContractGas, - contractResp: &wasmvmtypes.IBCBasicResponse{ - Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}, {ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Custom: json.RawMessage(`{"foo":"bar"}`)}}}, - }, - }, - "emit contract attributes on success": { - contractAddr: example.Contract, - expContractGas: myContractGas + 10, - contractResp: &wasmvmtypes.IBCBasicResponse{ - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - }, - expEventTypes: []string{types.WasmModuleEventType}, - }, - "emit contract events on success": { - contractAddr: example.Contract, - expContractGas: myContractGas + 46, // cost for custom events - contractResp: &wasmvmtypes.IBCBasicResponse{ - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - Events: []wasmvmtypes.Event{{ - Type: "custom", - Attributes: []wasmvmtypes.EventAttribute{{ - Key: "message", - Value: "to rudi", - }}, - }}, - }, - expEventTypes: []string{types.WasmModuleEventType, "wasm-custom"}, - }, - "messenger errors returned, events stored before": { - contractAddr: example.Contract, - expContractGas: myContractGas + 10, - contractResp: &wasmvmtypes.IBCBasicResponse{ - Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}, {ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Custom: json.RawMessage(`{"foo":"bar"}`)}}}, - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - }, - overwriteMessenger: wasmtesting.NewErroringMessageHandler(), - expErr: true, - expEventTypes: []string{types.WasmModuleEventType}, - }, - "unknown contract address": { - contractAddr: RandomAccountAddress(t), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - myPacket := wasmvmtypes.IBCPacket{Data: []byte("my test packet")} - m.IBCPacketTimeoutFn = func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCPacketTimeoutMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - assert.Equal(t, myPacket, msg.Packet) - return spec.contractResp, myContractGas * DefaultGasMultiplier, spec.contractErr - } - - ctx, _ := parentCtx.CacheContext() - before := ctx.GasMeter().GasConsumed() - msger, capturedMsgs := wasmtesting.NewCapturingMessageHandler() - *messenger = *msger - - if spec.overwriteMessenger != nil { - *messenger = *spec.overwriteMessenger - } - - // when - msg := wasmvmtypes.IBCPacketTimeoutMsg{Packet: myPacket} - err := keepers.WasmKeeper.OnTimeoutPacket(ctx, spec.contractAddr, msg) - - // then - if spec.expErr { - require.Error(t, err) - assert.Empty(t, capturedMsgs) // no messages captured on error - assert.Equal(t, spec.expEventTypes, stripTypes(ctx.EventManager().Events())) - return - } - require.NoError(t, err) - // verify gas consumed - const storageCosts = sdk.Gas(2903) - assert.Equal(t, spec.expContractGas, ctx.GasMeter().GasConsumed()-before-storageCosts) - // verify msgs dispatched - require.Len(t, *capturedMsgs, len(spec.contractResp.Messages)) - for i, m := range spec.contractResp.Messages { - assert.Equal(t, (*capturedMsgs)[i], m.Msg) - } - assert.Equal(t, spec.expEventTypes, stripTypes(ctx.EventManager().Events())) - }) - } -} - -func stripTypes(events sdk.Events) []string { - var r []string - for _, e := range events { - r = append(r, e.Type) - } - return r -} diff --git a/x/wasm/keeper/snapshotter.go b/x/wasm/keeper/snapshotter.go deleted file mode 100644 index 3642c51..0000000 --- a/x/wasm/keeper/snapshotter.go +++ /dev/null @@ -1,141 +0,0 @@ -package keeper - -import ( - "encoding/hex" - "io" - - errorsmod "cosmossdk.io/errors" - "github.com/cometbft/cometbft/libs/log" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - snapshot "github.com/cosmos/cosmos-sdk/snapshots/types" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/terpnetwork/terp-core/x/wasm/ioutils" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -var _ snapshot.ExtensionSnapshotter = &WasmSnapshotter{} - -// SnapshotFormat format 1 is just gzipped wasm byte code for each item payload. No protobuf envelope, no metadata. -const SnapshotFormat = 1 - -type WasmSnapshotter struct { - wasm *Keeper - cms sdk.MultiStore -} - -func NewWasmSnapshotter(cms sdk.MultiStore, wasm *Keeper) *WasmSnapshotter { - return &WasmSnapshotter{ - wasm: wasm, - cms: cms, - } -} - -func (ws *WasmSnapshotter) SnapshotName() string { - return types.ModuleName -} - -func (ws *WasmSnapshotter) SnapshotFormat() uint32 { - return SnapshotFormat -} - -func (ws *WasmSnapshotter) SupportedFormats() []uint32 { - // If we support older formats, add them here and handle them in Restore - return []uint32{SnapshotFormat} -} - -func (ws *WasmSnapshotter) SnapshotExtension(height uint64, payloadWriter snapshot.ExtensionPayloadWriter) error { - cacheMS, err := ws.cms.CacheMultiStoreWithVersion(int64(height)) - if err != nil { - return err - } - - ctx := sdk.NewContext(cacheMS, tmproto.Header{}, false, log.NewNopLogger()) - seenBefore := make(map[string]bool) - var rerr error - - ws.wasm.IterateCodeInfos(ctx, func(id uint64, info types.CodeInfo) bool { - // Many code ids may point to the same code hash... only sync it once - hexHash := hex.EncodeToString(info.CodeHash) - // if seenBefore, just skip this one and move to the next - if seenBefore[hexHash] { - return false - } - seenBefore[hexHash] = true - - // load code and abort on error - wasmBytes, err := ws.wasm.GetByteCode(ctx, id) - if err != nil { - rerr = err - return true - } - - compressedWasm, err := ioutils.GzipIt(wasmBytes) - if err != nil { - rerr = err - return true - } - - err = payloadWriter(compressedWasm) - if err != nil { - rerr = err - return true - } - - return false - }) - - return rerr -} - -func (ws *WasmSnapshotter) RestoreExtension(height uint64, format uint32, payloadReader snapshot.ExtensionPayloadReader) error { - if format == SnapshotFormat { - return ws.processAllItems(height, payloadReader, restoreV1, finalizeV1) - } - return snapshot.ErrUnknownFormat -} - -func restoreV1(_ sdk.Context, k *Keeper, compressedCode []byte) error { - if !ioutils.IsGzip(compressedCode) { - return types.ErrInvalid.Wrap("not a gzip") - } - wasmCode, err := ioutils.Uncompress(compressedCode, uint64(types.MaxWasmSize)) - if err != nil { - return errorsmod.Wrap(types.ErrCreateFailed, err.Error()) - } - - // FIXME: check which codeIDs the checksum matches?? - _, err = k.wasmVM.Create(wasmCode) - if err != nil { - return errorsmod.Wrap(types.ErrCreateFailed, err.Error()) - } - return nil -} - -func finalizeV1(ctx sdk.Context, k *Keeper) error { - // FIXME: ensure all codes have been uploaded? - return k.InitializePinnedCodes(ctx) -} - -func (ws *WasmSnapshotter) processAllItems( - height uint64, - payloadReader snapshot.ExtensionPayloadReader, - cb func(sdk.Context, *Keeper, []byte) error, - finalize func(sdk.Context, *Keeper) error, -) error { - ctx := sdk.NewContext(ws.cms, tmproto.Header{Height: int64(height)}, false, log.NewNopLogger()) - for { - payload, err := payloadReader() - if err == io.EOF { - break - } else if err != nil { - return err - } - - if err := cb(ctx, ws.wasm, payload); err != nil { - return errorsmod.Wrap(err, "processing snapshot item") - } - } - - return finalize(ctx, ws.wasm) -} diff --git a/x/wasm/keeper/snapshotter_integration_test.go b/x/wasm/keeper/snapshotter_integration_test.go deleted file mode 100644 index 2925f09..0000000 --- a/x/wasm/keeper/snapshotter_integration_test.go +++ /dev/null @@ -1,124 +0,0 @@ -package keeper_test - -import ( - "crypto/sha256" - "os" - "testing" - "time" - - "github.com/terpnetwork/terp-core/x/wasm/types" - - "github.com/stretchr/testify/assert" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtypes "github.com/cometbft/cometbft/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/app" - "github.com/terpnetwork/terp-core/x/wasm/keeper" -) - -func TestSnapshotter(t *testing.T) { - specs := map[string]struct { - wasmFiles []string - }{ - "single contract": { - wasmFiles: []string{"./testdata/reflect.wasm"}, - }, - "multiple contract": { - wasmFiles: []string{"./testdata/reflect.wasm", "./testdata/burner.wasm", "./testdata/reflect.wasm"}, - }, - "duplicate contracts": { - wasmFiles: []string{"./testdata/reflect.wasm", "./testdata/reflect.wasm"}, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - // setup source app - srcTerpApp, genesisAddr := newWasmExampleApp(t) - - // store wasm codes on chain - ctx := srcTerpApp.NewUncachedContext(false, tmproto.Header{ - ChainID: "foo", - Height: srcTerpApp.LastBlockHeight() + 1, - Time: time.Now(), - }) - wasmKeeper := srcTerpApp.WasmKeeper - contractKeeper := keeper.NewDefaultPermissionKeeper(&wasmKeeper) - - srcCodeIDToChecksum := make(map[uint64][]byte, len(spec.wasmFiles)) - for i, v := range spec.wasmFiles { - wasmCode, err := os.ReadFile(v) - require.NoError(t, err) - codeID, checksum, err := contractKeeper.Create(ctx, genesisAddr, wasmCode, nil) - require.NoError(t, err) - require.Equal(t, uint64(i+1), codeID) - srcCodeIDToChecksum[codeID] = checksum - } - // create snapshot - srcTerpApp.Commit() - snapshotHeight := uint64(srcTerpApp.LastBlockHeight()) - snapshot, err := srcTerpApp.SnapshotManager().Create(snapshotHeight) - require.NoError(t, err) - assert.NotNil(t, snapshot) - - // when snapshot imported into dest app instance - destTerpApp := app.SetupWithEmptyStore(t) - require.NoError(t, destTerpApp.SnapshotManager().Restore(*snapshot)) - for i := uint32(0); i < snapshot.Chunks; i++ { - chunkBz, err := srcTerpApp.SnapshotManager().LoadChunk(snapshot.Height, snapshot.Format, i) - require.NoError(t, err) - end, err := destTerpApp.SnapshotManager().RestoreChunk(chunkBz) - require.NoError(t, err) - if end { - break - } - } - - // then all wasm contracts are imported - wasmKeeper = destTerpApp.WasmKeeper - ctx = destTerpApp.NewUncachedContext(false, tmproto.Header{ - ChainID: "foo", - Height: destTerpApp.LastBlockHeight() + 1, - Time: time.Now(), - }) - - destCodeIDToChecksum := make(map[uint64][]byte, len(spec.wasmFiles)) - wasmKeeper.IterateCodeInfos(ctx, func(id uint64, info types.CodeInfo) bool { - bz, err := wasmKeeper.GetByteCode(ctx, id) - require.NoError(t, err) - hash := sha256.Sum256(bz) - destCodeIDToChecksum[id] = hash[:] - assert.Equal(t, hash[:], info.CodeHash) - return false - }) - assert.Equal(t, srcCodeIDToChecksum, destCodeIDToChecksum) - }) - } -} - -func newWasmExampleApp(t *testing.T) (*app.TerpApp, sdk.AccAddress) { - senderPrivKey := ed25519.GenPrivKey() - pubKey, err := cryptocodec.ToTmPubKeyInterface(senderPrivKey.PubKey()) - require.NoError(t, err) - - senderAddr := senderPrivKey.PubKey().Address().Bytes() - acc := authtypes.NewBaseAccount(senderAddr, senderPrivKey.PubKey(), 0, 0) - amount, ok := sdk.NewIntFromString("10000000000000000000") - require.True(t, ok) - - balance := banktypes.Balance{ - Address: acc.GetAddress().String(), - Coins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, amount)), - } - validator := tmtypes.NewValidator(pubKey, 1) - valSet := tmtypes.NewValidatorSet([]*tmtypes.Validator{validator}) - wasmApp := app.SetupWithGenesisValSet(t, valSet, []authtypes.GenesisAccount{acc}, "testing", nil, balance) - - return wasmApp, senderAddr -} diff --git a/x/wasm/keeper/staking_test.go b/x/wasm/keeper/staking_test.go deleted file mode 100644 index eb26f9c..0000000 --- a/x/wasm/keeper/staking_test.go +++ /dev/null @@ -1,739 +0,0 @@ -package keeper - -import ( - "encoding/json" - "os" - "testing" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" - sdk "github.com/cosmos/cosmos-sdk/types" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - distributionkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" - "github.com/cosmos/cosmos-sdk/x/staking" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/keeper/testdata" - wasmtypes "github.com/terpnetwork/terp-core/x/wasm/types" -) - -type StakingInitMsg struct { - Name string `json:"name"` - Symbol string `json:"symbol"` - Decimals uint8 `json:"decimals"` - Validator sdk.ValAddress `json:"validator"` - ExitTax sdk.Dec `json:"exit_tax"` - // MinWithdrawal is uint128 encoded as a string (use math.Int?) - MinWithdrawl string `json:"min_withdrawal"` -} - -// StakingHandleMsg is used to encode handle messages -type StakingHandleMsg struct { - Transfer *transferPayload `json:"transfer,omitempty"` - Bond *struct{} `json:"bond,omitempty"` - Unbond *unbondPayload `json:"unbond,omitempty"` - Claim *struct{} `json:"claim,omitempty"` - Reinvest *struct{} `json:"reinvest,omitempty"` - Change *testdata.OwnerPayload `json:"change_owner,omitempty"` -} - -type transferPayload struct { - Recipient sdk.Address `json:"recipient"` - // uint128 encoded as string - Amount string `json:"amount"` -} - -type unbondPayload struct { - // uint128 encoded as string - Amount string `json:"amount"` -} - -// StakingQueryMsg is used to encode query messages -type StakingQueryMsg struct { - Balance *addressQuery `json:"balance,omitempty"` - Claims *addressQuery `json:"claims,omitempty"` - TokenInfo *struct{} `json:"token_info,omitempty"` - Investment *struct{} `json:"investment,omitempty"` -} - -type addressQuery struct { - Address sdk.AccAddress `json:"address"` -} - -type BalanceResponse struct { - Balance string `json:"balance,omitempty"` -} - -type ClaimsResponse struct { - Claims string `json:"claims,omitempty"` -} - -type TokenInfoResponse struct { - Name string `json:"name"` - Symbol string `json:"symbol"` - Decimals uint8 `json:"decimals"` -} - -type InvestmentResponse struct { - TokenSupply string `json:"token_supply"` - StakedTokens sdk.Coin `json:"staked_tokens"` - NominalValue sdk.Dec `json:"nominal_value"` - Owner sdk.AccAddress `json:"owner"` - Validator sdk.ValAddress `json:"validator"` - ExitTax sdk.Dec `json:"exit_tax"` - // MinWithdrawl is uint128 encoded as a string (use math.Int?) - MinWithdrawl string `json:"min_withdrawal"` -} - -func TestInitializeStaking(t *testing.T) { - ctx, k := CreateTestInput(t, false, AvailableCapabilities) - accKeeper, stakingKeeper, keeper, bankKeeper := k.AccountKeeper, k.StakingKeeper, k.ContractKeeper, k.BankKeeper - - valAddr := addValidator(t, ctx, stakingKeeper, k.Faucet, sdk.NewInt64Coin("stake", 1234567)) - ctx = nextBlock(ctx, stakingKeeper) - v, found := stakingKeeper.GetValidator(ctx, valAddr) - assert.True(t, found) - assert.Equal(t, v.GetDelegatorShares(), sdk.NewDec(1234567)) - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000), sdk.NewInt64Coin("stake", 500000)) - creator := k.Faucet.NewFundedRandomAccount(ctx, deposit...) - - // upload staking derivates code - stakingCode, err := os.ReadFile("./testdata/staking.wasm") - require.NoError(t, err) - stakingID, _, err := keeper.Create(ctx, creator, stakingCode, nil) - require.NoError(t, err) - require.Equal(t, uint64(1), stakingID) - - // register to a valid address - initMsg := StakingInitMsg{ - Name: "Staking Derivatives", - Symbol: "DRV", - Decimals: 0, - Validator: valAddr, - ExitTax: sdk.MustNewDecFromStr("0.10"), - MinWithdrawl: "100", - } - initBz, err := json.Marshal(&initMsg) - require.NoError(t, err) - - stakingAddr, _, err := k.ContractKeeper.Instantiate(ctx, stakingID, creator, nil, initBz, "staking derivates - DRV", nil) - require.NoError(t, err) - require.NotEmpty(t, stakingAddr) - - // nothing spent here - checkAccount(t, ctx, accKeeper, bankKeeper, creator, deposit) - - // try to register with a validator not on the list and it fails - _, bob := keyPubAddr() - badInitMsg := StakingInitMsg{ - Name: "Missing Validator", - Symbol: "MISS", - Decimals: 0, - Validator: sdk.ValAddress(bob), - ExitTax: sdk.MustNewDecFromStr("0.10"), - MinWithdrawl: "100", - } - badBz, err := json.Marshal(&badInitMsg) - require.NoError(t, err) - - _, _, err = k.ContractKeeper.Instantiate(ctx, stakingID, creator, nil, badBz, "missing validator", nil) - require.Error(t, err) - - // no changes to bonding shares - val, _ := stakingKeeper.GetValidator(ctx, valAddr) - assert.Equal(t, val.GetDelegatorShares(), sdk.NewDec(1234567)) -} - -type initInfo struct { - valAddr sdk.ValAddress - creator sdk.AccAddress - contractAddr sdk.AccAddress - - ctx sdk.Context - accKeeper authkeeper.AccountKeeper - stakingKeeper *stakingkeeper.Keeper - distKeeper distributionkeeper.Keeper - wasmKeeper Keeper - contractKeeper wasmtypes.ContractOpsKeeper - bankKeeper bankkeeper.Keeper - faucet *TestFaucet -} - -func initializeStaking(t *testing.T) initInfo { - ctx, k := CreateTestInput(t, false, AvailableCapabilities) - accKeeper, stakingKeeper, keeper, bankKeeper := k.AccountKeeper, k.StakingKeeper, k.WasmKeeper, k.BankKeeper - - valAddr := addValidator(t, ctx, stakingKeeper, k.Faucet, sdk.NewInt64Coin("stake", 1000000)) - ctx = nextBlock(ctx, stakingKeeper) - - v, found := stakingKeeper.GetValidator(ctx, valAddr) - assert.True(t, found) - assert.Equal(t, v.GetDelegatorShares(), sdk.NewDec(1000000)) - assert.Equal(t, v.Status, stakingtypes.Bonded) - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000), sdk.NewInt64Coin("stake", 500000)) - creator := k.Faucet.NewFundedRandomAccount(ctx, deposit...) - - // upload staking derivates code - stakingCode, err := os.ReadFile("./testdata/staking.wasm") - require.NoError(t, err) - stakingID, _, err := k.ContractKeeper.Create(ctx, creator, stakingCode, nil) - require.NoError(t, err) - require.Equal(t, uint64(1), stakingID) - - // register to a valid address - initMsg := StakingInitMsg{ - Name: "Staking Derivatives", - Symbol: "DRV", - Decimals: 0, - Validator: valAddr, - ExitTax: sdk.MustNewDecFromStr("0.10"), - MinWithdrawl: "100", - } - initBz, err := json.Marshal(&initMsg) - require.NoError(t, err) - - stakingAddr, _, err := k.ContractKeeper.Instantiate(ctx, stakingID, creator, nil, initBz, "staking derivates - DRV", nil) - require.NoError(t, err) - require.NotEmpty(t, stakingAddr) - - return initInfo{ - valAddr: valAddr, - creator: creator, - contractAddr: stakingAddr, - ctx: ctx, - accKeeper: accKeeper, - stakingKeeper: stakingKeeper, - wasmKeeper: *keeper, - distKeeper: k.DistKeeper, - bankKeeper: bankKeeper, - contractKeeper: k.ContractKeeper, - faucet: k.Faucet, - } -} - -func TestBonding(t *testing.T) { - initInfo := initializeStaking(t) - ctx, valAddr, contractAddr := initInfo.ctx, initInfo.valAddr, initInfo.contractAddr - keeper, stakingKeeper, accKeeper, bankKeeper := initInfo.wasmKeeper, initInfo.stakingKeeper, initInfo.accKeeper, initInfo.bankKeeper - - // initial checks of bonding state - val, found := stakingKeeper.GetValidator(ctx, valAddr) - require.True(t, found) - initPower := val.GetDelegatorShares() - - // bob has 160k, putting 80k into the contract - full := sdk.NewCoins(sdk.NewInt64Coin("stake", 160000)) - funds := sdk.NewCoins(sdk.NewInt64Coin("stake", 80000)) - bob := initInfo.faucet.NewFundedRandomAccount(ctx, full...) - - // check contract state before - assertBalance(t, ctx, keeper, contractAddr, bob, "0") - assertClaims(t, ctx, keeper, contractAddr, bob, "0") - assertSupply(t, ctx, keeper, contractAddr, "0", sdk.NewInt64Coin("stake", 0)) - - bond := StakingHandleMsg{ - Bond: &struct{}{}, - } - bondBz, err := json.Marshal(bond) - require.NoError(t, err) - _, err = initInfo.contractKeeper.Execute(ctx, contractAddr, bob, bondBz, funds) - require.NoError(t, err) - - // check some account values - the money is on neither account (cuz it is bonded) - checkAccount(t, ctx, accKeeper, bankKeeper, contractAddr, sdk.Coins{}) - checkAccount(t, ctx, accKeeper, bankKeeper, bob, funds) - - // make sure the proper number of tokens have been bonded - val, _ = stakingKeeper.GetValidator(ctx, valAddr) - finalPower := val.GetDelegatorShares() - assert.Equal(t, sdk.NewInt(80000), finalPower.Sub(initPower).TruncateInt()) - - // check the delegation itself - d, found := stakingKeeper.GetDelegation(ctx, contractAddr, valAddr) - require.True(t, found) - assert.Equal(t, d.Shares, sdk.MustNewDecFromStr("80000")) - - // check we have the desired balance - assertBalance(t, ctx, keeper, contractAddr, bob, "80000") - assertClaims(t, ctx, keeper, contractAddr, bob, "0") - assertSupply(t, ctx, keeper, contractAddr, "80000", sdk.NewInt64Coin("stake", 80000)) -} - -func TestUnbonding(t *testing.T) { - initInfo := initializeStaking(t) - ctx, valAddr, contractAddr := initInfo.ctx, initInfo.valAddr, initInfo.contractAddr - keeper, stakingKeeper, accKeeper, bankKeeper := initInfo.wasmKeeper, initInfo.stakingKeeper, initInfo.accKeeper, initInfo.bankKeeper - - // initial checks of bonding state - val, found := stakingKeeper.GetValidator(ctx, valAddr) - require.True(t, found) - initPower := val.GetDelegatorShares() - - // bob has 160k, putting 80k into the contract - full := sdk.NewCoins(sdk.NewInt64Coin("stake", 160000)) - funds := sdk.NewCoins(sdk.NewInt64Coin("stake", 80000)) - bob := initInfo.faucet.NewFundedRandomAccount(ctx, full...) - - bond := StakingHandleMsg{ - Bond: &struct{}{}, - } - bondBz, err := json.Marshal(bond) - require.NoError(t, err) - _, err = initInfo.contractKeeper.Execute(ctx, contractAddr, bob, bondBz, funds) - require.NoError(t, err) - - // update height a bit - ctx = nextBlock(ctx, stakingKeeper) - - // now unbond 30k - note that 3k (10%) goes to the owner as a tax, 27k unbonded and available as claims - unbond := StakingHandleMsg{ - Unbond: &unbondPayload{ - Amount: "30000", - }, - } - unbondBz, err := json.Marshal(unbond) - require.NoError(t, err) - _, err = initInfo.contractKeeper.Execute(ctx, contractAddr, bob, unbondBz, nil) - require.NoError(t, err) - - // check some account values - the money is on neither account (cuz it is bonded) - // Note: why is this immediate? just test setup? - checkAccount(t, ctx, accKeeper, bankKeeper, contractAddr, sdk.Coins{}) - checkAccount(t, ctx, accKeeper, bankKeeper, bob, funds) - - // make sure the proper number of tokens have been bonded (80k - 27k = 53k) - val, _ = stakingKeeper.GetValidator(ctx, valAddr) - finalPower := val.GetDelegatorShares() - assert.Equal(t, sdk.NewInt(53000), finalPower.Sub(initPower).TruncateInt(), finalPower.String()) - - // check the delegation itself - d, found := stakingKeeper.GetDelegation(ctx, contractAddr, valAddr) - require.True(t, found) - assert.Equal(t, d.Shares, sdk.MustNewDecFromStr("53000")) - - // check there is unbonding in progress - un, found := stakingKeeper.GetUnbondingDelegation(ctx, contractAddr, valAddr) - require.True(t, found) - require.Equal(t, 1, len(un.Entries)) - assert.Equal(t, "27000", un.Entries[0].Balance.String()) - - // check we have the desired balance - assertBalance(t, ctx, keeper, contractAddr, bob, "50000") - assertBalance(t, ctx, keeper, contractAddr, initInfo.creator, "3000") - assertClaims(t, ctx, keeper, contractAddr, bob, "27000") - assertSupply(t, ctx, keeper, contractAddr, "53000", sdk.NewInt64Coin("stake", 53000)) -} - -func TestReinvest(t *testing.T) { - initInfo := initializeStaking(t) - ctx, valAddr, contractAddr := initInfo.ctx, initInfo.valAddr, initInfo.contractAddr - keeper, stakingKeeper, accKeeper, bankKeeper := initInfo.wasmKeeper, initInfo.stakingKeeper, initInfo.accKeeper, initInfo.bankKeeper - distKeeper := initInfo.distKeeper - - // initial checks of bonding state - val, found := stakingKeeper.GetValidator(ctx, valAddr) - require.True(t, found) - initPower := val.GetDelegatorShares() - assert.Equal(t, val.Tokens, sdk.NewInt(1000000), "%s", val.Tokens) - - // full is 2x funds, 1x goes to the contract, other stays on his wallet - full := sdk.NewCoins(sdk.NewInt64Coin("stake", 400000)) - funds := sdk.NewCoins(sdk.NewInt64Coin("stake", 200000)) - bob := initInfo.faucet.NewFundedRandomAccount(ctx, full...) - - // we will stake 200k to a validator with 1M self-bond - // this means we should get 1/6 of the rewards - bond := StakingHandleMsg{ - Bond: &struct{}{}, - } - bondBz, err := json.Marshal(bond) - require.NoError(t, err) - _, err = initInfo.contractKeeper.Execute(ctx, contractAddr, bob, bondBz, funds) - require.NoError(t, err) - - // update height a bit to solidify the delegation - ctx = nextBlock(ctx, stakingKeeper) - // we get 1/6, our share should be 40k minus 10% commission = 36k - setValidatorRewards(ctx, stakingKeeper, distKeeper, valAddr, "240000") - - // this should withdraw our outstanding 36k of rewards and reinvest them in the same delegation - reinvest := StakingHandleMsg{ - Reinvest: &struct{}{}, - } - reinvestBz, err := json.Marshal(reinvest) - require.NoError(t, err) - _, err = initInfo.contractKeeper.Execute(ctx, contractAddr, bob, reinvestBz, nil) - require.NoError(t, err) - - // check some account values - the money is on neither account (cuz it is bonded) - // Note: why is this immediate? just test setup? - checkAccount(t, ctx, accKeeper, bankKeeper, contractAddr, sdk.Coins{}) - checkAccount(t, ctx, accKeeper, bankKeeper, bob, funds) - - // check the delegation itself - d, found := stakingKeeper.GetDelegation(ctx, contractAddr, valAddr) - require.True(t, found) - // we started with 200k and added 36k - assert.Equal(t, d.Shares, sdk.MustNewDecFromStr("236000")) - - // make sure the proper number of tokens have been bonded (80k + 40k = 120k) - val, _ = stakingKeeper.GetValidator(ctx, valAddr) - finalPower := val.GetDelegatorShares() - assert.Equal(t, sdk.NewInt(236000), finalPower.Sub(initPower).TruncateInt(), finalPower.String()) - - // check there is no unbonding in progress - un, found := stakingKeeper.GetUnbondingDelegation(ctx, contractAddr, valAddr) - assert.False(t, found, "%#v", un) - - // check we have the desired balance - assertBalance(t, ctx, keeper, contractAddr, bob, "200000") - assertBalance(t, ctx, keeper, contractAddr, initInfo.creator, "0") - assertClaims(t, ctx, keeper, contractAddr, bob, "0") - assertSupply(t, ctx, keeper, contractAddr, "200000", sdk.NewInt64Coin("stake", 236000)) -} - -func TestQueryStakingInfo(t *testing.T) { - // STEP 1: take a lot of setup from TestReinvest so we have non-zero info - initInfo := initializeStaking(t) - ctx, valAddr, contractAddr := initInfo.ctx, initInfo.valAddr, initInfo.contractAddr - keeper, stakingKeeper := initInfo.wasmKeeper, initInfo.stakingKeeper - distKeeper := initInfo.distKeeper - - // initial checks of bonding state - val, found := stakingKeeper.GetValidator(ctx, valAddr) - require.True(t, found) - assert.Equal(t, sdk.NewInt(1000000), val.Tokens) - - // full is 2x funds, 1x goes to the contract, other stays on his wallet - full := sdk.NewCoins(sdk.NewInt64Coin("stake", 400000)) - funds := sdk.NewCoins(sdk.NewInt64Coin("stake", 200000)) - bob := initInfo.faucet.NewFundedRandomAccount(ctx, full...) - - // we will stake 200k to a validator with 1M self-bond - // this means we should get 1/6 of the rewards - bond := StakingHandleMsg{ - Bond: &struct{}{}, - } - bondBz, err := json.Marshal(bond) - require.NoError(t, err) - _, err = initInfo.contractKeeper.Execute(ctx, contractAddr, bob, bondBz, funds) - require.NoError(t, err) - - // update height a bit to solidify the delegation - ctx = nextBlock(ctx, stakingKeeper) - // we get 1/6, our share should be 40k minus 10% commission = 36k - setValidatorRewards(ctx, stakingKeeper, distKeeper, valAddr, "240000") - - // see what the current rewards are - origReward := distKeeper.GetValidatorCurrentRewards(ctx, valAddr) - - // STEP 2: Prepare the mask contract - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := initInfo.faucet.NewFundedRandomAccount(ctx, deposit...) - - // upload mask code - maskID, _, err := initInfo.contractKeeper.Create(ctx, creator, testdata.ReflectContractWasm(), nil) - require.NoError(t, err) - require.Equal(t, uint64(2), maskID) - - // creator instantiates a contract and gives it tokens - maskAddr, _, err := initInfo.contractKeeper.Instantiate(ctx, maskID, creator, nil, []byte("{}"), "mask contract 2", nil) - require.NoError(t, err) - require.NotEmpty(t, maskAddr) - - // STEP 3: now, let's reflect some queries. - // let's get the bonded denom - reflectBondedQuery := testdata.ReflectQueryMsg{Chain: &testdata.ChainQuery{Request: &wasmvmtypes.QueryRequest{Staking: &wasmvmtypes.StakingQuery{ - BondedDenom: &struct{}{}, - }}}} - reflectBondedBin := buildReflectQuery(t, &reflectBondedQuery) - res, err := keeper.QuerySmart(ctx, maskAddr, reflectBondedBin) - require.NoError(t, err) - // first we pull out the data from chain response, before parsing the original response - var reflectRes testdata.ChainResponse - mustParse(t, res, &reflectRes) - var bondedRes wasmvmtypes.BondedDenomResponse - mustParse(t, reflectRes.Data, &bondedRes) - assert.Equal(t, "stake", bondedRes.Denom) - - // now, let's reflect a smart query into the x/wasm handlers and see if we get the same result - reflectAllValidatorsQuery := testdata.ReflectQueryMsg{Chain: &testdata.ChainQuery{Request: &wasmvmtypes.QueryRequest{Staking: &wasmvmtypes.StakingQuery{ - AllValidators: &wasmvmtypes.AllValidatorsQuery{}, - }}}} - reflectAllValidatorsBin := buildReflectQuery(t, &reflectAllValidatorsQuery) - res, err = keeper.QuerySmart(ctx, maskAddr, reflectAllValidatorsBin) - require.NoError(t, err) - // first we pull out the data from chain response, before parsing the original response - mustParse(t, res, &reflectRes) - var allValidatorsRes wasmvmtypes.AllValidatorsResponse - mustParse(t, reflectRes.Data, &allValidatorsRes) - require.Len(t, allValidatorsRes.Validators, 1, string(res)) - valInfo := allValidatorsRes.Validators[0] - // Note: this ValAddress not AccAddress, may change with #264 - require.Equal(t, valAddr.String(), valInfo.Address) - require.Contains(t, valInfo.Commission, "0.100") - require.Contains(t, valInfo.MaxCommission, "0.200") - require.Contains(t, valInfo.MaxChangeRate, "0.010") - - // find a validator - reflectValidatorQuery := testdata.ReflectQueryMsg{Chain: &testdata.ChainQuery{Request: &wasmvmtypes.QueryRequest{Staking: &wasmvmtypes.StakingQuery{ - Validator: &wasmvmtypes.ValidatorQuery{ - Address: valAddr.String(), - }, - }}}} - reflectValidatorBin := buildReflectQuery(t, &reflectValidatorQuery) - res, err = keeper.QuerySmart(ctx, maskAddr, reflectValidatorBin) - require.NoError(t, err) - // first we pull out the data from chain response, before parsing the original response - mustParse(t, res, &reflectRes) - var validatorRes wasmvmtypes.ValidatorResponse - mustParse(t, reflectRes.Data, &validatorRes) - require.NotNil(t, validatorRes.Validator) - valInfo = *validatorRes.Validator - // Note: this ValAddress not AccAddress, may change with #264 - require.Equal(t, valAddr.String(), valInfo.Address) - require.Contains(t, valInfo.Commission, "0.100") - require.Contains(t, valInfo.MaxCommission, "0.200") - require.Contains(t, valInfo.MaxChangeRate, "0.010") - - // missing validator - noVal := sdk.ValAddress(secp256k1.GenPrivKey().PubKey().Address()) - reflectNoValidatorQuery := testdata.ReflectQueryMsg{Chain: &testdata.ChainQuery{Request: &wasmvmtypes.QueryRequest{Staking: &wasmvmtypes.StakingQuery{ - Validator: &wasmvmtypes.ValidatorQuery{ - Address: noVal.String(), - }, - }}}} - reflectNoValidatorBin := buildReflectQuery(t, &reflectNoValidatorQuery) - res, err = keeper.QuerySmart(ctx, maskAddr, reflectNoValidatorBin) - require.NoError(t, err) - // first we pull out the data from chain response, before parsing the original response - mustParse(t, res, &reflectRes) - var noValidatorRes wasmvmtypes.ValidatorResponse - mustParse(t, reflectRes.Data, &noValidatorRes) - require.Nil(t, noValidatorRes.Validator) - - // test to get all my delegations - reflectAllDelegationsQuery := testdata.ReflectQueryMsg{Chain: &testdata.ChainQuery{Request: &wasmvmtypes.QueryRequest{Staking: &wasmvmtypes.StakingQuery{ - AllDelegations: &wasmvmtypes.AllDelegationsQuery{ - Delegator: contractAddr.String(), - }, - }}}} - reflectAllDelegationsBin := buildReflectQuery(t, &reflectAllDelegationsQuery) - res, err = keeper.QuerySmart(ctx, maskAddr, reflectAllDelegationsBin) - require.NoError(t, err) - // first we pull out the data from chain response, before parsing the original response - mustParse(t, res, &reflectRes) - var allDelegationsRes wasmvmtypes.AllDelegationsResponse - mustParse(t, reflectRes.Data, &allDelegationsRes) - require.Len(t, allDelegationsRes.Delegations, 1) - delInfo := allDelegationsRes.Delegations[0] - // Note: this ValAddress not AccAddress, may change with #264 - require.Equal(t, valAddr.String(), delInfo.Validator) - // note this is not bob (who staked to the contract), but the contract itself - require.Equal(t, contractAddr.String(), delInfo.Delegator) - // this is a different Coin type, with String not BigInt, compare field by field - require.Equal(t, funds[0].Denom, delInfo.Amount.Denom) - require.Equal(t, funds[0].Amount.String(), delInfo.Amount.Amount) - - // test to get one delegation - reflectDelegationQuery := testdata.ReflectQueryMsg{Chain: &testdata.ChainQuery{Request: &wasmvmtypes.QueryRequest{Staking: &wasmvmtypes.StakingQuery{ - Delegation: &wasmvmtypes.DelegationQuery{ - Validator: valAddr.String(), - Delegator: contractAddr.String(), - }, - }}}} - reflectDelegationBin := buildReflectQuery(t, &reflectDelegationQuery) - res, err = keeper.QuerySmart(ctx, maskAddr, reflectDelegationBin) - require.NoError(t, err) - // first we pull out the data from chain response, before parsing the original response - mustParse(t, res, &reflectRes) - - var delegationRes wasmvmtypes.DelegationResponse - mustParse(t, reflectRes.Data, &delegationRes) - assert.NotEmpty(t, delegationRes.Delegation) - delInfo2 := delegationRes.Delegation - // Note: this ValAddress not AccAddress, may change with #264 - require.Equal(t, valAddr.String(), delInfo2.Validator) - // note this is not bob (who staked to the contract), but the contract itself - require.Equal(t, contractAddr.String(), delInfo2.Delegator) - // this is a different Coin type, with String not BigInt, compare field by field - require.Equal(t, funds[0].Denom, delInfo2.Amount.Denom) - require.Equal(t, funds[0].Amount.String(), delInfo2.Amount.Amount) - - require.Equal(t, wasmvmtypes.NewCoin(200000, "stake"), delInfo2.CanRedelegate) - require.Len(t, delInfo2.AccumulatedRewards, 1) - // see bonding above to see how we calculate 36000 (240000 / 6 - 10% commission) - require.Equal(t, wasmvmtypes.NewCoin(36000, "stake"), delInfo2.AccumulatedRewards[0]) - - // ensure rewards did not change when querying (neither amount nor period) - finalReward := distKeeper.GetValidatorCurrentRewards(ctx, valAddr) - require.Equal(t, origReward, finalReward) -} - -func TestQueryStakingPlugin(t *testing.T) { - // STEP 1: take a lot of setup from TestReinvest so we have non-zero info - initInfo := initializeStaking(t) - ctx, valAddr, contractAddr := initInfo.ctx, initInfo.valAddr, initInfo.contractAddr - stakingKeeper := initInfo.stakingKeeper - distKeeper := initInfo.distKeeper - - // initial checks of bonding state - val, found := stakingKeeper.GetValidator(ctx, valAddr) - require.True(t, found) - assert.Equal(t, sdk.NewInt(1000000), val.Tokens) - - // full is 2x funds, 1x goes to the contract, other stays on his wallet - full := sdk.NewCoins(sdk.NewInt64Coin("stake", 400000)) - funds := sdk.NewCoins(sdk.NewInt64Coin("stake", 200000)) - bob := initInfo.faucet.NewFundedRandomAccount(ctx, full...) - - // we will stake 200k to a validator with 1M self-bond - // this means we should get 1/6 of the rewards - bond := StakingHandleMsg{ - Bond: &struct{}{}, - } - bondBz, err := json.Marshal(bond) - require.NoError(t, err) - _, err = initInfo.contractKeeper.Execute(ctx, contractAddr, bob, bondBz, funds) - require.NoError(t, err) - - // update height a bit to solidify the delegation - ctx = nextBlock(ctx, stakingKeeper) - // we get 1/6, our share should be 40k minus 10% commission = 36k - setValidatorRewards(ctx, stakingKeeper, distKeeper, valAddr, "240000") - - // see what the current rewards are - origReward := distKeeper.GetValidatorCurrentRewards(ctx, valAddr) - - // Step 2: Try out the query plugins - query := wasmvmtypes.StakingQuery{ - Delegation: &wasmvmtypes.DelegationQuery{ - Delegator: contractAddr.String(), - Validator: valAddr.String(), - }, - } - raw, err := StakingQuerier(stakingKeeper, distributionkeeper.NewQuerier(distKeeper))(ctx, &query) - require.NoError(t, err) - var res wasmvmtypes.DelegationResponse - mustParse(t, raw, &res) - assert.NotEmpty(t, res.Delegation) - delInfo := res.Delegation - // Note: this ValAddress not AccAddress, may change with #264 - require.Equal(t, valAddr.String(), delInfo.Validator) - // note this is not bob (who staked to the contract), but the contract itself - require.Equal(t, contractAddr.String(), delInfo.Delegator) - // this is a different Coin type, with String not BigInt, compare field by field - require.Equal(t, funds[0].Denom, delInfo.Amount.Denom) - require.Equal(t, funds[0].Amount.String(), delInfo.Amount.Amount) - - require.Equal(t, wasmvmtypes.NewCoin(200000, "stake"), delInfo.CanRedelegate) - require.Len(t, delInfo.AccumulatedRewards, 1) - // see bonding above to see how we calculate 36000 (240000 / 6 - 10% commission) - require.Equal(t, wasmvmtypes.NewCoin(36000, "stake"), delInfo.AccumulatedRewards[0]) - - // ensure rewards did not change when querying (neither amount nor period) - finalReward := distKeeper.GetValidatorCurrentRewards(ctx, valAddr) - require.Equal(t, origReward, finalReward) -} - -// adds a few validators and returns a list of validators that are registered -func addValidator(t *testing.T, ctx sdk.Context, stakingKeeper *stakingkeeper.Keeper, faucet *TestFaucet, value sdk.Coin) sdk.ValAddress { - owner := faucet.NewFundedRandomAccount(ctx, value) - - privKey := secp256k1.GenPrivKey() - pubKey := privKey.PubKey() - addr := sdk.ValAddress(pubKey.Address()) - - pkAny, err := codectypes.NewAnyWithValue(pubKey) - require.NoError(t, err) - msg := &stakingtypes.MsgCreateValidator{ - Description: stakingtypes.Description{ - Moniker: "Validator power", - }, - Commission: stakingtypes.CommissionRates{ - Rate: sdk.MustNewDecFromStr("0.1"), - MaxRate: sdk.MustNewDecFromStr("0.2"), - MaxChangeRate: sdk.MustNewDecFromStr("0.01"), - }, - MinSelfDelegation: sdk.OneInt(), - DelegatorAddress: owner.String(), - ValidatorAddress: addr.String(), - Pubkey: pkAny, - Value: value, - } - _, err = stakingkeeper.NewMsgServerImpl(stakingKeeper).CreateValidator(sdk.WrapSDKContext(ctx), msg) - require.NoError(t, err) - return addr -} - -// this will commit the current set, update the block height and set historic info -// basically, letting two blocks pass -func nextBlock(ctx sdk.Context, stakingKeeper *stakingkeeper.Keeper) sdk.Context { - staking.EndBlocker(ctx, stakingKeeper) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - staking.BeginBlocker(ctx, stakingKeeper) - return ctx -} - -func setValidatorRewards(ctx sdk.Context, stakingKeeper *stakingkeeper.Keeper, distKeeper distributionkeeper.Keeper, valAddr sdk.ValAddress, reward string) { - // allocate some rewards - vali := stakingKeeper.Validator(ctx, valAddr) - amount, err := sdk.NewDecFromStr(reward) - if err != nil { - panic(err) - } - payout := sdk.DecCoins{{Denom: "stake", Amount: amount}} - distKeeper.AllocateTokensToValidator(ctx, vali, payout) -} - -func assertBalance(t *testing.T, ctx sdk.Context, keeper Keeper, contract sdk.AccAddress, addr sdk.AccAddress, expected string) { - query := StakingQueryMsg{ - Balance: &addressQuery{ - Address: addr, - }, - } - queryBz, err := json.Marshal(query) - require.NoError(t, err) - res, err := keeper.QuerySmart(ctx, contract, queryBz) - require.NoError(t, err) - var balance BalanceResponse - err = json.Unmarshal(res, &balance) - require.NoError(t, err) - assert.Equal(t, expected, balance.Balance) -} - -func assertClaims(t *testing.T, ctx sdk.Context, keeper Keeper, contract sdk.AccAddress, addr sdk.AccAddress, expected string) { - query := StakingQueryMsg{ - Claims: &addressQuery{ - Address: addr, - }, - } - queryBz, err := json.Marshal(query) - require.NoError(t, err) - res, err := keeper.QuerySmart(ctx, contract, queryBz) - require.NoError(t, err) - var claims ClaimsResponse - err = json.Unmarshal(res, &claims) - require.NoError(t, err) - assert.Equal(t, expected, claims.Claims) -} - -func assertSupply(t *testing.T, ctx sdk.Context, keeper Keeper, contract sdk.AccAddress, expectedIssued string, expectedBonded sdk.Coin) { - query := StakingQueryMsg{Investment: &struct{}{}} - queryBz, err := json.Marshal(query) - require.NoError(t, err) - res, err := keeper.QuerySmart(ctx, contract, queryBz) - require.NoError(t, err) - var invest InvestmentResponse - err = json.Unmarshal(res, &invest) - require.NoError(t, err) - assert.Equal(t, expectedIssued, invest.TokenSupply) - assert.Equal(t, expectedBonded, invest.StakedTokens) -} diff --git a/x/wasm/keeper/submsg_test.go b/x/wasm/keeper/submsg_test.go deleted file mode 100644 index fc14d2c..0000000 --- a/x/wasm/keeper/submsg_test.go +++ /dev/null @@ -1,552 +0,0 @@ -package keeper - -import ( - "encoding/json" - "fmt" - "os" - "strconv" - "testing" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/keeper/testdata" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// test handing of submessages, very closely related to the reflect_test - -// Try a simple send, no gas limit to for a sanity check before trying table tests -func TestDispatchSubMsgSuccessCase(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, ReflectFeatures) - accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.WasmKeeper, keepers.BankKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - contractStart := sdk.NewCoins(sdk.NewInt64Coin("denom", 40000)) - - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - creatorBalance := deposit.Sub(contractStart...) - _, fred := keyPubAddr() - - // upload code - codeID, _, err := keepers.ContractKeeper.Create(ctx, creator, testdata.ReflectContractWasm(), nil) - require.NoError(t, err) - require.Equal(t, uint64(1), codeID) - - // creator instantiates a contract and gives it tokens - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, []byte("{}"), "reflect contract 1", contractStart) - require.NoError(t, err) - require.NotEmpty(t, contractAddr) - - // check some account values - checkAccount(t, ctx, accKeeper, bankKeeper, contractAddr, contractStart) - checkAccount(t, ctx, accKeeper, bankKeeper, creator, creatorBalance) - checkAccount(t, ctx, accKeeper, bankKeeper, fred, nil) - - // creator can send contract's tokens to fred (using SendMsg) - msg := wasmvmtypes.CosmosMsg{ - Bank: &wasmvmtypes.BankMsg{ - Send: &wasmvmtypes.SendMsg{ - ToAddress: fred.String(), - Amount: []wasmvmtypes.Coin{{ - Denom: "denom", - Amount: "15000", - }}, - }, - }, - } - reflectSend := testdata.ReflectHandleMsg{ - ReflectSubMsg: &testdata.ReflectSubPayload{ - Msgs: []wasmvmtypes.SubMsg{{ - ID: 7, - Msg: msg, - ReplyOn: wasmvmtypes.ReplyAlways, - }}, - }, - } - reflectSendBz, err := json.Marshal(reflectSend) - require.NoError(t, err) - _, err = keepers.ContractKeeper.Execute(ctx, contractAddr, creator, reflectSendBz, nil) - require.NoError(t, err) - - // fred got coins - checkAccount(t, ctx, accKeeper, bankKeeper, fred, sdk.NewCoins(sdk.NewInt64Coin("denom", 15000))) - // contract lost them - checkAccount(t, ctx, accKeeper, bankKeeper, contractAddr, sdk.NewCoins(sdk.NewInt64Coin("denom", 25000))) - checkAccount(t, ctx, accKeeper, bankKeeper, creator, creatorBalance) - - // query the reflect state to ensure the result was stored - query := testdata.ReflectQueryMsg{ - SubMsgResult: &testdata.SubCall{ID: 7}, - } - queryBz, err := json.Marshal(query) - require.NoError(t, err) - queryRes, err := keeper.QuerySmart(ctx, contractAddr, queryBz) - require.NoError(t, err) - - var res wasmvmtypes.Reply - err = json.Unmarshal(queryRes, &res) - require.NoError(t, err) - assert.Equal(t, uint64(7), res.ID) - assert.Empty(t, res.Result.Err) - require.NotNil(t, res.Result.Ok) - sub := res.Result.Ok - assert.Empty(t, sub.Data) - // as of v0.28.0 we strip out all events that don't come from wasm contracts. can't trust the sdk. - require.Len(t, sub.Events, 0) -} - -func TestDispatchSubMsgErrorHandling(t *testing.T) { - fundedDenom := "funds" - fundedAmount := 1_000_000 - ctxGasLimit := uint64(1_000_000) - subGasLimit := uint64(300_000) - - // prep - create one chain and upload the code - ctx, keepers := CreateTestInput(t, false, ReflectFeatures) - ctx = ctx.WithGasMeter(sdk.NewInfiniteGasMeter()) - ctx = ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter()) - keeper := keepers.WasmKeeper - contractStart := sdk.NewCoins(sdk.NewInt64Coin(fundedDenom, int64(fundedAmount))) - uploader := keepers.Faucet.NewFundedRandomAccount(ctx, contractStart.Add(contractStart...)...) - - // upload code - reflectID, _, err := keepers.ContractKeeper.Create(ctx, uploader, testdata.ReflectContractWasm(), nil) - require.NoError(t, err) - - // create hackatom contract for testing (for infinite loop) - hackatomCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - hackatomID, _, err := keepers.ContractKeeper.Create(ctx, uploader, hackatomCode, nil) - require.NoError(t, err) - _, bob := keyPubAddr() - _, fred := keyPubAddr() - initMsg := HackatomExampleInitMsg{ - Verifier: fred, - Beneficiary: bob, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - hackatomAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, hackatomID, uploader, nil, initMsgBz, "hackatom demo", contractStart) - require.NoError(t, err) - - validBankSend := func(contract, emptyAccount string) wasmvmtypes.CosmosMsg { - return wasmvmtypes.CosmosMsg{ - Bank: &wasmvmtypes.BankMsg{ - Send: &wasmvmtypes.SendMsg{ - ToAddress: emptyAccount, - Amount: []wasmvmtypes.Coin{{ - Denom: fundedDenom, - Amount: strconv.Itoa(fundedAmount / 2), - }}, - }, - }, - } - } - - invalidBankSend := func(contract, emptyAccount string) wasmvmtypes.CosmosMsg { - return wasmvmtypes.CosmosMsg{ - Bank: &wasmvmtypes.BankMsg{ - Send: &wasmvmtypes.SendMsg{ - ToAddress: emptyAccount, - Amount: []wasmvmtypes.Coin{{ - Denom: fundedDenom, - Amount: strconv.Itoa(fundedAmount * 2), - }}, - }, - }, - } - } - - infiniteLoop := func(contract, emptyAccount string) wasmvmtypes.CosmosMsg { - return wasmvmtypes.CosmosMsg{ - Wasm: &wasmvmtypes.WasmMsg{ - Execute: &wasmvmtypes.ExecuteMsg{ - ContractAddr: hackatomAddr.String(), - Msg: []byte(`{"cpu_loop":{}}`), - }, - }, - } - } - - instantiateContract := func(contract, emptyAccount string) wasmvmtypes.CosmosMsg { - return wasmvmtypes.CosmosMsg{ - Wasm: &wasmvmtypes.WasmMsg{ - Instantiate: &wasmvmtypes.InstantiateMsg{ - CodeID: reflectID, - Msg: []byte("{}"), - Label: "subcall reflect", - }, - }, - } - } - - type assertion func(t *testing.T, ctx sdk.Context, contract, emptyAccount string, response wasmvmtypes.SubMsgResult) - - assertReturnedEvents := func(expectedEvents int) assertion { - return func(t *testing.T, ctx sdk.Context, contract, emptyAccount string, response wasmvmtypes.SubMsgResult) { - require.Len(t, response.Ok.Events, expectedEvents) - } - } - - assertGasUsed := func(minGas, maxGas uint64) assertion { - return func(t *testing.T, ctx sdk.Context, contract, emptyAccount string, response wasmvmtypes.SubMsgResult) { - gasUsed := ctx.GasMeter().GasConsumed() - assert.True(t, gasUsed >= minGas, "Used %d gas (less than expected %d)", gasUsed, minGas) - assert.True(t, gasUsed <= maxGas, "Used %d gas (more than expected %d)", gasUsed, maxGas) - } - } - - assertErrorString := func(shouldContain string) assertion { - return func(t *testing.T, ctx sdk.Context, contract, emptyAccount string, response wasmvmtypes.SubMsgResult) { - assert.Contains(t, response.Err, shouldContain) - } - } - - assertGotContractAddr := func(t *testing.T, ctx sdk.Context, contract, emptyAccount string, response wasmvmtypes.SubMsgResult) { - // should get the events emitted on new contract - event := response.Ok.Events[0] - require.Equal(t, event.Type, "instantiate") - assert.Equal(t, event.Attributes[0].Key, "_contract_address") - eventAddr := event.Attributes[0].Value - assert.NotEqual(t, contract, eventAddr) - - var res types.MsgInstantiateContractResponse - keepers.EncodingConfig.Marshaler.MustUnmarshal(response.Ok.Data, &res) - assert.Equal(t, eventAddr, res.Address) - } - - cases := map[string]struct { - submsgID uint64 - // we will generate message from the - msg func(contract, emptyAccount string) wasmvmtypes.CosmosMsg - gasLimit *uint64 - - // true if we expect this to throw out of gas panic - isOutOfGasPanic bool - // true if we expect this execute to return an error (can be false when submessage errors) - executeError bool - // true if we expect submessage to return an error (but execute to return success) - subMsgError bool - // make assertions after dispatch - resultAssertions []assertion - }{ - "send tokens": { - submsgID: 5, - msg: validBankSend, - resultAssertions: []assertion{assertReturnedEvents(0), assertGasUsed(102000, 103000)}, - }, - "not enough tokens": { - submsgID: 6, - msg: invalidBankSend, - subMsgError: true, - // uses less gas than the send tokens (cost of bank transfer) - resultAssertions: []assertion{assertGasUsed(76000, 79000), assertErrorString("codespace: sdk, code: 5")}, - }, - "out of gas panic with no gas limit": { - submsgID: 7, - msg: infiniteLoop, - isOutOfGasPanic: true, - }, - - "send tokens with limit": { - submsgID: 15, - msg: validBankSend, - gasLimit: &subGasLimit, - // uses same gas as call without limit (note we do not charge the 40k on reply) - resultAssertions: []assertion{assertReturnedEvents(0), assertGasUsed(102000, 103000)}, - }, - "not enough tokens with limit": { - submsgID: 16, - msg: invalidBankSend, - subMsgError: true, - gasLimit: &subGasLimit, - // uses same gas as call without limit (note we do not charge the 40k on reply) - resultAssertions: []assertion{assertGasUsed(77700, 77800), assertErrorString("codespace: sdk, code: 5")}, - }, - "out of gas caught with gas limit": { - submsgID: 17, - msg: infiniteLoop, - subMsgError: true, - gasLimit: &subGasLimit, - // uses all the subGasLimit, plus the 52k or so for the main contract - resultAssertions: []assertion{assertGasUsed(subGasLimit+73000, subGasLimit+74000), assertErrorString("codespace: sdk, code: 11")}, - }, - "instantiate contract gets address in data and events": { - submsgID: 21, - msg: instantiateContract, - resultAssertions: []assertion{assertReturnedEvents(1), assertGotContractAddr}, - }, - } - for name, tc := range cases { - t.Run(name, func(t *testing.T) { - creator := keepers.Faucet.NewFundedRandomAccount(ctx, contractStart...) - _, empty := keyPubAddr() - - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, reflectID, creator, nil, []byte("{}"), fmt.Sprintf("contract %s", name), contractStart) - require.NoError(t, err) - - msg := tc.msg(contractAddr.String(), empty.String()) - reflectSend := testdata.ReflectHandleMsg{ - ReflectSubMsg: &testdata.ReflectSubPayload{ - Msgs: []wasmvmtypes.SubMsg{{ - ID: tc.submsgID, - Msg: msg, - GasLimit: tc.gasLimit, - ReplyOn: wasmvmtypes.ReplyAlways, - }}, - }, - } - reflectSendBz, err := json.Marshal(reflectSend) - require.NoError(t, err) - - execCtx := ctx.WithGasMeter(sdk.NewGasMeter(ctxGasLimit)) - defer func() { - if tc.isOutOfGasPanic { - r := recover() - require.NotNil(t, r, "expected panic") - if _, ok := r.(sdk.ErrorOutOfGas); !ok { - t.Fatalf("Expected OutOfGas panic, got: %#v\n", r) - } - } - }() - _, err = keepers.ContractKeeper.Execute(execCtx, contractAddr, creator, reflectSendBz, nil) - - if tc.executeError { - require.Error(t, err) - } else { - require.NoError(t, err) - - // query the reply - query := testdata.ReflectQueryMsg{ - SubMsgResult: &testdata.SubCall{ID: tc.submsgID}, - } - queryBz, err := json.Marshal(query) - require.NoError(t, err) - queryRes, err := keeper.QuerySmart(ctx, contractAddr, queryBz) - require.NoError(t, err) - var res wasmvmtypes.Reply - err = json.Unmarshal(queryRes, &res) - require.NoError(t, err) - assert.Equal(t, tc.submsgID, res.ID) - - if tc.subMsgError { - require.NotEmpty(t, res.Result.Err) - require.Nil(t, res.Result.Ok) - } else { - require.Empty(t, res.Result.Err) - require.NotNil(t, res.Result.Ok) - } - - for _, assertion := range tc.resultAssertions { - assertion(t, execCtx, contractAddr.String(), empty.String(), res.Result) - } - - } - }) - } -} - -// Test an error case, where the Encoded doesn't return any sdk.Msg and we trigger(ed) a null pointer exception. -// This occurs with the IBC encoder. Test this. -func TestDispatchSubMsgEncodeToNoSdkMsg(t *testing.T) { - // fake out the bank handle to return success with no data - nilEncoder := func(sender sdk.AccAddress, msg *wasmvmtypes.BankMsg) ([]sdk.Msg, error) { - return nil, nil - } - customEncoders := &MessageEncoders{ - Bank: nilEncoder, - } - - ctx, keepers := CreateTestInput(t, false, ReflectFeatures, WithMessageHandler(NewSDKMessageHandler(nil, customEncoders))) - keeper := keepers.WasmKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - contractStart := sdk.NewCoins(sdk.NewInt64Coin("denom", 40000)) - - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - _, fred := keyPubAddr() - - // upload code - codeID, _, err := keepers.ContractKeeper.Create(ctx, creator, testdata.ReflectContractWasm(), nil) - require.NoError(t, err) - - // creator instantiates a contract and gives it tokens - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, []byte("{}"), "reflect contract 1", contractStart) - require.NoError(t, err) - require.NotEmpty(t, contractAddr) - - // creator can send contract's tokens to fred (using SendMsg) - msg := wasmvmtypes.CosmosMsg{ - Bank: &wasmvmtypes.BankMsg{ - Send: &wasmvmtypes.SendMsg{ - ToAddress: fred.String(), - Amount: []wasmvmtypes.Coin{{ - Denom: "denom", - Amount: "15000", - }}, - }, - }, - } - reflectSend := testdata.ReflectHandleMsg{ - ReflectSubMsg: &testdata.ReflectSubPayload{ - Msgs: []wasmvmtypes.SubMsg{{ - ID: 7, - Msg: msg, - ReplyOn: wasmvmtypes.ReplyAlways, - }}, - }, - } - reflectSendBz, err := json.Marshal(reflectSend) - require.NoError(t, err) - _, err = keepers.ContractKeeper.Execute(ctx, contractAddr, creator, reflectSendBz, nil) - require.NoError(t, err) - - // query the reflect state to ensure the result was stored - query := testdata.ReflectQueryMsg{ - SubMsgResult: &testdata.SubCall{ID: 7}, - } - queryBz, err := json.Marshal(query) - require.NoError(t, err) - queryRes, err := keeper.QuerySmart(ctx, contractAddr, queryBz) - require.NoError(t, err) - - var res wasmvmtypes.Reply - err = json.Unmarshal(queryRes, &res) - require.NoError(t, err) - assert.Equal(t, uint64(7), res.ID) - assert.Empty(t, res.Result.Err) - require.NotNil(t, res.Result.Ok) - sub := res.Result.Ok - assert.Empty(t, sub.Data) - require.Len(t, sub.Events, 0) -} - -// Try a simple send, no gas limit to for a sanity check before trying table tests -func TestDispatchSubMsgConditionalReplyOn(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, ReflectFeatures) - keeper := keepers.WasmKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - contractStart := sdk.NewCoins(sdk.NewInt64Coin("denom", 40000)) - - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - _, fred := keyPubAddr() - - // upload code - codeID, _, err := keepers.ContractKeeper.Create(ctx, creator, testdata.ReflectContractWasm(), nil) - require.NoError(t, err) - - // creator instantiates a contract and gives it tokens - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, []byte("{}"), "reflect contract 1", contractStart) - require.NoError(t, err) - - goodSend := wasmvmtypes.CosmosMsg{ - Bank: &wasmvmtypes.BankMsg{ - Send: &wasmvmtypes.SendMsg{ - ToAddress: fred.String(), - Amount: []wasmvmtypes.Coin{{ - Denom: "denom", - Amount: "1000", - }}, - }, - }, - } - failSend := wasmvmtypes.CosmosMsg{ - Bank: &wasmvmtypes.BankMsg{ - Send: &wasmvmtypes.SendMsg{ - ToAddress: fred.String(), - Amount: []wasmvmtypes.Coin{{ - Denom: "no-such-token", - Amount: "777777", - }}, - }, - }, - } - - cases := map[string]struct { - // true for wasmvmtypes.ReplySuccess, false for wasmvmtypes.ReplyError - replyOnSuccess bool - msg wasmvmtypes.CosmosMsg - // true if the call should return an error (it wasn't handled) - expectError bool - // true if the reflect contract wrote the response (success or error) - it was captured - writeResult bool - }{ - "all good, reply success": { - replyOnSuccess: true, - msg: goodSend, - expectError: false, - writeResult: true, - }, - "all good, reply error": { - replyOnSuccess: false, - msg: goodSend, - expectError: false, - writeResult: false, - }, - "bad msg, reply success": { - replyOnSuccess: true, - msg: failSend, - expectError: true, - writeResult: false, - }, - "bad msg, reply error": { - replyOnSuccess: false, - msg: failSend, - expectError: false, - writeResult: true, - }, - } - - var id uint64 - for name, tc := range cases { - id++ - t.Run(name, func(t *testing.T) { - subMsg := wasmvmtypes.SubMsg{ - ID: id, - Msg: tc.msg, - ReplyOn: wasmvmtypes.ReplySuccess, - } - if !tc.replyOnSuccess { - subMsg.ReplyOn = wasmvmtypes.ReplyError - } - - reflectSend := testdata.ReflectHandleMsg{ - ReflectSubMsg: &testdata.ReflectSubPayload{ - Msgs: []wasmvmtypes.SubMsg{subMsg}, - }, - } - reflectSendBz, err := json.Marshal(reflectSend) - require.NoError(t, err) - _, err = keepers.ContractKeeper.Execute(ctx, contractAddr, creator, reflectSendBz, nil) - - if tc.expectError { - require.Error(t, err) - } else { - require.NoError(t, err) - } - - // query the reflect state to check if the result was stored - query := testdata.ReflectQueryMsg{ - SubMsgResult: &testdata.SubCall{ID: id}, - } - queryBz, err := json.Marshal(query) - require.NoError(t, err) - queryRes, err := keeper.QuerySmart(ctx, contractAddr, queryBz) - if tc.writeResult { - // we got some data for this call - require.NoError(t, err) - var res wasmvmtypes.Reply - err = json.Unmarshal(queryRes, &res) - require.NoError(t, err) - require.Equal(t, id, res.ID) - } else { - // nothing should be there -> error - require.Error(t, err) - } - }) - } -} diff --git a/x/wasm/keeper/test_common.go b/x/wasm/keeper/test_common.go deleted file mode 100644 index 7b7f9c7..0000000 --- a/x/wasm/keeper/test_common.go +++ /dev/null @@ -1,816 +0,0 @@ -package keeper - -import ( - "bytes" - "encoding/binary" - "encoding/json" - "fmt" - "os" - "testing" - "time" - - "github.com/terpnetwork/terp-core/x/wasm/keeper/testdata" - - icacontrollertypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/controller/types" - icahosttypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/host/types" - - errorsmod "cosmossdk.io/errors" - - dbm "github.com/cometbft/cometbft-db" - "github.com/cometbft/cometbft/crypto" - "github.com/cometbft/cometbft/crypto/ed25519" - "github.com/cometbft/cometbft/libs/log" - "github.com/cometbft/cometbft/libs/rand" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/std" - "github.com/cosmos/cosmos-sdk/store" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/types/module" - "github.com/cosmos/cosmos-sdk/x/auth" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - authzkeeper "github.com/cosmos/cosmos-sdk/x/authz/keeper" - "github.com/cosmos/cosmos-sdk/x/bank" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/cosmos/cosmos-sdk/x/capability" - capabilitykeeper "github.com/cosmos/cosmos-sdk/x/capability/keeper" - capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" - "github.com/cosmos/cosmos-sdk/x/crisis" - crisistypes "github.com/cosmos/cosmos-sdk/x/crisis/types" - "github.com/cosmos/cosmos-sdk/x/distribution" - distributionkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" - distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - "github.com/cosmos/cosmos-sdk/x/evidence" - evidencetypes "github.com/cosmos/cosmos-sdk/x/evidence/types" - "github.com/cosmos/cosmos-sdk/x/feegrant" - "github.com/cosmos/cosmos-sdk/x/gov" - govclient "github.com/cosmos/cosmos-sdk/x/gov/client" - govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - "github.com/cosmos/cosmos-sdk/x/mint" - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" - "github.com/cosmos/cosmos-sdk/x/params" - paramsclient "github.com/cosmos/cosmos-sdk/x/params/client" - paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" - paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" - paramproposal "github.com/cosmos/cosmos-sdk/x/params/types/proposal" - "github.com/cosmos/cosmos-sdk/x/slashing" - slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" - "github.com/cosmos/cosmos-sdk/x/staking" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/cosmos/cosmos-sdk/x/upgrade" - upgradeclient "github.com/cosmos/cosmos-sdk/x/upgrade/client" - upgradekeeper "github.com/cosmos/cosmos-sdk/x/upgrade/keeper" - upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" - "github.com/cosmos/ibc-go/v7/modules/apps/transfer" - ibctransfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" - ibc "github.com/cosmos/ibc-go/v7/modules/core" - ibcexported "github.com/cosmos/ibc-go/v7/modules/core/exported" - ibckeeper "github.com/cosmos/ibc-go/v7/modules/core/keeper" - "github.com/stretchr/testify/require" - - wasmappparams "github.com/terpnetwork/terp-core/app/params" - "github.com/terpnetwork/terp-core/x/wasm/keeper/wasmtesting" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -var moduleBasics = module.NewBasicManager( - auth.AppModuleBasic{}, - bank.AppModuleBasic{}, - capability.AppModuleBasic{}, - staking.AppModuleBasic{}, - mint.AppModuleBasic{}, - distribution.AppModuleBasic{}, - gov.NewAppModuleBasic([]govclient.ProposalHandler{ - paramsclient.ProposalHandler, - upgradeclient.LegacyProposalHandler, - upgradeclient.LegacyCancelProposalHandler, - }), - params.AppModuleBasic{}, - crisis.AppModuleBasic{}, - slashing.AppModuleBasic{}, - ibc.AppModuleBasic{}, - upgrade.AppModuleBasic{}, - evidence.AppModuleBasic{}, - transfer.AppModuleBasic{}, - vesting.AppModuleBasic{}, -) - -func MakeTestCodec(t testing.TB) codec.Codec { - return MakeEncodingConfig(t).Marshaler -} - -func MakeEncodingConfig(_ testing.TB) wasmappparams.EncodingConfig { - encodingConfig := wasmappparams.MakeEncodingConfig() - amino := encodingConfig.Amino - interfaceRegistry := encodingConfig.InterfaceRegistry - - std.RegisterInterfaces(interfaceRegistry) - std.RegisterLegacyAminoCodec(amino) - - moduleBasics.RegisterLegacyAminoCodec(amino) - moduleBasics.RegisterInterfaces(interfaceRegistry) - // add wasmd types - types.RegisterInterfaces(interfaceRegistry) - types.RegisterLegacyAminoCodec(amino) - - return encodingConfig -} - -var TestingStakeParams = stakingtypes.Params{ - UnbondingTime: 100, - MaxValidators: 10, - MaxEntries: 10, - HistoricalEntries: 10, - BondDenom: "stake", - MinCommissionRate: stakingtypes.DefaultMinCommissionRate, -} - -type TestFaucet struct { - t testing.TB - bankKeeper bankkeeper.Keeper - sender sdk.AccAddress - balance sdk.Coins - minterModuleName string -} - -func NewTestFaucet(t testing.TB, ctx sdk.Context, bankKeeper bankkeeper.Keeper, minterModuleName string, initialAmount ...sdk.Coin) *TestFaucet { - require.NotEmpty(t, initialAmount) - r := &TestFaucet{t: t, bankKeeper: bankKeeper, minterModuleName: minterModuleName} - _, addr := keyPubAddr() - r.sender = addr - r.Mint(ctx, addr, initialAmount...) - r.balance = initialAmount - return r -} - -func (f *TestFaucet) Mint(parentCtx sdk.Context, addr sdk.AccAddress, amounts ...sdk.Coin) { - require.NotEmpty(f.t, amounts) - ctx := parentCtx.WithEventManager(sdk.NewEventManager()) // discard all faucet related events - err := f.bankKeeper.MintCoins(ctx, f.minterModuleName, amounts) - require.NoError(f.t, err) - err = f.bankKeeper.SendCoinsFromModuleToAccount(ctx, f.minterModuleName, addr, amounts) - require.NoError(f.t, err) - f.balance = f.balance.Add(amounts...) -} - -func (f *TestFaucet) Fund(parentCtx sdk.Context, receiver sdk.AccAddress, amounts ...sdk.Coin) { - require.NotEmpty(f.t, amounts) - // ensure faucet is always filled - if !f.balance.IsAllGTE(amounts) { - f.Mint(parentCtx, f.sender, amounts...) - } - ctx := parentCtx.WithEventManager(sdk.NewEventManager()) // discard all faucet related events - err := f.bankKeeper.SendCoins(ctx, f.sender, receiver, amounts) - require.NoError(f.t, err) - f.balance = f.balance.Sub(amounts...) -} - -func (f *TestFaucet) NewFundedRandomAccount(ctx sdk.Context, amounts ...sdk.Coin) sdk.AccAddress { - _, addr := keyPubAddr() - f.Fund(ctx, addr, amounts...) - return addr -} - -type TestKeepers struct { - AccountKeeper authkeeper.AccountKeeper - StakingKeeper *stakingkeeper.Keeper - DistKeeper distributionkeeper.Keeper - BankKeeper bankkeeper.Keeper - GovKeeper *govkeeper.Keeper - ContractKeeper types.ContractOpsKeeper - WasmKeeper *Keeper - IBCKeeper *ibckeeper.Keeper - Router MessageRouter - EncodingConfig wasmappparams.EncodingConfig - Faucet *TestFaucet - MultiStore sdk.CommitMultiStore - ScopedWasmKeeper capabilitykeeper.ScopedKeeper - WasmStoreKey *storetypes.KVStoreKey -} - -// CreateDefaultTestInput common settings for CreateTestInput -func CreateDefaultTestInput(t testing.TB) (sdk.Context, TestKeepers) { - return CreateTestInput(t, false, "staking") -} - -// CreateTestInput encoders can be nil to accept the defaults, or set it to override some of the message handlers (like default) -func CreateTestInput(t testing.TB, isCheckTx bool, availableCapabilities string, opts ...Option) (sdk.Context, TestKeepers) { - // Load default wasm config - return createTestInput(t, isCheckTx, availableCapabilities, types.DefaultWasmConfig(), dbm.NewMemDB(), opts...) -} - -// encoders can be nil to accept the defaults, or set it to override some of the message handlers (like default) -func createTestInput( - t testing.TB, - isCheckTx bool, - availableCapabilities string, - wasmConfig types.WasmConfig, - db dbm.DB, - opts ...Option, -) (sdk.Context, TestKeepers) { - tempDir := t.TempDir() - - keys := sdk.NewKVStoreKeys( - authtypes.StoreKey, banktypes.StoreKey, stakingtypes.StoreKey, - minttypes.StoreKey, distributiontypes.StoreKey, slashingtypes.StoreKey, - govtypes.StoreKey, paramstypes.StoreKey, ibcexported.StoreKey, upgradetypes.StoreKey, - evidencetypes.StoreKey, ibctransfertypes.StoreKey, - capabilitytypes.StoreKey, feegrant.StoreKey, authzkeeper.StoreKey, - types.StoreKey, - ) - ms := store.NewCommitMultiStore(db) - for _, v := range keys { - ms.MountStoreWithDB(v, storetypes.StoreTypeIAVL, db) - } - tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey) - for _, v := range tkeys { - ms.MountStoreWithDB(v, storetypes.StoreTypeTransient, db) - } - - memKeys := sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey) - for _, v := range memKeys { - ms.MountStoreWithDB(v, storetypes.StoreTypeMemory, db) - } - - require.NoError(t, ms.LoadLatestVersion()) - - ctx := sdk.NewContext(ms, tmproto.Header{ - Height: 1234567, - Time: time.Date(2020, time.April, 22, 12, 0, 0, 0, time.UTC), - }, isCheckTx, log.NewNopLogger()) - ctx = types.WithTXCounter(ctx, 0) - - encodingConfig := MakeEncodingConfig(t) - appCodec, legacyAmino := encodingConfig.Marshaler, encodingConfig.Amino - - paramsKeeper := paramskeeper.NewKeeper( - appCodec, - legacyAmino, - keys[paramstypes.StoreKey], - tkeys[paramstypes.TStoreKey], - ) - for _, m := range []string{ - authtypes.ModuleName, - banktypes.ModuleName, - stakingtypes.ModuleName, - minttypes.ModuleName, - distributiontypes.ModuleName, - slashingtypes.ModuleName, - crisistypes.ModuleName, - ibctransfertypes.ModuleName, - capabilitytypes.ModuleName, - ibcexported.ModuleName, - govtypes.ModuleName, - types.ModuleName, - } { - paramsKeeper.Subspace(m) - } - subspace := func(m string) paramstypes.Subspace { - r, ok := paramsKeeper.GetSubspace(m) - require.True(t, ok) - - var keyTable paramstypes.KeyTable - switch r.Name() { - case authtypes.ModuleName: - keyTable = authtypes.ParamKeyTable() //nolint:staticcheck - case banktypes.ModuleName: - keyTable = banktypes.ParamKeyTable() //nolint:staticcheck - case stakingtypes.ModuleName: - keyTable = stakingtypes.ParamKeyTable() - case minttypes.ModuleName: - keyTable = minttypes.ParamKeyTable() //nolint:staticcheck - case distributiontypes.ModuleName: - keyTable = distributiontypes.ParamKeyTable() //nolint:staticcheck - case slashingtypes.ModuleName: - keyTable = slashingtypes.ParamKeyTable() //nolint:staticcheck - case govtypes.ModuleName: - keyTable = govv1.ParamKeyTable() //nolint:staticcheck - case crisistypes.ModuleName: - keyTable = crisistypes.ParamKeyTable() //nolint:staticcheck - // ibc types - case ibctransfertypes.ModuleName: - keyTable = ibctransfertypes.ParamKeyTable() - case icahosttypes.SubModuleName: - keyTable = icahosttypes.ParamKeyTable() - case icacontrollertypes.SubModuleName: - keyTable = icacontrollertypes.ParamKeyTable() - // wasm - case types.ModuleName: - keyTable = types.ParamKeyTable() //nolint:staticcheck - default: - return r - } - - if !r.HasKeyTable() { - r = r.WithKeyTable(keyTable) - } - return r - } - maccPerms := map[string][]string{ // module account permissions - authtypes.FeeCollectorName: nil, - distributiontypes.ModuleName: nil, - minttypes.ModuleName: {authtypes.Minter}, - stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking}, - stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking}, - govtypes.ModuleName: {authtypes.Burner}, - ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner}, - types.ModuleName: {authtypes.Burner}, - } - accountKeeper := authkeeper.NewAccountKeeper( - appCodec, - keys[authtypes.StoreKey], // target store - authtypes.ProtoBaseAccount, // prototype - maccPerms, - sdk.Bech32MainPrefix, - authtypes.NewModuleAddress(authtypes.ModuleName).String(), - ) - blockedAddrs := make(map[string]bool) - for acc := range maccPerms { - blockedAddrs[authtypes.NewModuleAddress(acc).String()] = true - } - - require.NoError(t, accountKeeper.SetParams(ctx, authtypes.DefaultParams())) - - bankKeeper := bankkeeper.NewBaseKeeper( - appCodec, - keys[banktypes.StoreKey], - accountKeeper, - blockedAddrs, - authtypes.NewModuleAddress(banktypes.ModuleName).String(), - ) - require.NoError(t, bankKeeper.SetParams(ctx, banktypes.DefaultParams())) - - stakingKeeper := stakingkeeper.NewKeeper( - appCodec, - keys[stakingtypes.StoreKey], - accountKeeper, - bankKeeper, - authtypes.NewModuleAddress(stakingtypes.ModuleName).String(), - ) - stakingtypes.DefaultParams() - require.NoError(t, stakingKeeper.SetParams(ctx, TestingStakeParams)) - - distKeeper := distributionkeeper.NewKeeper( - appCodec, - keys[distributiontypes.StoreKey], - accountKeeper, - bankKeeper, - stakingKeeper, - authtypes.FeeCollectorName, - authtypes.NewModuleAddress(distributiontypes.ModuleName).String(), - ) - require.NoError(t, distKeeper.SetParams(ctx, distributiontypes.DefaultParams())) - stakingKeeper.SetHooks(distKeeper.Hooks()) - - // set genesis items required for distribution - distKeeper.SetFeePool(ctx, distributiontypes.InitialFeePool()) - - upgradeKeeper := upgradekeeper.NewKeeper( - map[int64]bool{}, - keys[upgradetypes.StoreKey], - appCodec, - tempDir, - nil, - authtypes.NewModuleAddress(upgradetypes.ModuleName).String(), - ) - - faucet := NewTestFaucet(t, ctx, bankKeeper, minttypes.ModuleName, sdk.NewCoin("stake", sdk.NewInt(100_000_000_000))) - - // set some funds ot pay out validatores, based on code from: - // https://github.com/cosmos/cosmos-sdk/blob/fea231556aee4d549d7551a6190389c4328194eb/x/distribution/keeper/keeper_test.go#L50-L57 - distrAcc := distKeeper.GetDistributionAccount(ctx) - faucet.Fund(ctx, distrAcc.GetAddress(), sdk.NewCoin("stake", sdk.NewInt(2000000))) - accountKeeper.SetModuleAccount(ctx, distrAcc) - - capabilityKeeper := capabilitykeeper.NewKeeper( - appCodec, - keys[capabilitytypes.StoreKey], - memKeys[capabilitytypes.MemStoreKey], - ) - scopedIBCKeeper := capabilityKeeper.ScopeToModule(ibcexported.ModuleName) - scopedWasmKeeper := capabilityKeeper.ScopeToModule(types.ModuleName) - - ibcKeeper := ibckeeper.NewKeeper( - appCodec, - keys[ibcexported.StoreKey], - subspace(ibcexported.ModuleName), - stakingKeeper, - upgradeKeeper, - scopedIBCKeeper, - ) - - querier := baseapp.NewGRPCQueryRouter() - querier.SetInterfaceRegistry(encodingConfig.InterfaceRegistry) - msgRouter := baseapp.NewMsgServiceRouter() - msgRouter.SetInterfaceRegistry(encodingConfig.InterfaceRegistry) - - cfg := sdk.GetConfig() - cfg.SetAddressVerifier(types.VerifyAddressLen()) - - keeper := NewKeeper( - appCodec, - keys[types.StoreKey], - accountKeeper, - bankKeeper, - stakingKeeper, - distributionkeeper.NewQuerier(distKeeper), - ibcKeeper.ChannelKeeper, - &ibcKeeper.PortKeeper, - scopedWasmKeeper, - wasmtesting.MockIBCTransferKeeper{}, - msgRouter, - querier, - tempDir, - wasmConfig, - availableCapabilities, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), - opts..., - ) - require.NoError(t, keeper.SetParams(ctx, types.DefaultParams())) - - // add wasm handler so we can loop-back (contracts calling contracts) - contractKeeper := NewDefaultPermissionKeeper(&keeper) - - govRouter := govv1beta1.NewRouter(). - AddRoute(govtypes.RouterKey, govv1beta1.ProposalHandler). - AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(paramsKeeper)). - AddRoute(types.RouterKey, NewWasmProposalHandler(&keeper, types.EnableAllProposals)) - - govKeeper := govkeeper.NewKeeper( - appCodec, - keys[govtypes.StoreKey], - accountKeeper, - bankKeeper, - stakingKeeper, - msgRouter, - govtypes.DefaultConfig(), - authtypes.NewModuleAddress(govtypes.ModuleName).String(), - ) - require.NoError(t, govKeeper.SetParams(ctx, govv1.DefaultParams())) - govKeeper.SetLegacyRouter(govRouter) - govKeeper.SetProposalID(ctx, 1) - - am := module.NewManager( // minimal module set that we use for message/ query tests - bank.NewAppModule(appCodec, bankKeeper, accountKeeper, subspace(banktypes.ModuleName)), - staking.NewAppModule(appCodec, stakingKeeper, accountKeeper, bankKeeper, subspace(stakingtypes.ModuleName)), - distribution.NewAppModule(appCodec, distKeeper, accountKeeper, bankKeeper, stakingKeeper, subspace(distributiontypes.ModuleName)), - gov.NewAppModule(appCodec, govKeeper, accountKeeper, bankKeeper, subspace(govtypes.ModuleName)), - ) - am.RegisterServices(module.NewConfigurator(appCodec, msgRouter, querier)) - types.RegisterMsgServer(msgRouter, NewMsgServerImpl(&keeper)) - types.RegisterQueryServer(querier, NewGrpcQuerier(appCodec, keys[types.ModuleName], keeper, keeper.queryGasLimit)) - - keepers := TestKeepers{ - AccountKeeper: accountKeeper, - StakingKeeper: stakingKeeper, - DistKeeper: distKeeper, - ContractKeeper: contractKeeper, - WasmKeeper: &keeper, - BankKeeper: bankKeeper, - GovKeeper: govKeeper, - IBCKeeper: ibcKeeper, - Router: msgRouter, - EncodingConfig: encodingConfig, - Faucet: faucet, - MultiStore: ms, - ScopedWasmKeeper: scopedWasmKeeper, - WasmStoreKey: keys[types.StoreKey], - } - return ctx, keepers -} - -// TestHandler returns a wasm handler for tests (to avoid circular imports) -func TestHandler(k types.ContractOpsKeeper) MessageRouter { - return MessageRouterFunc(func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { - ctx = ctx.WithEventManager(sdk.NewEventManager()) - switch msg := msg.(type) { - case *types.MsgStoreCode: - return handleStoreCode(ctx, k, msg) - case *types.MsgInstantiateContract: - return handleInstantiate(ctx, k, msg) - case *types.MsgExecuteContract: - return handleExecute(ctx, k, msg) - default: - errMsg := fmt.Sprintf("unrecognized wasm message type: %T", msg) - return nil, errorsmod.Wrap(sdkerrors.ErrUnknownRequest, errMsg) - } - }) -} - -var _ MessageRouter = MessageRouterFunc(nil) - -type MessageRouterFunc func(ctx sdk.Context, req sdk.Msg) (*sdk.Result, error) - -func (m MessageRouterFunc) Handler(msg sdk.Msg) baseapp.MsgServiceHandler { - return m -} - -func handleStoreCode(ctx sdk.Context, k types.ContractOpsKeeper, msg *types.MsgStoreCode) (*sdk.Result, error) { - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, errorsmod.Wrap(err, "sender") - } - codeID, _, err := k.Create(ctx, senderAddr, msg.WASMByteCode, msg.InstantiatePermission) - if err != nil { - return nil, err - } - - return &sdk.Result{ - Data: []byte(fmt.Sprintf("%d", codeID)), - Events: ctx.EventManager().ABCIEvents(), - }, nil -} - -func handleInstantiate(ctx sdk.Context, k types.ContractOpsKeeper, msg *types.MsgInstantiateContract) (*sdk.Result, error) { - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, errorsmod.Wrap(err, "sender") - } - var adminAddr sdk.AccAddress - if msg.Admin != "" { - if adminAddr, err = sdk.AccAddressFromBech32(msg.Admin); err != nil { - return nil, errorsmod.Wrap(err, "admin") - } - } - - contractAddr, _, err := k.Instantiate(ctx, msg.CodeID, senderAddr, adminAddr, msg.Msg, msg.Label, msg.Funds) - if err != nil { - return nil, err - } - - return &sdk.Result{ - Data: contractAddr, - Events: ctx.EventManager().Events().ToABCIEvents(), - }, nil -} - -func handleExecute(ctx sdk.Context, k types.ContractOpsKeeper, msg *types.MsgExecuteContract) (*sdk.Result, error) { - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, errorsmod.Wrap(err, "sender") - } - contractAddr, err := sdk.AccAddressFromBech32(msg.Contract) - if err != nil { - return nil, errorsmod.Wrap(err, "admin") - } - data, err := k.Execute(ctx, contractAddr, senderAddr, msg.Msg, msg.Funds) - if err != nil { - return nil, err - } - - return &sdk.Result{ - Data: data, - Events: ctx.EventManager().Events().ToABCIEvents(), - }, nil -} - -func RandomAccountAddress(_ testing.TB) sdk.AccAddress { - _, addr := keyPubAddr() - return addr -} - -// DeterministicAccountAddress creates a test address with v repeated to valid address size -func DeterministicAccountAddress(_ testing.TB, v byte) sdk.AccAddress { - return bytes.Repeat([]byte{v}, address.Len) -} - -func RandomBech32AccountAddress(t testing.TB) string { - return RandomAccountAddress(t).String() -} - -type ExampleContract struct { - InitialAmount sdk.Coins - Creator crypto.PrivKey - CreatorAddr sdk.AccAddress - CodeID uint64 - Checksum []byte -} - -func StoreHackatomExampleContract(t testing.TB, ctx sdk.Context, keepers TestKeepers) ExampleContract { - return StoreExampleContractWasm(t, ctx, keepers, testdata.HackatomContractWasm()) -} - -func StoreBurnerExampleContract(t testing.TB, ctx sdk.Context, keepers TestKeepers) ExampleContract { - return StoreExampleContractWasm(t, ctx, keepers, testdata.BurnerContractWasm()) -} - -func StoreIBCReflectContract(t testing.TB, ctx sdk.Context, keepers TestKeepers) ExampleContract { - return StoreExampleContractWasm(t, ctx, keepers, testdata.IBCReflectContractWasm()) -} - -func StoreReflectContract(t testing.TB, ctx sdk.Context, keepers TestKeepers) ExampleContract { - return StoreExampleContractWasm(t, ctx, keepers, testdata.ReflectContractWasm()) -} - -func StoreExampleContract(t testing.TB, ctx sdk.Context, keepers TestKeepers, wasmFile string) ExampleContract { - wasmCode, err := os.ReadFile(wasmFile) - require.NoError(t, err) - return StoreExampleContractWasm(t, ctx, keepers, wasmCode) -} - -func StoreExampleContractWasm(t testing.TB, ctx sdk.Context, keepers TestKeepers, wasmCode []byte) ExampleContract { - anyAmount := sdk.NewCoins(sdk.NewInt64Coin("denom", 1000)) - creator, creatorAddr := keyPubAddr() - fundAccounts(t, ctx, keepers.AccountKeeper, keepers.BankKeeper, creatorAddr, anyAmount) - - codeID, _, err := keepers.ContractKeeper.Create(ctx, creatorAddr, wasmCode, nil) - require.NoError(t, err) - hash := keepers.WasmKeeper.GetCodeInfo(ctx, codeID).CodeHash - return ExampleContract{anyAmount, creator, creatorAddr, codeID, hash} -} - -var wasmIdent = []byte("\x00\x61\x73\x6D") - -type ExampleContractInstance struct { - ExampleContract - Contract sdk.AccAddress -} - -// SeedNewContractInstance sets the mock wasmerEngine in keeper and calls store + instantiate to init the contract's metadata -func SeedNewContractInstance(t testing.TB, ctx sdk.Context, keepers TestKeepers, mock types.WasmerEngine) ExampleContractInstance { - t.Helper() - exampleContract := StoreRandomContract(t, ctx, keepers, mock) - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, exampleContract.CodeID, exampleContract.CreatorAddr, exampleContract.CreatorAddr, []byte(`{}`), "", nil) - require.NoError(t, err) - return ExampleContractInstance{ - ExampleContract: exampleContract, - Contract: contractAddr, - } -} - -// StoreRandomContract sets the mock wasmerEngine in keeper and calls store -func StoreRandomContract(t testing.TB, ctx sdk.Context, keepers TestKeepers, mock types.WasmerEngine) ExampleContract { - return StoreRandomContractWithAccessConfig(t, ctx, keepers, mock, nil) -} - -func StoreRandomContractWithAccessConfig( - t testing.TB, ctx sdk.Context, - keepers TestKeepers, - mock types.WasmerEngine, - cfg *types.AccessConfig, -) ExampleContract { - t.Helper() - anyAmount := sdk.NewCoins(sdk.NewInt64Coin("denom", 1000)) - creator, creatorAddr := keyPubAddr() - fundAccounts(t, ctx, keepers.AccountKeeper, keepers.BankKeeper, creatorAddr, anyAmount) - keepers.WasmKeeper.wasmVM = mock - wasmCode := append(wasmIdent, rand.Bytes(10)...) //nolint:gocritic - codeID, checksum, err := keepers.ContractKeeper.Create(ctx, creatorAddr, wasmCode, cfg) - require.NoError(t, err) - exampleContract := ExampleContract{InitialAmount: anyAmount, Creator: creator, CreatorAddr: creatorAddr, CodeID: codeID, Checksum: checksum} - return exampleContract -} - -type HackatomExampleInstance struct { - ExampleContract - Contract sdk.AccAddress - Verifier crypto.PrivKey - VerifierAddr sdk.AccAddress - Beneficiary crypto.PrivKey - BeneficiaryAddr sdk.AccAddress - Label string - Deposit sdk.Coins -} - -// InstantiateHackatomExampleContract load and instantiate the "./testdata/hackatom.wasm" contract -func InstantiateHackatomExampleContract(t testing.TB, ctx sdk.Context, keepers TestKeepers) HackatomExampleInstance { - contract := StoreHackatomExampleContract(t, ctx, keepers) - - verifier, verifierAddr := keyPubAddr() - fundAccounts(t, ctx, keepers.AccountKeeper, keepers.BankKeeper, verifierAddr, contract.InitialAmount) - - beneficiary, beneficiaryAddr := keyPubAddr() - initMsgBz := HackatomExampleInitMsg{ - Verifier: verifierAddr, - Beneficiary: beneficiaryAddr, - }.GetBytes(t) - initialAmount := sdk.NewCoins(sdk.NewInt64Coin("denom", 100)) - - adminAddr := contract.CreatorAddr - label := "demo contract to query" - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, contract.CodeID, contract.CreatorAddr, adminAddr, initMsgBz, label, initialAmount) - require.NoError(t, err) - return HackatomExampleInstance{ - ExampleContract: contract, - Contract: contractAddr, - Verifier: verifier, - VerifierAddr: verifierAddr, - Beneficiary: beneficiary, - BeneficiaryAddr: beneficiaryAddr, - Label: label, - Deposit: initialAmount, - } -} - -type ExampleInstance struct { - ExampleContract - Contract sdk.AccAddress - Label string - Deposit sdk.Coins -} - -// InstantiateReflectExampleContract load and instantiate the "./testdata/reflect.wasm" contract -func InstantiateReflectExampleContract(t testing.TB, ctx sdk.Context, keepers TestKeepers) ExampleInstance { - example := StoreReflectContract(t, ctx, keepers) - initialAmount := sdk.NewCoins(sdk.NewInt64Coin("denom", 100)) - label := "demo contract to query" - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, example.CodeID, example.CreatorAddr, example.CreatorAddr, []byte("{}"), label, initialAmount) - - require.NoError(t, err) - return ExampleInstance{ - ExampleContract: example, - Contract: contractAddr, - Label: label, - Deposit: initialAmount, - } -} - -type HackatomExampleInitMsg struct { - Verifier sdk.AccAddress `json:"verifier"` - Beneficiary sdk.AccAddress `json:"beneficiary"` -} - -func (m HackatomExampleInitMsg) GetBytes(t testing.TB) []byte { - initMsgBz, err := json.Marshal(m) - require.NoError(t, err) - return initMsgBz -} - -type IBCReflectExampleInstance struct { - Contract sdk.AccAddress - Admin sdk.AccAddress - CodeID uint64 - ReflectCodeID uint64 -} - -// InstantiateIBCReflectContract load and instantiate the "./testdata/ibc_reflect.wasm" contract -func InstantiateIBCReflectContract(t testing.TB, ctx sdk.Context, keepers TestKeepers) IBCReflectExampleInstance { - reflectID := StoreReflectContract(t, ctx, keepers).CodeID - ibcReflectID := StoreIBCReflectContract(t, ctx, keepers).CodeID - - initMsgBz := IBCReflectInitMsg{ - ReflectCodeID: reflectID, - }.GetBytes(t) - adminAddr := RandomAccountAddress(t) - - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, ibcReflectID, adminAddr, adminAddr, initMsgBz, "ibc-reflect-factory", nil) - require.NoError(t, err) - return IBCReflectExampleInstance{ - Admin: adminAddr, - Contract: contractAddr, - CodeID: ibcReflectID, - ReflectCodeID: reflectID, - } -} - -type IBCReflectInitMsg struct { - ReflectCodeID uint64 `json:"reflect_code_id"` -} - -func (m IBCReflectInitMsg) GetBytes(t testing.TB) []byte { - initMsgBz, err := json.Marshal(m) - require.NoError(t, err) - return initMsgBz -} - -type BurnerExampleInitMsg struct { - Payout sdk.AccAddress `json:"payout"` -} - -func (m BurnerExampleInitMsg) GetBytes(t testing.TB) []byte { - initMsgBz, err := json.Marshal(m) - require.NoError(t, err) - return initMsgBz -} - -func fundAccounts(t testing.TB, ctx sdk.Context, am authkeeper.AccountKeeper, bank bankkeeper.Keeper, addr sdk.AccAddress, coins sdk.Coins) { - acc := am.NewAccountWithAddress(ctx, addr) - am.SetAccount(ctx, acc) - NewTestFaucet(t, ctx, bank, minttypes.ModuleName, coins...).Fund(ctx, addr, coins...) -} - -var keyCounter uint64 - -// we need to make this deterministic (same every test run), as encoded address size and thus gas cost, -// depends on the actual bytes (due to ugly CanonicalAddress encoding) -func keyPubAddr() (crypto.PrivKey, sdk.AccAddress) { - keyCounter++ - seed := make([]byte, 8) - binary.BigEndian.PutUint64(seed, keyCounter) - - key := ed25519.GenPrivKeyFromSecret(seed) - pub := key.PubKey() - addr := sdk.AccAddress(pub.Address()) - return key, addr -} diff --git a/x/wasm/keeper/test_fuzz.go b/x/wasm/keeper/test_fuzz.go deleted file mode 100644 index d6acf7b..0000000 --- a/x/wasm/keeper/test_fuzz.go +++ /dev/null @@ -1,78 +0,0 @@ -package keeper - -import ( - "encoding/json" - - tmBytes "github.com/cometbft/cometbft/libs/bytes" - sdk "github.com/cosmos/cosmos-sdk/types" - fuzz "github.com/google/gofuzz" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -var ModelFuzzers = []interface{}{FuzzAddr, FuzzAddrString, FuzzAbsoluteTxPosition, FuzzContractInfo, FuzzStateModel, FuzzAccessType, FuzzAccessConfig, FuzzContractCodeHistory} - -func FuzzAddr(m *sdk.AccAddress, c fuzz.Continue) { - *m = make([]byte, 20) - c.Read(*m) -} - -func FuzzAddrString(m *string, c fuzz.Continue) { - var x sdk.AccAddress - FuzzAddr(&x, c) - *m = x.String() -} - -func FuzzAbsoluteTxPosition(m *types.AbsoluteTxPosition, c fuzz.Continue) { - m.BlockHeight = c.RandUint64() - m.TxIndex = c.RandUint64() -} - -func FuzzContractInfo(m *types.ContractInfo, c fuzz.Continue) { - m.CodeID = c.RandUint64() - FuzzAddrString(&m.Creator, c) - FuzzAddrString(&m.Admin, c) - m.Label = c.RandString() - c.Fuzz(&m.Created) -} - -func FuzzContractCodeHistory(m *types.ContractCodeHistoryEntry, c fuzz.Continue) { - const maxMsgSize = 128 - m.CodeID = c.RandUint64() - msg := make([]byte, c.RandUint64()%maxMsgSize) - c.Read(msg) - var err error - if m.Msg, err = json.Marshal(msg); err != nil { - panic(err) - } - c.Fuzz(&m.Updated) - m.Operation = types.AllCodeHistoryTypes[c.Int()%len(types.AllCodeHistoryTypes)] -} - -func FuzzStateModel(m *types.Model, c fuzz.Continue) { - m.Key = tmBytes.HexBytes(c.RandString()) - if len(m.Key) != 0 { - c.Fuzz(&m.Value) - return - } - // try again, keys must not be empty - FuzzStateModel(m, c) -} - -func FuzzAccessType(m *types.AccessType, c fuzz.Continue) { - pos := c.Int() % len(types.AllAccessTypes) - for _, v := range types.AllAccessTypes { - if pos == 0 { - *m = v - return - } - pos-- - } -} - -func FuzzAccessConfig(m *types.AccessConfig, c fuzz.Continue) { - FuzzAccessType(&m.Permission, c) - var add sdk.AccAddress - FuzzAddr(&add, c) - *m = m.Permission.With(add) -} diff --git a/x/wasm/keeper/testdata/broken_crc.gzip b/x/wasm/keeper/testdata/broken_crc.gzip deleted file mode 100644 index 378713e..0000000 Binary files a/x/wasm/keeper/testdata/broken_crc.gzip and /dev/null differ diff --git a/x/wasm/keeper/testdata/burner.wasm b/x/wasm/keeper/testdata/burner.wasm deleted file mode 100644 index 6639075..0000000 Binary files a/x/wasm/keeper/testdata/burner.wasm and /dev/null differ diff --git a/x/wasm/keeper/testdata/contracts.go b/x/wasm/keeper/testdata/contracts.go deleted file mode 100644 index 6073e4d..0000000 --- a/x/wasm/keeper/testdata/contracts.go +++ /dev/null @@ -1,94 +0,0 @@ -package testdata - -import ( - _ "embed" - - typwasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/cosmos/cosmos-sdk/types" -) - -var ( - //go:embed reflect.wasm - reflectContract []byte - //go:embed reflect_1_1.wasm - migrateReflectContract []byte - //go:embed cyberpunk.wasm - cyberpunkContract []byte - //go:embed ibc_reflect.wasm - ibcReflectContract []byte - //go:embed burner.wasm - burnerContract []byte - //go:embed hackatom.wasm - hackatomContract []byte -) - -func ReflectContractWasm() []byte { - return reflectContract -} - -func MigrateReflectContractWasm() []byte { - return migrateReflectContract -} - -func CyberpunkContractWasm() []byte { - return cyberpunkContract -} - -func IBCReflectContractWasm() []byte { - return ibcReflectContract -} - -func BurnerContractWasm() []byte { - return burnerContract -} - -func HackatomContractWasm() []byte { - return hackatomContract -} - -// ReflectHandleMsg is used to encode handle messages -type ReflectHandleMsg struct { - Reflect *ReflectPayload `json:"reflect_msg,omitempty"` - ReflectSubMsg *ReflectSubPayload `json:"reflect_sub_msg,omitempty"` - ChangeOwner *OwnerPayload `json:"change_owner,omitempty"` -} - -type OwnerPayload struct { - Owner types.Address `json:"owner"` -} - -type ReflectPayload struct { - Msgs []typwasmvmtypes.CosmosMsg `json:"msgs"` -} - -type ReflectSubPayload struct { - Msgs []typwasmvmtypes.SubMsg `json:"msgs"` -} - -// ReflectQueryMsg is used to encode query messages -type ReflectQueryMsg struct { - Owner *struct{} `json:"owner,omitempty"` - Capitalized *Text `json:"capitalized,omitempty"` - Chain *ChainQuery `json:"chain,omitempty"` - SubMsgResult *SubCall `json:"sub_msg_result,omitempty"` -} - -type ChainQuery struct { - Request *typwasmvmtypes.QueryRequest `json:"request,omitempty"` -} - -type Text struct { - Text string `json:"text"` -} - -type SubCall struct { - ID uint64 `json:"id"` -} - -type OwnerResponse struct { - Owner string `json:"owner,omitempty"` -} - -type ChainResponse struct { - Data []byte `json:"data,omitempty"` -} diff --git a/x/wasm/keeper/testdata/cyberpunk.wasm b/x/wasm/keeper/testdata/cyberpunk.wasm deleted file mode 100644 index 355804a..0000000 Binary files a/x/wasm/keeper/testdata/cyberpunk.wasm and /dev/null differ diff --git a/x/wasm/keeper/testdata/download_releases.sh b/x/wasm/keeper/testdata/download_releases.sh deleted file mode 100755 index 544cdd2..0000000 --- a/x/wasm/keeper/testdata/download_releases.sh +++ /dev/null @@ -1,23 +0,0 @@ -#!/bin/bash -set -o errexit -o nounset -o pipefail -command -v shellcheck > /dev/null && shellcheck "$0" - -if [ $# -ne 1 ]; then - echo "Usage: ./download_releases.sh RELEASE_TAG" - exit 1 -fi - -tag="$1" - -for contract in burner hackatom ibc_reflect ibc_reflect_send reflect staking cyberpunk; do - url="https://github.com/CosmWasm/cosmwasm/releases/download/$tag/${contract}.wasm" - echo "Downloading $url ..." - wget -O "${contract}.wasm" "$url" -done - -# create the zip variant -gzip -k hackatom.wasm -mv hackatom.wasm.gz hackatom.wasm.gzip - -rm -f version.txt -echo "$tag" >version.txt \ No newline at end of file diff --git a/x/wasm/keeper/testdata/genesis.json b/x/wasm/keeper/testdata/genesis.json deleted file mode 100644 index 08969c7..0000000 --- a/x/wasm/keeper/testdata/genesis.json +++ /dev/null @@ -1,219 +0,0 @@ -{ - "genesis_time": "2020-07-13T07:49:08.2945876Z", - "chain_id": "testing", - "consensus_params": { - "block": { - "max_bytes": "22020096", - "max_gas": "-1", - "time_iota_ms": "1000" - }, - "evidence": { - "max_age_num_blocks": "100000", - "max_age_duration": "172800000000000" - }, - "validator": { - "pub_key_types": [ - "ed25519" - ] - } - }, - "app_hash": "", - "app_state": { - "upgrade": {}, - "evidence": { - "params": { - "max_evidence_age": "120000000000" - }, - "evidence": [] - }, - "supply": { - "supply": [] - }, - "mint": { - "minter": { - "inflation": "0.130000000000000000", - "annual_provisions": "0.000000000000000000" - }, - "params": { - "mint_denom": "ustake", - "inflation_rate_change": "0.130000000000000000", - "inflation_max": "0.200000000000000000", - "inflation_min": "0.070000000000000000", - "goal_bonded": "0.670000000000000000", - "blocks_per_year": "6311520" - } - }, - "gov": { - "starting_proposal_id": "1", - "deposits": null, - "votes": null, - "proposals": null, - "deposit_params": { - "min_deposit": [ - { - "denom": "ustake", - "amount": "1" - } - ], - "max_deposit_period": "172800000000000" - }, - "voting_params": { - "voting_period": "60000000000", - "voting_period_desc": "1minute" - }, - "tally_params": { - "quorum": "0.000000000000000001", - "threshold": "0.000000000000000001", - "veto": "0.334000000000000000" - } - }, - "slashing": { - "params": { - "signed_blocks_window": "100", - "min_signed_per_window": "0.500000000000000000", - "downtime_jail_duration": "600000000000", - "slash_fraction_double_sign": "0.050000000000000000", - "slash_fraction_downtime": "0.010000000000000000" - }, - "signing_infos": {}, - "missed_blocks": {} - }, - "wasm": { - "params": { - "upload_access": { - "type": 3, - "address": "" - }, - "instantiate_default_permission": 3 - }, - "codes": null, - "contracts": null, - "sequences": null - }, - "bank": { - "send_enabled": true - }, - "distribution": { - "params": { - "community_tax": "0.020000000000000000", - "base_proposer_reward": "0.010000000000000000", - "bonus_proposer_reward": "0.040000000000000000", - "withdraw_addr_enabled": true - }, - "fee_pool": { - "community_pool": [] - }, - "delegator_withdraw_infos": [], - "previous_proposer": "", - "outstanding_rewards": [], - "validator_accumulated_commissions": [], - "validator_historical_rewards": [], - "validator_current_rewards": [], - "delegator_starting_infos": [], - "validator_slash_events": [] - }, - "crisis": { - "constant_fee": { - "denom": "ustake", - "amount": "1000" - } - }, - "genutil": { - "gentxs": [ - { - "type": "cosmos-sdk/StdTx", - "value": { - "msg": [ - { - "type": "cosmos-sdk/MsgCreateValidator", - "value": { - "description": { - "moniker": "testing", - "identity": "", - "website": "", - "security_contact": "", - "details": "" - }, - "commission": { - "rate": "0.100000000000000000", - "max_rate": "0.200000000000000000", - "max_change_rate": "0.010000000000000000" - }, - "min_self_delegation": "1", - "delegator_address": "cosmos1ve557a5g9yw2g2z57js3pdmcvd5my6g8ze20np", - "validator_address": "cosmosvaloper1ve557a5g9yw2g2z57js3pdmcvd5my6g88d76lj", - "pubkey": "cosmosvalconspub1zcjduepqddfln4tujr2p8actpgqz4h2xnls9y7tu9c9tu5lqkdglmdjalzuqah4neg", - "value": { - "denom": "ustake", - "amount": "250000000" - } - } - } - ], - "fee": { - "amount": [], - "gas": "200000" - }, - "signatures": [ - { - "pub_key": { - "type": "tendermint/PubKeySecp256k1", - "value": "A//cqZxkpH1re0VrHBtH308nb5t8K+Y/hF0GeRdRBmaJ" - }, - "signature": "5QEEIuUVQTEBMuAtOOHnnKo6rPsIbmfzUxUqRnDFERVqwVr1Kg+ex4f/UGIK0yrOAvOG8zDADwFP4yF8lw+o5g==" - } - ], - "memo": "836fc54e9cad58f4ed6420223ec6290f75342afa@172.17.0.2:26656" - } - } - ] - }, - "auth": { - "params": { - "max_memo_characters": "256", - "tx_sig_limit": "7", - "tx_size_cost_per_byte": "10", - "sig_verify_cost_ed25519": "590", - "sig_verify_cost_secp256k1": "1000" - }, - "accounts": [ - { - "type": "cosmos-sdk/Account", - "value": { - "address": "cosmos1ve557a5g9yw2g2z57js3pdmcvd5my6g8ze20np", - "coins": [ - { - "denom": "ucosm", - "amount": "1000000000" - }, - { - "denom": "ustake", - "amount": "1000000000" - } - ], - "public_key": "", - "account_number": 0, - "sequence": 0 - } - } - ] - }, - "params": null, - "staking": { - "params": { - "unbonding_time": "1814400000000000", - "max_validators": 100, - "max_entries": 7, - "historical_entries": 0, - "bond_denom": "ustake" - }, - "last_total_power": "0", - "last_validator_powers": null, - "validators": null, - "delegations": null, - "unbonding_delegations": null, - "redelegations": null, - "exported": false - } - } -} \ No newline at end of file diff --git a/x/wasm/keeper/testdata/hackatom.wasm b/x/wasm/keeper/testdata/hackatom.wasm deleted file mode 100644 index baa03a8..0000000 Binary files a/x/wasm/keeper/testdata/hackatom.wasm and /dev/null differ diff --git a/x/wasm/keeper/testdata/hackatom.wasm.gzip b/x/wasm/keeper/testdata/hackatom.wasm.gzip deleted file mode 100644 index 3c95e9b..0000000 Binary files a/x/wasm/keeper/testdata/hackatom.wasm.gzip and /dev/null differ diff --git a/x/wasm/keeper/testdata/ibc_reflect.wasm b/x/wasm/keeper/testdata/ibc_reflect.wasm deleted file mode 100644 index ec73710..0000000 Binary files a/x/wasm/keeper/testdata/ibc_reflect.wasm and /dev/null differ diff --git a/x/wasm/keeper/testdata/ibc_reflect_send.wasm b/x/wasm/keeper/testdata/ibc_reflect_send.wasm deleted file mode 100644 index 0f7d7e4..0000000 Binary files a/x/wasm/keeper/testdata/ibc_reflect_send.wasm and /dev/null differ diff --git a/x/wasm/keeper/testdata/reflect.wasm b/x/wasm/keeper/testdata/reflect.wasm deleted file mode 100644 index 3173564..0000000 Binary files a/x/wasm/keeper/testdata/reflect.wasm and /dev/null differ diff --git a/x/wasm/keeper/testdata/reflect.wasm.v1_0 b/x/wasm/keeper/testdata/reflect.wasm.v1_0 deleted file mode 100644 index 312f457..0000000 Binary files a/x/wasm/keeper/testdata/reflect.wasm.v1_0 and /dev/null differ diff --git a/x/wasm/keeper/testdata/reflect_1_1.wasm b/x/wasm/keeper/testdata/reflect_1_1.wasm deleted file mode 100644 index 7383a6d..0000000 Binary files a/x/wasm/keeper/testdata/reflect_1_1.wasm and /dev/null differ diff --git a/x/wasm/keeper/testdata/staking.wasm b/x/wasm/keeper/testdata/staking.wasm deleted file mode 100644 index 015ae00..0000000 Binary files a/x/wasm/keeper/testdata/staking.wasm and /dev/null differ diff --git a/x/wasm/keeper/testdata/version.txt b/x/wasm/keeper/testdata/version.txt deleted file mode 100644 index 79127d8..0000000 --- a/x/wasm/keeper/testdata/version.txt +++ /dev/null @@ -1 +0,0 @@ -v1.2.0 diff --git a/x/wasm/keeper/wasmtesting/extension_mocks.go b/x/wasm/keeper/wasmtesting/extension_mocks.go deleted file mode 100644 index 562d9e7..0000000 --- a/x/wasm/keeper/wasmtesting/extension_mocks.go +++ /dev/null @@ -1,28 +0,0 @@ -package wasmtesting - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -type MockCoinTransferrer struct { - TransferCoinsFn func(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) error -} - -func (m *MockCoinTransferrer) TransferCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) error { - if m.TransferCoinsFn == nil { - panic("not expected to be called") - } - return m.TransferCoinsFn(ctx, fromAddr, toAddr, amt) -} - -type AccountPrunerMock struct { - CleanupExistingAccountFn func(ctx sdk.Context, existingAccount authtypes.AccountI) (handled bool, err error) -} - -func (m AccountPrunerMock) CleanupExistingAccount(ctx sdk.Context, existingAccount authtypes.AccountI) (handled bool, err error) { - if m.CleanupExistingAccountFn == nil { - panic("not expected to be called") - } - return m.CleanupExistingAccountFn(ctx, existingAccount) -} diff --git a/x/wasm/keeper/wasmtesting/gas_register.go b/x/wasm/keeper/wasmtesting/gas_register.go deleted file mode 100644 index 516cd5f..0000000 --- a/x/wasm/keeper/wasmtesting/gas_register.go +++ /dev/null @@ -1,74 +0,0 @@ -package wasmtesting - -import ( - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// MockGasRegister mock that implements keeper.GasRegister -type MockGasRegister struct { - CompileCostFn func(byteLength int) sdk.Gas - NewContractInstanceCostFn func(pinned bool, msgLen int) sdk.Gas - InstantiateContractCostFn func(pinned bool, msgLen int) sdk.Gas - ReplyCostFn func(pinned bool, reply wasmvmtypes.Reply) sdk.Gas - EventCostsFn func(evts []wasmvmtypes.EventAttribute) sdk.Gas - ToWasmVMGasFn func(source sdk.Gas) uint64 - FromWasmVMGasFn func(source uint64) sdk.Gas - UncompressCostsFn func(byteLength int) sdk.Gas -} - -func (m MockGasRegister) NewContractInstanceCosts(pinned bool, msgLen int) sdk.Gas { - if m.NewContractInstanceCostFn == nil { - panic("not expected to be called") - } - return m.NewContractInstanceCostFn(pinned, msgLen) -} - -func (m MockGasRegister) CompileCosts(byteLength int) sdk.Gas { - if m.CompileCostFn == nil { - panic("not expected to be called") - } - return m.CompileCostFn(byteLength) -} - -func (m MockGasRegister) UncompressCosts(byteLength int) sdk.Gas { - if m.UncompressCostsFn == nil { - panic("not expected to be called") - } - return m.UncompressCostsFn(byteLength) -} - -func (m MockGasRegister) InstantiateContractCosts(pinned bool, msgLen int) sdk.Gas { - if m.InstantiateContractCostFn == nil { - panic("not expected to be called") - } - return m.InstantiateContractCostFn(pinned, msgLen) -} - -func (m MockGasRegister) ReplyCosts(pinned bool, reply wasmvmtypes.Reply) sdk.Gas { - if m.ReplyCostFn == nil { - panic("not expected to be called") - } - return m.ReplyCostFn(pinned, reply) -} - -func (m MockGasRegister) EventCosts(evts []wasmvmtypes.EventAttribute, _ wasmvmtypes.Events) sdk.Gas { - if m.EventCostsFn == nil { - panic("not expected to be called") - } - return m.EventCostsFn(evts) -} - -func (m MockGasRegister) ToWasmVMGas(source sdk.Gas) uint64 { - if m.ToWasmVMGasFn == nil { - panic("not expected to be called") - } - return m.ToWasmVMGasFn(source) -} - -func (m MockGasRegister) FromWasmVMGas(source uint64) sdk.Gas { - if m.FromWasmVMGasFn == nil { - panic("not expected to be called") - } - return m.FromWasmVMGasFn(source) -} diff --git a/x/wasm/keeper/wasmtesting/message_router.go b/x/wasm/keeper/wasmtesting/message_router.go deleted file mode 100644 index 712e012..0000000 --- a/x/wasm/keeper/wasmtesting/message_router.go +++ /dev/null @@ -1,27 +0,0 @@ -package wasmtesting - -import ( - "github.com/cosmos/cosmos-sdk/baseapp" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// MockMessageRouter mock for testing -type MockMessageRouter struct { - HandlerFn func(msg sdk.Msg) baseapp.MsgServiceHandler -} - -// Handler is the entry point -func (m MockMessageRouter) Handler(msg sdk.Msg) baseapp.MsgServiceHandler { - if m.HandlerFn == nil { - panic("not expected to be called") - } - return m.HandlerFn(msg) -} - -// MessageRouterFunc convenient type to match the keeper.MessageRouter interface -type MessageRouterFunc func(msg sdk.Msg) baseapp.MsgServiceHandler - -// Handler is the entry point -func (m MessageRouterFunc) Handler(msg sdk.Msg) baseapp.MsgServiceHandler { - return m(msg) -} diff --git a/x/wasm/keeper/wasmtesting/messenger.go b/x/wasm/keeper/wasmtesting/messenger.go deleted file mode 100644 index dbafda3..0000000 --- a/x/wasm/keeper/wasmtesting/messenger.go +++ /dev/null @@ -1,38 +0,0 @@ -package wasmtesting - -import ( - "errors" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -type MockMessageHandler struct { - DispatchMsgFn func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) -} - -func (m *MockMessageHandler) DispatchMsg(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - if m.DispatchMsgFn == nil { - panic("not expected to be called") - } - return m.DispatchMsgFn(ctx, contractAddr, contractIBCPortID, msg) -} - -func NewCapturingMessageHandler() (*MockMessageHandler, *[]wasmvmtypes.CosmosMsg) { - var messages []wasmvmtypes.CosmosMsg - return &MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - messages = append(messages, msg) - // return one data item so that this doesn't cause an error in submessage processing (it takes the first element from data) - return nil, [][]byte{{1}}, nil - }, - }, &messages -} - -func NewErroringMessageHandler() *MockMessageHandler { - return &MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - return nil, nil, errors.New("test, ignore") - }, - } -} diff --git a/x/wasm/keeper/wasmtesting/mock_engine.go b/x/wasm/keeper/wasmtesting/mock_engine.go deleted file mode 100644 index 052d165..0000000 --- a/x/wasm/keeper/wasmtesting/mock_engine.go +++ /dev/null @@ -1,402 +0,0 @@ -package wasmtesting - -import ( - "bytes" - "crypto/sha256" - - errorsmod "cosmossdk.io/errors" - - wasmvm "github.com/CosmWasm/wasmvm" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/cometbft/cometbft/libs/rand" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -var _ types.WasmerEngine = &MockWasmer{} - -// MockWasmer implements types.WasmerEngine for testing purpose. One or multiple messages can be stubbed. -// Without a stub function a panic is thrown. -type MockWasmer struct { - CreateFn func(codeID wasmvm.WasmCode) (wasmvm.Checksum, error) - AnalyzeCodeFn func(codeID wasmvm.Checksum) (*wasmvmtypes.AnalysisReport, error) - InstantiateFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, initMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) - ExecuteFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, executeMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) - QueryFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, queryMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) ([]byte, uint64, error) - MigrateFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, migrateMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) - SudoFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, sudoMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) - ReplyFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, reply wasmvmtypes.Reply, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) - GetCodeFn func(codeID wasmvm.Checksum) (wasmvm.WasmCode, error) - CleanupFn func() - IBCChannelOpenFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCChannelOpenMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBC3ChannelOpenResponse, uint64, error) - IBCChannelConnectFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCChannelConnectMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) - IBCChannelCloseFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCChannelCloseMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) - IBCPacketReceiveFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCPacketReceiveMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCReceiveResult, uint64, error) - IBCPacketAckFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCPacketAckMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) - IBCPacketTimeoutFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCPacketTimeoutMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) - PinFn func(checksum wasmvm.Checksum) error - UnpinFn func(checksum wasmvm.Checksum) error - GetMetricsFn func() (*wasmvmtypes.Metrics, error) -} - -func (m *MockWasmer) IBCChannelOpen(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCChannelOpenMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBC3ChannelOpenResponse, uint64, error) { - if m.IBCChannelOpenFn == nil { - panic("not supposed to be called!") - } - return m.IBCChannelOpenFn(codeID, env, msg, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m *MockWasmer) IBCChannelConnect(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCChannelConnectMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - if m.IBCChannelConnectFn == nil { - panic("not supposed to be called!") - } - return m.IBCChannelConnectFn(codeID, env, msg, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m *MockWasmer) IBCChannelClose(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCChannelCloseMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - if m.IBCChannelCloseFn == nil { - panic("not supposed to be called!") - } - return m.IBCChannelCloseFn(codeID, env, msg, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m *MockWasmer) IBCPacketReceive(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCPacketReceiveMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCReceiveResult, uint64, error) { - if m.IBCPacketReceiveFn == nil { - panic("not supposed to be called!") - } - return m.IBCPacketReceiveFn(codeID, env, msg, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m *MockWasmer) IBCPacketAck(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCPacketAckMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - if m.IBCPacketAckFn == nil { - panic("not supposed to be called!") - } - return m.IBCPacketAckFn(codeID, env, msg, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m *MockWasmer) IBCPacketTimeout(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCPacketTimeoutMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - if m.IBCPacketTimeoutFn == nil { - panic("not supposed to be called!") - } - return m.IBCPacketTimeoutFn(codeID, env, msg, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m *MockWasmer) Create(codeID wasmvm.WasmCode) (wasmvm.Checksum, error) { - if m.CreateFn == nil { - panic("not supposed to be called!") - } - return m.CreateFn(codeID) -} - -func (m *MockWasmer) AnalyzeCode(codeID wasmvm.Checksum) (*wasmvmtypes.AnalysisReport, error) { - if m.AnalyzeCodeFn == nil { - panic("not supposed to be called!") - } - return m.AnalyzeCodeFn(codeID) -} - -func (m *MockWasmer) Instantiate(codeID wasmvm.Checksum, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, initMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - if m.InstantiateFn == nil { - panic("not supposed to be called!") - } - return m.InstantiateFn(codeID, env, info, initMsg, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m *MockWasmer) Execute(codeID wasmvm.Checksum, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, executeMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - if m.ExecuteFn == nil { - panic("not supposed to be called!") - } - return m.ExecuteFn(codeID, env, info, executeMsg, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m *MockWasmer) Query(codeID wasmvm.Checksum, env wasmvmtypes.Env, queryMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) ([]byte, uint64, error) { - if m.QueryFn == nil { - panic("not supposed to be called!") - } - return m.QueryFn(codeID, env, queryMsg, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m *MockWasmer) Migrate(codeID wasmvm.Checksum, env wasmvmtypes.Env, migrateMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - if m.MigrateFn == nil { - panic("not supposed to be called!") - } - return m.MigrateFn(codeID, env, migrateMsg, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m *MockWasmer) Sudo(codeID wasmvm.Checksum, env wasmvmtypes.Env, sudoMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - if m.SudoFn == nil { - panic("not supposed to be called!") - } - return m.SudoFn(codeID, env, sudoMsg, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m *MockWasmer) Reply(codeID wasmvm.Checksum, env wasmvmtypes.Env, reply wasmvmtypes.Reply, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - if m.ReplyFn == nil { - panic("not supposed to be called!") - } - return m.ReplyFn(codeID, env, reply, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m *MockWasmer) GetCode(codeID wasmvm.Checksum) (wasmvm.WasmCode, error) { - if m.GetCodeFn == nil { - panic("not supposed to be called!") - } - return m.GetCodeFn(codeID) -} - -func (m *MockWasmer) Cleanup() { - if m.CleanupFn == nil { - panic("not supposed to be called!") - } - m.CleanupFn() -} - -func (m *MockWasmer) Pin(checksum wasmvm.Checksum) error { - if m.PinFn == nil { - panic("not supposed to be called!") - } - return m.PinFn(checksum) -} - -func (m *MockWasmer) Unpin(checksum wasmvm.Checksum) error { - if m.UnpinFn == nil { - panic("not supposed to be called!") - } - return m.UnpinFn(checksum) -} - -func (m *MockWasmer) GetMetrics() (*wasmvmtypes.Metrics, error) { - if m.GetMetricsFn == nil { - panic("not expected to be called") - } - return m.GetMetricsFn() -} - -var AlwaysPanicMockWasmer = &MockWasmer{} - -// SelfCallingInstMockWasmer prepares a Wasmer mock that calls itself on instantiation. -func SelfCallingInstMockWasmer(executeCalled *bool) *MockWasmer { - return &MockWasmer{ - CreateFn: func(code wasmvm.WasmCode) (wasmvm.Checksum, error) { - anyCodeID := bytes.Repeat([]byte{0x1}, 32) - return anyCodeID, nil - }, - InstantiateFn: func(codeID wasmvm.Checksum, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, initMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - return &wasmvmtypes.Response{ - Messages: []wasmvmtypes.SubMsg{ - {Msg: wasmvmtypes.CosmosMsg{ - Wasm: &wasmvmtypes.WasmMsg{Execute: &wasmvmtypes.ExecuteMsg{ContractAddr: env.Contract.Address, Msg: []byte(`{}`)}}, - }}, - }, - }, 1, nil - }, - AnalyzeCodeFn: WithoutIBCAnalyzeFn, - ExecuteFn: func(codeID wasmvm.Checksum, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, executeMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - *executeCalled = true - return &wasmvmtypes.Response{}, 1, nil - }, - } -} - -// IBCContractCallbacks defines the methods from wasmvm to interact with the wasm contract. -// A mock contract would implement the interface to fully simulate a wasm contract's behaviour. -type IBCContractCallbacks interface { - IBCChannelOpen( - codeID wasmvm.Checksum, - env wasmvmtypes.Env, - channel wasmvmtypes.IBCChannelOpenMsg, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.IBC3ChannelOpenResponse, uint64, error) - - IBCChannelConnect( - codeID wasmvm.Checksum, - env wasmvmtypes.Env, - channel wasmvmtypes.IBCChannelConnectMsg, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.IBCBasicResponse, uint64, error) - - IBCChannelClose( - codeID wasmvm.Checksum, - env wasmvmtypes.Env, - channel wasmvmtypes.IBCChannelCloseMsg, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.IBCBasicResponse, uint64, error) - - IBCPacketReceive( - codeID wasmvm.Checksum, - env wasmvmtypes.Env, - packet wasmvmtypes.IBCPacketReceiveMsg, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.IBCReceiveResult, uint64, error) - - IBCPacketAck( - codeID wasmvm.Checksum, - env wasmvmtypes.Env, - ack wasmvmtypes.IBCPacketAckMsg, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.IBCBasicResponse, uint64, error) - - IBCPacketTimeout( - codeID wasmvm.Checksum, - env wasmvmtypes.Env, - packet wasmvmtypes.IBCPacketTimeoutMsg, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.IBCBasicResponse, uint64, error) -} - -type contractExecutable interface { - Execute( - codeID wasmvm.Checksum, - env wasmvmtypes.Env, - info wasmvmtypes.MessageInfo, - executeMsg []byte, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.Response, uint64, error) -} - -// MakeInstantiable adds some noop functions to not fail when contract is used for instantiation -func MakeInstantiable(m *MockWasmer) { - m.CreateFn = HashOnlyCreateFn - m.InstantiateFn = NoOpInstantiateFn - m.AnalyzeCodeFn = WithoutIBCAnalyzeFn -} - -// MakeIBCInstantiable adds some noop functions to not fail when contract is used for instantiation -func MakeIBCInstantiable(m *MockWasmer) { - MakeInstantiable(m) - m.AnalyzeCodeFn = HasIBCAnalyzeFn -} - -// NewIBCContractMockWasmer prepares a mocked wasm_engine for testing with an IBC contract test type. -// It is safe to use the mock with store code and instantiate functions in keeper as is also prepared -// with stubs. Execute is optional. When implemented by the Go test contract then it can be used with -// the mock. -func NewIBCContractMockWasmer(c IBCContractCallbacks) *MockWasmer { - m := &MockWasmer{ - IBCChannelOpenFn: c.IBCChannelOpen, - IBCChannelConnectFn: c.IBCChannelConnect, - IBCChannelCloseFn: c.IBCChannelClose, - IBCPacketReceiveFn: c.IBCPacketReceive, - IBCPacketAckFn: c.IBCPacketAck, - IBCPacketTimeoutFn: c.IBCPacketTimeout, - } - MakeIBCInstantiable(m) - if e, ok := c.(contractExecutable); ok { // optional function - m.ExecuteFn = e.Execute - } - return m -} - -func HashOnlyCreateFn(code wasmvm.WasmCode) (wasmvm.Checksum, error) { - if code == nil { - return nil, errorsmod.Wrap(types.ErrInvalid, "wasm code must not be nil") - } - hash := sha256.Sum256(code) - return hash[:], nil -} - -func NoOpInstantiateFn(wasmvm.Checksum, wasmvmtypes.Env, wasmvmtypes.MessageInfo, []byte, wasmvm.KVStore, wasmvm.GoAPI, wasmvm.Querier, wasmvm.GasMeter, uint64, wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - return &wasmvmtypes.Response{}, 0, nil -} - -func NoOpCreateFn(_ wasmvm.WasmCode) (wasmvm.Checksum, error) { - return rand.Bytes(32), nil -} - -func HasIBCAnalyzeFn(wasmvm.Checksum) (*wasmvmtypes.AnalysisReport, error) { - return &wasmvmtypes.AnalysisReport{ - HasIBCEntryPoints: true, - }, nil -} - -func WithoutIBCAnalyzeFn(wasmvm.Checksum) (*wasmvmtypes.AnalysisReport, error) { - return &wasmvmtypes.AnalysisReport{}, nil -} - -var _ IBCContractCallbacks = &MockIBCContractCallbacks{} - -type MockIBCContractCallbacks struct { - IBCChannelOpenFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCChannelOpenMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBC3ChannelOpenResponse, uint64, error) - IBCChannelConnectFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCChannelConnectMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) - IBCChannelCloseFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCChannelCloseMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) - IBCPacketReceiveFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCPacketReceiveMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCReceiveResult, uint64, error) - IBCPacketAckFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCPacketAckMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) - IBCPacketTimeoutFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCPacketTimeoutMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) -} - -func (m MockIBCContractCallbacks) IBCChannelOpen(codeID wasmvm.Checksum, env wasmvmtypes.Env, channel wasmvmtypes.IBCChannelOpenMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBC3ChannelOpenResponse, uint64, error) { - if m.IBCChannelOpenFn == nil { - panic("not expected to be called") - } - return m.IBCChannelOpenFn(codeID, env, channel, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m MockIBCContractCallbacks) IBCChannelConnect(codeID wasmvm.Checksum, env wasmvmtypes.Env, channel wasmvmtypes.IBCChannelConnectMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - if m.IBCChannelConnectFn == nil { - panic("not expected to be called") - } - return m.IBCChannelConnectFn(codeID, env, channel, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m MockIBCContractCallbacks) IBCChannelClose(codeID wasmvm.Checksum, env wasmvmtypes.Env, channel wasmvmtypes.IBCChannelCloseMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - if m.IBCChannelCloseFn == nil { - panic("not expected to be called") - } - return m.IBCChannelCloseFn(codeID, env, channel, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m MockIBCContractCallbacks) IBCPacketReceive(codeID wasmvm.Checksum, env wasmvmtypes.Env, packet wasmvmtypes.IBCPacketReceiveMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCReceiveResult, uint64, error) { - if m.IBCPacketReceiveFn == nil { - panic("not expected to be called") - } - return m.IBCPacketReceiveFn(codeID, env, packet, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m MockIBCContractCallbacks) IBCPacketAck(codeID wasmvm.Checksum, env wasmvmtypes.Env, ack wasmvmtypes.IBCPacketAckMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - if m.IBCPacketAckFn == nil { - panic("not expected to be called") - } - return m.IBCPacketAckFn(codeID, env, ack, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m MockIBCContractCallbacks) IBCPacketTimeout(codeID wasmvm.Checksum, env wasmvmtypes.Env, packet wasmvmtypes.IBCPacketTimeoutMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - if m.IBCPacketTimeoutFn == nil { - panic("not expected to be called") - } - return m.IBCPacketTimeoutFn(codeID, env, packet, store, goapi, querier, gasMeter, gasLimit, deserCost) -} diff --git a/x/wasm/keeper/wasmtesting/mock_keepers.go b/x/wasm/keeper/wasmtesting/mock_keepers.go deleted file mode 100644 index 021a29f..0000000 --- a/x/wasm/keeper/wasmtesting/mock_keepers.go +++ /dev/null @@ -1,112 +0,0 @@ -package wasmtesting - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" - clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -type MockChannelKeeper struct { - GetChannelFn func(ctx sdk.Context, srcPort, srcChan string) (channel channeltypes.Channel, found bool) - SendPacketFn func(ctx sdk.Context, channelCap *capabilitytypes.Capability, sourcePort string, sourceChannel string, timeoutHeight clienttypes.Height, timeoutTimestamp uint64, data []byte) (uint64, error) - ChanCloseInitFn func(ctx sdk.Context, portID, channelID string, chanCap *capabilitytypes.Capability) error - GetAllChannelsFn func(ctx sdk.Context) []channeltypes.IdentifiedChannel - IterateChannelsFn func(ctx sdk.Context, cb func(channeltypes.IdentifiedChannel) bool) - SetChannelFn func(ctx sdk.Context, portID, channelID string, channel channeltypes.Channel) -} - -func (m *MockChannelKeeper) GetChannel(ctx sdk.Context, srcPort, srcChan string) (channel channeltypes.Channel, found bool) { - if m.GetChannelFn == nil { - panic("not supposed to be called!") - } - return m.GetChannelFn(ctx, srcPort, srcChan) -} - -func (m *MockChannelKeeper) GetAllChannels(ctx sdk.Context) []channeltypes.IdentifiedChannel { - if m.GetAllChannelsFn == nil { - panic("not supposed to be called!") - } - return m.GetAllChannelsFn(ctx) -} - -func (m *MockChannelKeeper) SendPacket(ctx sdk.Context, channelCap *capabilitytypes.Capability, sourcePort string, sourceChannel string, timeoutHeight clienttypes.Height, timeoutTimestamp uint64, data []byte) (uint64, error) { - if m.SendPacketFn == nil { - panic("not supposed to be called!") - } - return m.SendPacketFn(ctx, channelCap, sourcePort, sourceChannel, timeoutHeight, timeoutTimestamp, data) -} - -func (m *MockChannelKeeper) ChanCloseInit(ctx sdk.Context, portID, channelID string, chanCap *capabilitytypes.Capability) error { - if m.ChanCloseInitFn == nil { - panic("not supposed to be called!") - } - return m.ChanCloseInitFn(ctx, portID, channelID, chanCap) -} - -func (m *MockChannelKeeper) IterateChannels(ctx sdk.Context, cb func(channeltypes.IdentifiedChannel) bool) { - if m.IterateChannelsFn == nil { - panic("not expected to be called") - } - m.IterateChannelsFn(ctx, cb) -} - -func (m *MockChannelKeeper) SetChannel(ctx sdk.Context, portID, channelID string, channel channeltypes.Channel) { - if m.GetChannelFn == nil { - panic("not supposed to be called!") - } - m.SetChannelFn(ctx, portID, channelID, channel) -} - -func MockChannelKeeperIterator(s []channeltypes.IdentifiedChannel) func(ctx sdk.Context, cb func(channeltypes.IdentifiedChannel) bool) { - return func(ctx sdk.Context, cb func(channeltypes.IdentifiedChannel) bool) { - for _, channel := range s { - stop := cb(channel) - if stop { - break - } - } - } -} - -type MockCapabilityKeeper struct { - GetCapabilityFn func(ctx sdk.Context, name string) (*capabilitytypes.Capability, bool) - ClaimCapabilityFn func(ctx sdk.Context, cap *capabilitytypes.Capability, name string) error - AuthenticateCapabilityFn func(ctx sdk.Context, capability *capabilitytypes.Capability, name string) bool -} - -func (m MockCapabilityKeeper) GetCapability(ctx sdk.Context, name string) (*capabilitytypes.Capability, bool) { - if m.GetCapabilityFn == nil { - panic("not supposed to be called!") - } - return m.GetCapabilityFn(ctx, name) -} - -func (m MockCapabilityKeeper) ClaimCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) error { - if m.ClaimCapabilityFn == nil { - panic("not supposed to be called!") - } - return m.ClaimCapabilityFn(ctx, cap, name) -} - -func (m MockCapabilityKeeper) AuthenticateCapability(ctx sdk.Context, capability *capabilitytypes.Capability, name string) bool { - if m.AuthenticateCapabilityFn == nil { - panic("not supposed to be called!") - } - return m.AuthenticateCapabilityFn(ctx, capability, name) -} - -var _ types.ICS20TransferPortSource = &MockIBCTransferKeeper{} - -type MockIBCTransferKeeper struct { - GetPortFn func(ctx sdk.Context) string -} - -func (m MockIBCTransferKeeper) GetPort(ctx sdk.Context) string { - if m.GetPortFn == nil { - panic("not expected to be called") - } - return m.GetPortFn(ctx) -} diff --git a/x/wasm/keeper/wasmtesting/msg_dispatcher.go b/x/wasm/keeper/wasmtesting/msg_dispatcher.go deleted file mode 100644 index a660094..0000000 --- a/x/wasm/keeper/wasmtesting/msg_dispatcher.go +++ /dev/null @@ -1,17 +0,0 @@ -package wasmtesting - -import ( - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -type MockMsgDispatcher struct { - DispatchSubmessagesFn func(ctx sdk.Context, contractAddr sdk.AccAddress, ibcPort string, msgs []wasmvmtypes.SubMsg) ([]byte, error) -} - -func (m MockMsgDispatcher) DispatchSubmessages(ctx sdk.Context, contractAddr sdk.AccAddress, ibcPort string, msgs []wasmvmtypes.SubMsg) ([]byte, error) { - if m.DispatchSubmessagesFn == nil { - panic("not expected to be called") - } - return m.DispatchSubmessagesFn(ctx, contractAddr, ibcPort, msgs) -} diff --git a/x/wasm/keeper/wasmtesting/query_handler.go b/x/wasm/keeper/wasmtesting/query_handler.go deleted file mode 100644 index 52cf97d..0000000 --- a/x/wasm/keeper/wasmtesting/query_handler.go +++ /dev/null @@ -1,17 +0,0 @@ -package wasmtesting - -import ( - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -type MockQueryHandler struct { - HandleQueryFn func(ctx sdk.Context, request wasmvmtypes.QueryRequest, caller sdk.AccAddress) ([]byte, error) -} - -func (m *MockQueryHandler) HandleQuery(ctx sdk.Context, caller sdk.AccAddress, request wasmvmtypes.QueryRequest) ([]byte, error) { - if m.HandleQueryFn == nil { - panic("not expected to be called") - } - return m.HandleQueryFn(ctx, request, caller) -} diff --git a/x/wasm/keeper/wasmtesting/store.go b/x/wasm/keeper/wasmtesting/store.go deleted file mode 100644 index 6548c8b..0000000 --- a/x/wasm/keeper/wasmtesting/store.go +++ /dev/null @@ -1,26 +0,0 @@ -package wasmtesting - -import ( - storetypes "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// MockCommitMultiStore mock with a CacheMultiStore to capture commits -type MockCommitMultiStore struct { - sdk.CommitMultiStore - Committed []bool -} - -func (m *MockCommitMultiStore) CacheMultiStore() storetypes.CacheMultiStore { - m.Committed = append(m.Committed, false) - return &mockCMS{m, &m.Committed[len(m.Committed)-1]} -} - -type mockCMS struct { - sdk.CommitMultiStore - committed *bool -} - -func (m *mockCMS) Write() { - *m.committed = true -} diff --git a/x/wasm/migrations/v1/store.go b/x/wasm/migrations/v1/store.go deleted file mode 100644 index f2c6dbb..0000000 --- a/x/wasm/migrations/v1/store.go +++ /dev/null @@ -1,36 +0,0 @@ -package v1 - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// AddToSecondIndexFn creates a secondary index entry for the creator fo the contract -type AddToSecondIndexFn func(ctx sdk.Context, creatorAddress sdk.AccAddress, position *types.AbsoluteTxPosition, contractAddress sdk.AccAddress) - -// Keeper abstract keeper -type wasmKeeper interface { - IterateContractInfo(ctx sdk.Context, cb func(sdk.AccAddress, types.ContractInfo) bool) -} - -// Migrator is a struct for handling in-place store migrations. -type Migrator struct { - keeper wasmKeeper - addToSecondIndexFn AddToSecondIndexFn -} - -// NewMigrator returns a new Migrator. -func NewMigrator(k wasmKeeper, fn AddToSecondIndexFn) Migrator { - return Migrator{keeper: k, addToSecondIndexFn: fn} -} - -// Migrate1to2 migrates from version 1 to 2. -func (m Migrator) Migrate1to2(ctx sdk.Context) error { - m.keeper.IterateContractInfo(ctx, func(contractAddr sdk.AccAddress, contractInfo types.ContractInfo) bool { - creator := sdk.MustAccAddressFromBech32(contractInfo.Creator) - m.addToSecondIndexFn(ctx, creator, contractInfo.Created, contractAddr) - return false - }) - return nil -} diff --git a/x/wasm/migrations/v1/store_test.go b/x/wasm/migrations/v1/store_test.go deleted file mode 100644 index 990baac..0000000 --- a/x/wasm/migrations/v1/store_test.go +++ /dev/null @@ -1,71 +0,0 @@ -package v1_test - -import ( - "bytes" - "encoding/json" - "testing" - - "github.com/terpnetwork/terp-core/x/wasm/keeper" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestMigrate1To2(t *testing.T) { - const AvailableCapabilities = "iterator,staking,stargate,cosmwasm_1_1" - ctx, keepers := keeper.CreateTestInput(t, false, AvailableCapabilities) - wasmKeeper := keepers.WasmKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := sdk.AccAddress(bytes.Repeat([]byte{1}, address.Len)) - keepers.Faucet.Fund(ctx, creator, deposit...) - example := keeper.StoreHackatomExampleContract(t, ctx, keepers) - - initMsg := keeper.HackatomExampleInitMsg{ - Verifier: keeper.RandomAccountAddress(t), - Beneficiary: keeper.RandomAccountAddress(t), - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - - em := sdk.NewEventManager() - - // create with no balance is also legal - gotContractAddr1, _, err := keepers.ContractKeeper.Instantiate(ctx.WithEventManager(em), example.CodeID, creator, nil, initMsgBz, "demo contract 1", nil) - require.NoError(t, err) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // create with no balance is also legal - gotContractAddr2, _, err := keepers.ContractKeeper.Instantiate(ctx.WithEventManager(em), example.CodeID, creator, nil, initMsgBz, "demo contract 1", nil) - require.NoError(t, err) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // create with no balance is also legal - gotContractAddr3, _, err := keepers.ContractKeeper.Instantiate(ctx.WithEventManager(em), example.CodeID, creator, nil, initMsgBz, "demo contract 1", nil) - require.NoError(t, err) - - info1 := wasmKeeper.GetContractInfo(ctx, gotContractAddr1) - info2 := wasmKeeper.GetContractInfo(ctx, gotContractAddr2) - info3 := wasmKeeper.GetContractInfo(ctx, gotContractAddr3) - - // remove key - ctx.KVStore(keepers.WasmStoreKey).Delete(types.GetContractByCreatorSecondaryIndexKey(creator, info1.Created.Bytes(), gotContractAddr1)) - ctx.KVStore(keepers.WasmStoreKey).Delete(types.GetContractByCreatorSecondaryIndexKey(creator, info2.Created.Bytes(), gotContractAddr2)) - ctx.KVStore(keepers.WasmStoreKey).Delete(types.GetContractByCreatorSecondaryIndexKey(creator, info3.Created.Bytes(), gotContractAddr3)) - - // migrator - err = keeper.NewMigrator(*wasmKeeper, nil).Migrate1to2(ctx) - require.NoError(t, err) - - // check new store - var allContract []string - wasmKeeper.IterateContractsByCreator(ctx, creator, func(addr sdk.AccAddress) bool { - allContract = append(allContract, addr.String()) - return false - }) - - require.Equal(t, []string{gotContractAddr1.String(), gotContractAddr2.String(), gotContractAddr3.String()}, allContract) -} diff --git a/x/wasm/migrations/v2/store.go b/x/wasm/migrations/v2/store.go deleted file mode 100644 index f6318c0..0000000 --- a/x/wasm/migrations/v2/store.go +++ /dev/null @@ -1,33 +0,0 @@ -package v2 - -import ( - "github.com/cosmos/cosmos-sdk/codec" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/terpnetwork/terp-core/x/wasm/exported" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// MigrateStore migrates the x/wasm module state from the consensus version 2 to -// version 3. Specifically, it takes the parameters that are currently stored -// and managed by the x/params module and stores them directly into the x/wasm -// module state. -func MigrateStore(ctx sdk.Context, storeKey storetypes.StoreKey, legacySubspace exported.Subspace, cdc codec.BinaryCodec) error { - store := ctx.KVStore(storeKey) - var currParams types.Params - legacySubspace.GetParamSet(ctx, &currParams) - - if err := currParams.ValidateBasic(); err != nil { - return err - } - - bz, err := cdc.Marshal(&currParams) - if err != nil { - return err - } - - store.Set(types.ParamsKey, bz) - - return nil -} diff --git a/x/wasm/migrations/v2/store_test.go b/x/wasm/migrations/v2/store_test.go deleted file mode 100644 index c5dcc7e..0000000 --- a/x/wasm/migrations/v2/store_test.go +++ /dev/null @@ -1,44 +0,0 @@ -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 deleted file mode 100644 index 371e804..0000000 --- a/x/wasm/module.go +++ /dev/null @@ -1,314 +0,0 @@ -package wasm - -import ( - "context" - "encoding/json" - "fmt" - "runtime/debug" - "strings" - - "cosmossdk.io/core/appmodule" - - "github.com/cosmos/cosmos-sdk/baseapp" - - wasmvm "github.com/CosmWasm/wasmvm" - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - cdctypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/server" - servertypes "github.com/cosmos/cosmos-sdk/server/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cast" - "github.com/spf13/cobra" - - "github.com/terpnetwork/terp-core/x/wasm/client/cli" - "github.com/terpnetwork/terp-core/x/wasm/exported" - "github.com/terpnetwork/terp-core/x/wasm/keeper" - "github.com/terpnetwork/terp-core/x/wasm/simulation" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -var ( - _ module.AppModuleBasic = AppModuleBasic{} - _ module.AppModuleSimulation = AppModule{} -) - -// Module init related flags -const ( - flagWasmMemoryCacheSize = "wasm.memory_cache_size" - flagWasmQueryGasLimit = "wasm.query_gas_limit" - flagWasmSimulationGasLimit = "wasm.simulation_gas_limit" -) - -// AppModuleBasic defines the basic application module used by the wasm module. -type AppModuleBasic struct{} - -func (b AppModuleBasic) RegisterLegacyAminoCodec(amino *codec.LegacyAmino) { - RegisterCodec(amino) -} - -func (b AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, serveMux *runtime.ServeMux) { - err := types.RegisterQueryHandlerClient(context.Background(), serveMux, types.NewQueryClient(clientCtx)) - if err != nil { - panic(err) - } -} - -// Name returns the wasm module's name. -func (AppModuleBasic) Name() string { - return ModuleName -} - -// DefaultGenesis returns default genesis state as raw bytes for the wasm -// module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(&GenesisState{ - Params: DefaultParams(), - }) -} - -// ValidateGenesis performs genesis state validation for the wasm module. -func (b AppModuleBasic) ValidateGenesis(marshaler codec.JSONCodec, _ client.TxEncodingConfig, message json.RawMessage) error { - var data GenesisState - err := marshaler.UnmarshalJSON(message, &data) - if err != nil { - return err - } - return ValidateGenesis(data) -} - -// GetTxCmd returns the root tx command for the wasm module. -func (b AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd() -} - -// GetQueryCmd returns no root query command for the wasm module. -func (b AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd() -} - -// RegisterInterfaces implements InterfaceModule -func (b AppModuleBasic) RegisterInterfaces(registry cdctypes.InterfaceRegistry) { - types.RegisterInterfaces(registry) -} - -// ____________________________________________________________________________ -var _ appmodule.AppModule = AppModule{} - -// AppModule implements an application module for the wasm module. -type AppModule struct { - AppModuleBasic - cdc codec.Codec - keeper *Keeper - validatorSetSource keeper.ValidatorSetSource - accountKeeper types.AccountKeeper // for simulation - bankKeeper simulation.BankKeeper - router keeper.MessageRouter - // legacySubspace is used solely for migration of x/params managed parameters - legacySubspace exported.Subspace -} - -// NewAppModule creates a new AppModule object -func NewAppModule( - cdc codec.Codec, - keeper *Keeper, - validatorSetSource keeper.ValidatorSetSource, - ak types.AccountKeeper, - bk simulation.BankKeeper, - router *baseapp.MsgServiceRouter, - ss exported.Subspace, -) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - cdc: cdc, - keeper: keeper, - validatorSetSource: validatorSetSource, - accountKeeper: ak, - bankKeeper: bk, - router: router, - legacySubspace: ss, - } -} - -// IsOnePerModuleType implements the depinject.OnePerModuleType interface. -func (am AppModule) IsOnePerModuleType() { // marker -} - -// IsAppModule implements the appmodule.AppModule interface. -func (am AppModule) IsAppModule() { // marker -} - -// ConsensusVersion is a sequence number for state-breaking change of the -// module. It should be incremented on each consensus-breaking change -// introduced by the module. To avoid wrong/empty versions, the initial version -// should be set to 1. -func (AppModule) ConsensusVersion() uint64 { return 3 } - -func (am AppModule) RegisterServices(cfg module.Configurator) { - types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) - types.RegisterQueryServer(cfg.QueryServer(), NewQuerier(am.keeper)) - - m := keeper.NewMigrator(*am.keeper, am.legacySubspace) - err := cfg.RegisterMigration(types.ModuleName, 1, m.Migrate1to2) - if err != nil { - panic(err) - } - err = cfg.RegisterMigration(types.ModuleName, 2, m.Migrate2to3) - if err != nil { - panic(err) - } -} - -// RegisterInvariants registers the wasm module invariants. -func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -// QuerierRoute returns the wasm module's querier route name. -func (AppModule) QuerierRoute() string { - return QuerierRoute -} - -// InitGenesis performs genesis initialization for the wasm module. It returns -// no validator updates. -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate { - var genesisState GenesisState - cdc.MustUnmarshalJSON(data, &genesisState) - validators, err := InitGenesis(ctx, am.keeper, genesisState) - if err != nil { - panic(err) - } - return validators -} - -// ExportGenesis returns the exported genesis state as raw bytes for the wasm -// module. -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { - gs := ExportGenesis(ctx, am.keeper) - return cdc.MustMarshalJSON(gs) -} - -// BeginBlock returns the begin blocker for the wasm module. -func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} - -// EndBlock returns the end blocker for the wasm module. It returns no validator -// updates. -func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} - -// ____________________________________________________________________________ - -// AppModuleSimulation functions - -// GenerateGenesisState creates a randomized GenState of the bank module. -func (AppModule) GenerateGenesisState(simState *module.SimulationState) { - simulation.RandomizedGenState(simState) -} - -// ProposalMsgs returns msgs used for governance proposals for simulations. -func (am AppModule) ProposalMsgs(simState module.SimulationState) []simtypes.WeightedProposalMsg { - return simulation.ProposalMsgs(am.bankKeeper, am.keeper) -} - -// RegisterStoreDecoder registers a decoder for supply module's types -func (am AppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) { -} - -// WeightedOperations returns the all the gov module operations with their respective weights. -func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { - return simulation.WeightedOperations(&simState, am.accountKeeper, am.bankKeeper, am.keeper) -} - -// ____________________________________________________________________________ - -// AddModuleInitFlags implements servertypes.ModuleInitFlags interface. -func AddModuleInitFlags(startCmd *cobra.Command) { - defaults := DefaultWasmConfig() - startCmd.Flags().Uint32(flagWasmMemoryCacheSize, defaults.MemoryCacheSize, "Sets the size in MiB (NOT bytes) of an in-memory cache for Wasm modules. Set to 0 to disable.") - startCmd.Flags().Uint64(flagWasmQueryGasLimit, defaults.SmartQueryGasLimit, "Set the max gas that can be spent on executing a query with a Wasm contract") - startCmd.Flags().String(flagWasmSimulationGasLimit, "", "Set the max gas that can be spent when executing a simulation TX") - - startCmd.PreRunE = chainPreRuns(checkLibwasmVersion, startCmd.PreRunE) -} - -// ReadWasmConfig reads the wasm specifig configuration -func ReadWasmConfig(opts servertypes.AppOptions) (types.WasmConfig, error) { - cfg := types.DefaultWasmConfig() - var err error - if v := opts.Get(flagWasmMemoryCacheSize); v != nil { - if cfg.MemoryCacheSize, err = cast.ToUint32E(v); err != nil { - return cfg, err - } - } - if v := opts.Get(flagWasmQueryGasLimit); v != nil { - if cfg.SmartQueryGasLimit, err = cast.ToUint64E(v); err != nil { - return cfg, err - } - } - if v := opts.Get(flagWasmSimulationGasLimit); v != nil { - if raw, ok := v.(string); !ok || raw != "" { - limit, err := cast.ToUint64E(v) // non empty string set - if err != nil { - return cfg, err - } - cfg.SimulationGasLimit = &limit - } - } - // attach contract debugging to global "trace" flag - if v := opts.Get(server.FlagTrace); v != nil { - if cfg.ContractDebugMode, err = cast.ToBoolE(v); err != nil { - return cfg, err - } - } - return cfg, nil -} - -func getExpectedLibwasmVersion() string { - buildInfo, ok := debug.ReadBuildInfo() - if !ok { - panic("can't read build info") - } - for _, d := range buildInfo.Deps { - if d.Path != "github.com/CosmWasm/wasmvm" { - continue - } - if d.Replace != nil { - return d.Replace.Version - } - return d.Version - } - return "" -} - -func checkLibwasmVersion(_ *cobra.Command, _ []string) error { - wasmVersion, err := wasmvm.LibwasmvmVersion() - if err != nil { - return fmt.Errorf("unable to retrieve libwasmversion %w", err) - } - wasmExpectedVersion := getExpectedLibwasmVersion() - if wasmExpectedVersion == "" { - return fmt.Errorf("wasmvm module not exist") - } - if !strings.Contains(wasmExpectedVersion, wasmVersion) { - return fmt.Errorf("libwasmversion mismatch. got: %s; expected: %s", wasmVersion, wasmExpectedVersion) - } - return nil -} - -type preRunFn func(cmd *cobra.Command, args []string) error - -func chainPreRuns(pfns ...preRunFn) preRunFn { - return func(cmd *cobra.Command, args []string) error { - for _, pfn := range pfns { - if pfn != nil { - if err := pfn(cmd, args); err != nil { - return err - } - } - } - return nil - } -} diff --git a/x/wasm/module_test.go b/x/wasm/module_test.go deleted file mode 100644 index 04fcbb8..0000000 --- a/x/wasm/module_test.go +++ /dev/null @@ -1,651 +0,0 @@ -package wasm - -import ( - "bytes" - "encoding/json" - "os" - "strings" - "testing" - - servertypes "github.com/cosmos/cosmos-sdk/server/types" - "github.com/spf13/viper" - - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cometbft/cometbft/crypto/ed25519" - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - "github.com/cosmos/cosmos-sdk/types/module" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/app/params" - "github.com/terpnetwork/terp-core/x/wasm/exported" - "github.com/terpnetwork/terp-core/x/wasm/keeper" - "github.com/terpnetwork/terp-core/x/wasm/keeper/testdata" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -type mockSubspace struct { - ps types.Params -} - -func newMockSubspace(ps types.Params) mockSubspace { - return mockSubspace{ps: ps} -} - -func (ms mockSubspace) GetParamSet(ctx sdk.Context, ps exported.ParamSet) { - *ps.(*types.Params) = ms.ps -} - -type testData struct { - module AppModule - ctx sdk.Context - acctKeeper authkeeper.AccountKeeper - keeper Keeper - bankKeeper bankkeeper.Keeper - stakingKeeper *stakingkeeper.Keeper - faucet *keeper.TestFaucet - grpcQueryRouter *baseapp.GRPCQueryRouter - msgServiceRouter *baseapp.MsgServiceRouter - encConf params.EncodingConfig -} - -func setupTest(t *testing.T) testData { - ctx, keepers := CreateTestInput(t, false, "iterator,staking,stargate,cosmwasm_1_1") - encConf := keeper.MakeEncodingConfig(t) - queryRouter := baseapp.NewGRPCQueryRouter() - serviceRouter := baseapp.NewMsgServiceRouter() - queryRouter.SetInterfaceRegistry(encConf.InterfaceRegistry) - serviceRouter.SetInterfaceRegistry(encConf.InterfaceRegistry) - data := testData{ - module: NewAppModule(encConf.Marshaler, keepers.WasmKeeper, keepers.StakingKeeper, keepers.AccountKeeper, keepers.BankKeeper, nil, newMockSubspace(types.DefaultParams())), - ctx: ctx, - acctKeeper: keepers.AccountKeeper, - keeper: *keepers.WasmKeeper, - bankKeeper: keepers.BankKeeper, - stakingKeeper: keepers.StakingKeeper, - faucet: keepers.Faucet, - grpcQueryRouter: queryRouter, - msgServiceRouter: serviceRouter, - encConf: encConf, - } - data.module.RegisterServices(module.NewConfigurator(encConf.Marshaler, serviceRouter, queryRouter)) - return data -} - -func keyPubAddr() sdk.AccAddress { - key := ed25519.GenPrivKey() - pub := key.PubKey() - addr := sdk.AccAddress(pub.Address()) - return addr -} - -func mustLoad(path string) []byte { - bz, err := os.ReadFile(path) - if err != nil { - panic(err) - } - return bz -} - -var ( - addrAcc1 = keyPubAddr() - addr1 = addrAcc1.String() - testContract = mustLoad("./keeper/testdata/hackatom.wasm") - maskContract = testdata.ReflectContractWasm() - oldContract = mustLoad("./testdata/escrow_0.7.wasm") -) - -func TestHandleCreate(t *testing.T) { - cases := map[string]struct { - msg sdk.Msg - isValid bool - }{ - "empty": { - msg: &MsgStoreCode{}, - isValid: false, - }, - "invalid wasm": { - msg: &MsgStoreCode{ - Sender: addr1, - WASMByteCode: []byte("foobar"), - }, - isValid: false, - }, - "valid wasm": { - msg: &MsgStoreCode{ - Sender: addr1, - WASMByteCode: testContract, - }, - isValid: true, - }, - "other valid wasm": { - msg: &MsgStoreCode{ - Sender: addr1, - WASMByteCode: maskContract, - }, - isValid: true, - }, - "old wasm (0.7)": { - msg: &MsgStoreCode{ - Sender: addr1, - WASMByteCode: oldContract, - }, - isValid: false, - }, - } - - for name, tc := range cases { - tc := tc - t.Run(name, func(t *testing.T) { - data := setupTest(t) - - h := data.msgServiceRouter.Handler(tc.msg) - // q := data.grpcQueryRouter.Route(sdk.MsgTypeURL(tc.msg)) - q := data.grpcQueryRouter - - res, err := h(data.ctx, tc.msg) - if !tc.isValid { - require.Error(t, err, "%#v", res) - assertCodeList(t, q, data.ctx, 0, data.encConf.Marshaler) - assertCodeBytes(t, q, data.ctx, 1, nil, data.encConf.Marshaler) - return - } - require.NoError(t, err) - assertCodeList(t, q, data.ctx, 1, data.encConf.Marshaler) - }) - } -} - -type initMsg struct { - Verifier sdk.AccAddress `json:"verifier"` - Beneficiary sdk.AccAddress `json:"beneficiary"` -} - -type state struct { - Verifier string `json:"verifier"` - Beneficiary string `json:"beneficiary"` - Funder string `json:"funder"` -} - -func TestHandleInstantiate(t *testing.T) { - data := setupTest(t) - creator := data.faucet.NewFundedRandomAccount(data.ctx, sdk.NewInt64Coin("denom", 100000)) - - msg := &MsgStoreCode{ - Sender: creator.String(), - WASMByteCode: testContract, - } - - h := data.msgServiceRouter.Handler(msg) - q := data.grpcQueryRouter - - res, err := h(data.ctx, msg) - require.NoError(t, err) - assertStoreCodeResponse(t, res.Data, 1) - - bob := keyPubAddr() - fred := keyPubAddr() - - initPayload := initMsg{ - Verifier: fred, - Beneficiary: bob, - } - initMsgBz, err := json.Marshal(initPayload) - require.NoError(t, err) - - // create with no balance is also legal - initMsg := &MsgInstantiateContract{ - Sender: creator.String(), - CodeID: firstCodeID, - Msg: initMsgBz, - Funds: nil, - Label: "testing", - } - h = data.msgServiceRouter.Handler(initMsg) - res, err = h(data.ctx, initMsg) - require.NoError(t, err) - contractBech32Addr := parseInitResponse(t, res.Data) - - require.Equal(t, "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr", contractBech32Addr) - // this should be standard x/wasm init event, nothing from contract - require.Equal(t, 2, len(res.Events), prettyEvents(res.Events)) - require.Equal(t, "instantiate", res.Events[0].Type) - require.Equal(t, "wasm", res.Events[1].Type) - assertAttribute(t, "_contract_address", contractBech32Addr, res.Events[1].Attributes[0]) - - assertCodeList(t, q, data.ctx, 1, data.encConf.Marshaler) - assertCodeBytes(t, q, data.ctx, 1, testContract, data.encConf.Marshaler) - - assertContractList(t, q, data.ctx, 1, []string{contractBech32Addr}, data.encConf.Marshaler) - assertContractInfo(t, q, data.ctx, contractBech32Addr, 1, creator, data.encConf.Marshaler) - assertContractState(t, q, data.ctx, contractBech32Addr, state{ - Verifier: fred.String(), - Beneficiary: bob.String(), - Funder: creator.String(), - }, data.encConf.Marshaler) -} - -func TestHandleExecute(t *testing.T) { - data := setupTest(t) - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) - - creator := data.faucet.NewFundedRandomAccount(data.ctx, deposit.Add(deposit...)...) - fred := data.faucet.NewFundedRandomAccount(data.ctx, topUp...) - - msg := &MsgStoreCode{ - Sender: creator.String(), - WASMByteCode: testContract, - } - h := data.msgServiceRouter.Handler(msg) - q := data.grpcQueryRouter - res, err := h(data.ctx, msg) - require.NoError(t, err) - assertStoreCodeResponse(t, res.Data, 1) - - bob := keyPubAddr() - initMsg := initMsg{ - Verifier: fred, - Beneficiary: bob, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - - initCmd := &MsgInstantiateContract{ - Sender: creator.String(), - CodeID: firstCodeID, - Msg: initMsgBz, - Funds: deposit, - Label: "testing", - } - h = data.msgServiceRouter.Handler(initCmd) - res, err = h(data.ctx, initCmd) - require.NoError(t, err) - contractBech32Addr := parseInitResponse(t, res.Data) - - require.Equal(t, "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr", contractBech32Addr) - // this should be standard x/wasm message event, init event, plus a bank send event (2), with no custom contract events - require.Equal(t, 5, len(res.Events), prettyEvents(res.Events)) - require.Equal(t, "coin_spent", res.Events[0].Type) - require.Equal(t, "coin_received", res.Events[1].Type) - require.Equal(t, "transfer", res.Events[2].Type) - require.Equal(t, "instantiate", res.Events[3].Type) - require.Equal(t, "wasm", res.Events[4].Type) - assertAttribute(t, "_contract_address", contractBech32Addr, res.Events[4].Attributes[0]) - - // ensure bob doesn't exist - bobAcct := data.acctKeeper.GetAccount(data.ctx, bob) - require.Nil(t, bobAcct) - - // ensure funder has reduced balance - creatorAcct := data.acctKeeper.GetAccount(data.ctx, creator) - require.NotNil(t, creatorAcct) - // we started at 2*deposit, should have spent one above - assert.Equal(t, deposit, data.bankKeeper.GetAllBalances(data.ctx, creatorAcct.GetAddress())) - - // ensure contract has updated balance - contractAddr, _ := sdk.AccAddressFromBech32(contractBech32Addr) - contractAcct := data.acctKeeper.GetAccount(data.ctx, contractAddr) - require.NotNil(t, contractAcct) - assert.Equal(t, deposit, data.bankKeeper.GetAllBalances(data.ctx, contractAcct.GetAddress())) - - execCmd := &MsgExecuteContract{ - Sender: fred.String(), - Contract: contractBech32Addr, - Msg: []byte(`{"release":{}}`), - Funds: topUp, - } - h = data.msgServiceRouter.Handler(execCmd) - res, err = h(data.ctx, execCmd) - require.NoError(t, err) - // from https://github.com/CosmWasm/cosmwasm/blob/master/contracts/hackatom/src/contract.rs#L167 - assertExecuteResponse(t, res.Data, []byte{0xf0, 0x0b, 0xaa}) - - // this should be standard message event, plus x/wasm init event, plus 2 bank send event, plus a special event from the contract - require.Equal(t, 9, len(res.Events), prettyEvents(res.Events)) - - assert.Equal(t, "coin_spent", res.Events[0].Type) - assert.Equal(t, "coin_received", res.Events[1].Type) - - require.Equal(t, "transfer", res.Events[2].Type) - require.Len(t, res.Events[2].Attributes, 3) - assertAttribute(t, "recipient", contractBech32Addr, res.Events[2].Attributes[0]) - assertAttribute(t, "sender", fred.String(), res.Events[2].Attributes[1]) - assertAttribute(t, "amount", "5000denom", res.Events[2].Attributes[2]) - - assert.Equal(t, "execute", res.Events[3].Type) - - // custom contract event attribute - assert.Equal(t, "wasm", res.Events[4].Type) - assertAttribute(t, "_contract_address", contractBech32Addr, res.Events[4].Attributes[0]) - assertAttribute(t, "action", "release", res.Events[4].Attributes[1]) - // custom contract event - assert.Equal(t, "wasm-hackatom", res.Events[5].Type) - assertAttribute(t, "_contract_address", contractBech32Addr, res.Events[5].Attributes[0]) - assertAttribute(t, "action", "release", res.Events[5].Attributes[1]) - // second transfer (this without conflicting message) - assert.Equal(t, "coin_spent", res.Events[6].Type) - assert.Equal(t, "coin_received", res.Events[7].Type) - - assert.Equal(t, "transfer", res.Events[8].Type) - assertAttribute(t, "recipient", bob.String(), res.Events[8].Attributes[0]) - assertAttribute(t, "sender", contractBech32Addr, res.Events[8].Attributes[1]) - assertAttribute(t, "amount", "105000denom", res.Events[8].Attributes[2]) - // finally, standard x/wasm tag - - // ensure bob now exists and got both payments released - bobAcct = data.acctKeeper.GetAccount(data.ctx, bob) - require.NotNil(t, bobAcct) - balance := data.bankKeeper.GetAllBalances(data.ctx, bobAcct.GetAddress()) - assert.Equal(t, deposit.Add(topUp...), balance) - - // ensure contract has updated balance - contractAcct = data.acctKeeper.GetAccount(data.ctx, contractAddr) - require.NotNil(t, contractAcct) - assert.Equal(t, sdk.Coins{}, data.bankKeeper.GetAllBalances(data.ctx, contractAcct.GetAddress())) - - // ensure all contract state is as after init - assertCodeList(t, q, data.ctx, 1, data.encConf.Marshaler) - assertCodeBytes(t, q, data.ctx, 1, testContract, data.encConf.Marshaler) - - assertContractList(t, q, data.ctx, 1, []string{contractBech32Addr}, data.encConf.Marshaler) - assertContractInfo(t, q, data.ctx, contractBech32Addr, 1, creator, data.encConf.Marshaler) - assertContractState(t, q, data.ctx, contractBech32Addr, state{ - Verifier: fred.String(), - Beneficiary: bob.String(), - Funder: creator.String(), - }, data.encConf.Marshaler) -} - -func TestHandleExecuteEscrow(t *testing.T) { - data := setupTest(t) - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) - creator := sdk.AccAddress(bytes.Repeat([]byte{1}, address.Len)) - data.faucet.Fund(data.ctx, creator, sdk.NewInt64Coin("denom", 100000)) - fred := data.faucet.NewFundedRandomAccount(data.ctx, topUp...) - - msg := &MsgStoreCode{ - Sender: creator.String(), - WASMByteCode: testContract, - } - - h := data.msgServiceRouter.Handler(msg) - _, err := h(data.ctx, msg) - require.NoError(t, err) - - bob := keyPubAddr() - initMsg := map[string]interface{}{ - "verifier": fred.String(), - "beneficiary": bob.String(), - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - - initCmd := MsgInstantiateContract{ - Sender: creator.String(), - CodeID: firstCodeID, - Msg: initMsgBz, - Funds: deposit, - Label: "testing", - } - h = data.msgServiceRouter.Handler(&initCmd) - res, err := h(data.ctx, &initCmd) - require.NoError(t, err) - contractBech32Addr := parseInitResponse(t, res.Data) - require.Equal(t, "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr", contractBech32Addr) - - handleMsg := map[string]interface{}{ - "release": map[string]interface{}{}, - } - handleMsgBz, err := json.Marshal(handleMsg) - require.NoError(t, err) - - execCmd := MsgExecuteContract{ - Sender: fred.String(), - Contract: contractBech32Addr, - Msg: handleMsgBz, - Funds: topUp, - } - h = data.msgServiceRouter.Handler(&execCmd) - res, err = h(data.ctx, &execCmd) - require.NoError(t, err) - // from https://github.com/CosmWasm/cosmwasm/blob/master/contracts/hackatom/src/contract.rs#L167 - assertExecuteResponse(t, res.Data, []byte{0xf0, 0x0b, 0xaa}) - - // ensure bob now exists and got both payments released - bobAcct := data.acctKeeper.GetAccount(data.ctx, bob) - require.NotNil(t, bobAcct) - balance := data.bankKeeper.GetAllBalances(data.ctx, bobAcct.GetAddress()) - assert.Equal(t, deposit.Add(topUp...), balance) - - // ensure contract has updated balance - contractAddr, _ := sdk.AccAddressFromBech32(contractBech32Addr) - contractAcct := data.acctKeeper.GetAccount(data.ctx, contractAddr) - require.NotNil(t, contractAcct) - assert.Equal(t, sdk.Coins{}, data.bankKeeper.GetAllBalances(data.ctx, contractAcct.GetAddress())) -} - -func TestReadWasmConfig(t *testing.T) { - withViper := func(s string) *viper.Viper { - v := viper.New() - v.SetConfigType("toml") - require.NoError(t, v.ReadConfig(strings.NewReader(s))) - return v - } - var one uint64 = 1 - defaults := DefaultWasmConfig() - - specs := map[string]struct { - src servertypes.AppOptions - exp types.WasmConfig - }{ - "set query gas limit via opts": { - src: AppOptionsMock{ - "wasm.query_gas_limit": 1, - }, - exp: types.WasmConfig{ - SmartQueryGasLimit: 1, - MemoryCacheSize: defaults.MemoryCacheSize, - }, - }, - "set cache via opts": { - src: AppOptionsMock{ - "wasm.memory_cache_size": 2, - }, - exp: types.WasmConfig{ - MemoryCacheSize: 2, - SmartQueryGasLimit: defaults.SmartQueryGasLimit, - }, - }, - "set debug via opts": { - src: AppOptionsMock{ - "trace": true, - }, - exp: types.WasmConfig{ - SmartQueryGasLimit: defaults.SmartQueryGasLimit, - MemoryCacheSize: defaults.MemoryCacheSize, - ContractDebugMode: true, - }, - }, - "all defaults when no options set": { - src: AppOptionsMock{}, - exp: defaults, - }, - "default config template values": { - src: withViper(types.DefaultConfigTemplate()), - exp: defaults, - }, - "custom config template values": { - src: withViper(types.ConfigTemplate(types.WasmConfig{ - SimulationGasLimit: &one, - SmartQueryGasLimit: 2, - MemoryCacheSize: 3, - })), - exp: types.WasmConfig{ - SimulationGasLimit: &one, - SmartQueryGasLimit: 2, - MemoryCacheSize: 3, - ContractDebugMode: false, - }, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - got, err := ReadWasmConfig(spec.src) - require.NoError(t, err) - assert.Equal(t, spec.exp, got) - }) - } -} - -type AppOptionsMock map[string]interface{} - -func (a AppOptionsMock) Get(s string) interface{} { - return a[s] -} - -type prettyEvent struct { - Type string - Attr []sdk.Attribute -} - -func prettyEvents(evts []abci.Event) string { - res := make([]prettyEvent, len(evts)) - for i, e := range evts { - res[i] = prettyEvent{ - Type: e.Type, - Attr: prettyAttrs(e.Attributes), - } - } - bz, err := json.MarshalIndent(res, "", " ") - if err != nil { - panic(err) - } - return string(bz) -} - -func prettyAttrs(attrs []abci.EventAttribute) []sdk.Attribute { - pretty := make([]sdk.Attribute, len(attrs)) - for i, a := range attrs { - pretty[i] = prettyAttr(a) - } - return pretty -} - -func prettyAttr(attr abci.EventAttribute) sdk.Attribute { - return sdk.NewAttribute(attr.Key, attr.Value) -} - -func assertAttribute(t *testing.T, key string, value string, attr abci.EventAttribute) { - t.Helper() - assert.Equal(t, key, attr.Key, prettyAttr(attr)) - assert.Equal(t, value, attr.Value, prettyAttr(attr)) -} - -func assertCodeList(t *testing.T, q *baseapp.GRPCQueryRouter, ctx sdk.Context, expectedNum int, marshaler codec.Codec) { - t.Helper() - path := "/cosmwasm.wasm.v1.Query/Codes" - resp, sdkerr := q.Route(path)(ctx, abci.RequestQuery{Path: path}) - require.NoError(t, sdkerr) - require.True(t, resp.IsOK()) - - bz := resp.Value - if len(bz) == 0 { - require.Equal(t, expectedNum, 0) - return - } - - var res types.QueryCodesResponse - require.NoError(t, marshaler.Unmarshal(bz, &res)) - assert.Equal(t, expectedNum, len(res.CodeInfos)) -} - -func assertCodeBytes(t *testing.T, q *baseapp.GRPCQueryRouter, ctx sdk.Context, codeID uint64, expectedBytes []byte, marshaler codec.Codec) { //nolint:unparam - t.Helper() - bz, err := marshaler.Marshal(&types.QueryCodeRequest{CodeId: codeID}) - require.NoError(t, err) - - path := "/cosmwasm.wasm.v1.Query/Code" - resp, err := q.Route(path)(ctx, abci.RequestQuery{Path: path, Data: bz}) - if len(expectedBytes) == 0 { - assert.ErrorIs(t, err, types.ErrNotFound) - return - } - require.NoError(t, err) - require.True(t, resp.IsOK()) - bz = resp.Value - - var rsp types.QueryCodeResponse - require.NoError(t, marshaler.Unmarshal(bz, &rsp)) - assert.Equal(t, expectedBytes, rsp.Data) -} - -func assertContractList(t *testing.T, q *baseapp.GRPCQueryRouter, ctx sdk.Context, codeID uint64, expContractAddrs []string, marshaler codec.Codec) { //nolint:unparam - t.Helper() - bz, err := marshaler.Marshal(&types.QueryContractsByCodeRequest{CodeId: codeID}) - require.NoError(t, err) - - path := "/cosmwasm.wasm.v1.Query/ContractsByCode" - resp, sdkerr := q.Route(path)(ctx, abci.RequestQuery{Path: path, Data: bz}) - if len(expContractAddrs) == 0 { - assert.ErrorIs(t, err, types.ErrNotFound) - return - } - require.NoError(t, sdkerr) - require.True(t, resp.IsOK()) - bz = resp.Value - - var rsp types.QueryContractsByCodeResponse - require.NoError(t, marshaler.Unmarshal(bz, &rsp)) - - hasAddrs := make([]string, len(rsp.Contracts)) - for i, r := range rsp.Contracts { //nolint:gosimple - hasAddrs[i] = r - } - assert.Equal(t, expContractAddrs, hasAddrs) -} - -func assertContractState(t *testing.T, q *baseapp.GRPCQueryRouter, ctx sdk.Context, contractBech32Addr string, expected state, marshaler codec.Codec) { - t.Helper() - bz, err := marshaler.Marshal(&types.QueryRawContractStateRequest{Address: contractBech32Addr, QueryData: []byte("config")}) - require.NoError(t, err) - - path := "/cosmwasm.wasm.v1.Query/RawContractState" - resp, sdkerr := q.Route(path)(ctx, abci.RequestQuery{Path: path, Data: bz}) - require.NoError(t, sdkerr) - require.True(t, resp.IsOK()) - bz = resp.Value - - var rsp types.QueryRawContractStateResponse - require.NoError(t, marshaler.Unmarshal(bz, &rsp)) - expectedBz, err := json.Marshal(expected) - require.NoError(t, err) - assert.Equal(t, expectedBz, rsp.Data) -} - -func assertContractInfo(t *testing.T, q *baseapp.GRPCQueryRouter, ctx sdk.Context, contractBech32Addr string, codeID uint64, creator sdk.AccAddress, marshaler codec.Codec) { //nolint:unparam - t.Helper() - bz, err := marshaler.Marshal(&types.QueryContractInfoRequest{Address: contractBech32Addr}) - require.NoError(t, err) - - path := "/cosmwasm.wasm.v1.Query/ContractInfo" - resp, sdkerr := q.Route(path)(ctx, abci.RequestQuery{Path: path, Data: bz}) - require.NoError(t, sdkerr) - require.True(t, resp.IsOK()) - bz = resp.Value - - var rsp types.QueryContractInfoResponse - require.NoError(t, marshaler.Unmarshal(bz, &rsp)) - - assert.Equal(t, codeID, rsp.CodeID) - assert.Equal(t, creator.String(), rsp.Creator) -} diff --git a/x/wasm/relay_pingpong_test.go b/x/wasm/relay_pingpong_test.go deleted file mode 100644 index 932bebb..0000000 --- a/x/wasm/relay_pingpong_test.go +++ /dev/null @@ -1,381 +0,0 @@ -package wasm_test - -import ( - "encoding/json" - "fmt" - "testing" - - ibctransfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" - ibctesting "github.com/cosmos/ibc-go/v7/testing" - - wasmvm "github.com/CosmWasm/wasmvm" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - sdk "github.com/cosmos/cosmos-sdk/types" - clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - wasmibctesting "github.com/terpnetwork/terp-core/x/wasm/ibctesting" - wasmkeeper "github.com/terpnetwork/terp-core/x/wasm/keeper" - "github.com/terpnetwork/terp-core/x/wasm/keeper/wasmtesting" - wasmtypes "github.com/terpnetwork/terp-core/x/wasm/types" -) - -const ( - ping = "ping" - pong = "pong" -) - -var doNotTimeout = clienttypes.NewHeight(1, 1111111) - -func TestPinPong(t *testing.T) { - // custom IBC protocol example - // scenario: given two chains, - // with a contract on chain A and chain B - // when a ibc packet comes in, the contract responds with a new packet containing - // either ping or pong - - pingContract := &player{t: t, actor: ping} - pongContract := &player{t: t, actor: pong} - - var ( - chainAOpts = []wasmkeeper.Option{ - wasmkeeper.WithWasmEngine( - wasmtesting.NewIBCContractMockWasmer(pingContract)), - } - chainBOpts = []wasmkeeper.Option{wasmkeeper.WithWasmEngine( - wasmtesting.NewIBCContractMockWasmer(pongContract), - )} - coordinator = wasmibctesting.NewCoordinator(t, 2, chainAOpts, chainBOpts) - chainA = coordinator.GetChain(wasmibctesting.GetChainID(1)) - chainB = coordinator.GetChain(wasmibctesting.GetChainID(2)) - ) - _ = chainB.SeedNewContractInstance() // skip 1 instance so that addresses are not the same - var ( - pingContractAddr = chainA.SeedNewContractInstance() - pongContractAddr = chainB.SeedNewContractInstance() - ) - require.NotEqual(t, pingContractAddr, pongContractAddr) - coordinator.CommitBlock(chainA, chainB) - - pingContract.chain = chainA - pingContract.contractAddr = pingContractAddr - - pongContract.chain = chainB - pongContract.contractAddr = pongContractAddr - - var ( - sourcePortID = wasmkeeper.PortIDForContract(pingContractAddr) - counterpartyPortID = wasmkeeper.PortIDForContract(pongContractAddr) - ) - - path := wasmibctesting.NewPath(chainA, chainB) - path.EndpointA.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: sourcePortID, - Version: ibctransfertypes.Version, - Order: channeltypes.ORDERED, - } - path.EndpointB.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: counterpartyPortID, - Version: ibctransfertypes.Version, - Order: channeltypes.ORDERED, - } - coordinator.SetupConnections(path) - coordinator.CreateChannels(path) - - // trigger start game via execute - const startValue uint64 = 100 - const rounds = 3 - s := startGame{ - ChannelID: path.EndpointA.ChannelID, - Value: startValue, - } - startMsg := &wasmtypes.MsgExecuteContract{ - Sender: chainA.SenderAccount.GetAddress().String(), - Contract: pingContractAddr.String(), - Msg: s.GetBytes(), - } - // on chain A - _, err := path.EndpointA.Chain.SendMsgs(startMsg) - require.NoError(t, err) - - // when some rounds are played - for i := 1; i <= rounds; i++ { - t.Logf("++ round: %d\n", i) - - require.Len(t, chainA.PendingSendPackets, 1) - err := coordinator.RelayAndAckPendingPackets(path) - require.NoError(t, err) - } - - // then receive/response state is as expected - assert.Equal(t, startValue+rounds, pingContract.QueryState(lastBallSentKey)) - assert.Equal(t, uint64(rounds), pingContract.QueryState(lastBallReceivedKey)) - assert.Equal(t, uint64(rounds+1), pingContract.QueryState(sentBallsCountKey)) - assert.Equal(t, uint64(rounds), pingContract.QueryState(receivedBallsCountKey)) - assert.Equal(t, uint64(rounds), pingContract.QueryState(confirmedBallsCountKey)) - - assert.Equal(t, uint64(rounds), pongContract.QueryState(lastBallSentKey)) - assert.Equal(t, startValue+rounds-1, pongContract.QueryState(lastBallReceivedKey)) - assert.Equal(t, uint64(rounds), pongContract.QueryState(sentBallsCountKey)) - assert.Equal(t, uint64(rounds), pongContract.QueryState(receivedBallsCountKey)) - assert.Equal(t, uint64(rounds), pongContract.QueryState(confirmedBallsCountKey)) -} - -var _ wasmtesting.IBCContractCallbacks = &player{} - -// player is a (mock) contract that sends and receives ibc packages -type player struct { - t *testing.T - chain *wasmibctesting.TestChain - contractAddr sdk.AccAddress - actor string // either ping or pong - execCalls int // number of calls to Execute method (checkTx + deliverTx) -} - -// Execute starts the ping pong game -// Contracts finds all connected channels and broadcasts a ping message -func (p *player) Execute(_ wasmvm.Checksum, _ wasmvmtypes.Env, _ wasmvmtypes.MessageInfo, executeMsg []byte, store wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - p.execCalls++ - // start game - var start startGame - if err := json.Unmarshal(executeMsg, &start); err != nil { - return nil, 0, err - } - - if start.MaxValue != 0 { - store.Set(maxValueKey, sdk.Uint64ToBigEndian(start.MaxValue)) - } - service := NewHit(p.actor, start.Value) - p.t.Logf("[%s] starting game with: %d: %v\n", p.actor, start.Value, service) - - p.incrementCounter(sentBallsCountKey, store) - store.Set(lastBallSentKey, sdk.Uint64ToBigEndian(start.Value)) - return &wasmvmtypes.Response{ - Messages: []wasmvmtypes.SubMsg{ - { - Msg: wasmvmtypes.CosmosMsg{ - IBC: &wasmvmtypes.IBCMsg{ - SendPacket: &wasmvmtypes.SendPacketMsg{ - ChannelID: start.ChannelID, - Data: service.GetBytes(), - Timeout: wasmvmtypes.IBCTimeout{Block: &wasmvmtypes.IBCTimeoutBlock{ - Revision: doNotTimeout.RevisionNumber, - Height: doNotTimeout.RevisionHeight, - }}, - }, - }, - }, - ReplyOn: wasmvmtypes.ReplyNever, - }, - }, - }, 0, nil -} - -// OnIBCChannelOpen ensures to accept only configured version -func (p player) IBCChannelOpen(_ wasmvm.Checksum, _ wasmvmtypes.Env, msg wasmvmtypes.IBCChannelOpenMsg, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBC3ChannelOpenResponse, uint64, error) { - if msg.GetChannel().Version != p.actor { - return &wasmvmtypes.IBC3ChannelOpenResponse{}, 0, nil - } - return &wasmvmtypes.IBC3ChannelOpenResponse{}, 0, nil -} - -// OnIBCChannelConnect persists connection endpoints -func (p player) IBCChannelConnect(_ wasmvm.Checksum, _ wasmvmtypes.Env, msg wasmvmtypes.IBCChannelConnectMsg, store wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - p.storeEndpoint(store, msg.GetChannel()) - return &wasmvmtypes.IBCBasicResponse{}, 0, nil -} - -// connectedChannelsModel is a simple persistence model to store endpoint addresses within the contract's store -type connectedChannelsModel struct { - Our wasmvmtypes.IBCEndpoint - Their wasmvmtypes.IBCEndpoint -} - -var ( // store keys - ibcEndpointsKey = []byte("ibc-endpoints") - maxValueKey = []byte("max-value") -) - -func (p player) storeEndpoint(store wasmvm.KVStore, channel wasmvmtypes.IBCChannel) { - var counterparties []connectedChannelsModel - if b := store.Get(ibcEndpointsKey); b != nil { - require.NoError(p.t, json.Unmarshal(b, &counterparties)) - } - counterparties = append(counterparties, connectedChannelsModel{Our: channel.Endpoint, Their: channel.CounterpartyEndpoint}) - bz, err := json.Marshal(&counterparties) - require.NoError(p.t, err) - store.Set(ibcEndpointsKey, bz) -} - -func (p player) IBCChannelClose(_ wasmvm.Checksum, _ wasmvmtypes.Env, _ wasmvmtypes.IBCChannelCloseMsg, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - panic("implement me") -} - -var ( // store keys - lastBallSentKey = []byte("lastBallSent") - lastBallReceivedKey = []byte("lastBallReceived") - sentBallsCountKey = []byte("sentBalls") - receivedBallsCountKey = []byte("recvBalls") - confirmedBallsCountKey = []byte("confBalls") -) - -// IBCPacketReceive receives the hit and serves a response hit via `wasmvmtypes.IBCPacket` -func (p player) IBCPacketReceive(_ wasmvm.Checksum, _ wasmvmtypes.Env, msg wasmvmtypes.IBCPacketReceiveMsg, store wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCReceiveResult, uint64, error) { - // parse received data and store - packet := msg.Packet - var receivedBall hit - if err := json.Unmarshal(packet.Data, &receivedBall); err != nil { - return &wasmvmtypes.IBCReceiveResult{ - Ok: &wasmvmtypes.IBCReceiveResponse{ - Acknowledgement: hitAcknowledgement{Error: err.Error()}.GetBytes(), - }, - // no hit msg, we stop the game - }, 0, nil - } - p.incrementCounter(receivedBallsCountKey, store) - - otherCount := receivedBall[counterParty(p.actor)] - store.Set(lastBallReceivedKey, sdk.Uint64ToBigEndian(otherCount)) - - if maxVal := store.Get(maxValueKey); maxVal != nil && otherCount > sdk.BigEndianToUint64(maxVal) { - errMsg := fmt.Sprintf("max value exceeded: %d got %d", sdk.BigEndianToUint64(maxVal), otherCount) - return &wasmvmtypes.IBCReceiveResult{Ok: &wasmvmtypes.IBCReceiveResponse{ - Acknowledgement: receivedBall.BuildError(errMsg).GetBytes(), - }}, 0, nil - } - - nextValue := p.incrementCounter(lastBallSentKey, store) - newHit := NewHit(p.actor, nextValue) - respHit := &wasmvmtypes.IBCMsg{SendPacket: &wasmvmtypes.SendPacketMsg{ - ChannelID: packet.Src.ChannelID, - Data: newHit.GetBytes(), - Timeout: wasmvmtypes.IBCTimeout{Block: &wasmvmtypes.IBCTimeoutBlock{ - Revision: doNotTimeout.RevisionNumber, - Height: doNotTimeout.RevisionHeight, - }}, - }} - p.incrementCounter(sentBallsCountKey, store) - p.t.Logf("[%s] received %d, returning %d: %v\n", p.actor, otherCount, nextValue, newHit) - - return &wasmvmtypes.IBCReceiveResult{ - Ok: &wasmvmtypes.IBCReceiveResponse{ - Acknowledgement: receivedBall.BuildAck().GetBytes(), - Messages: []wasmvmtypes.SubMsg{{Msg: wasmvmtypes.CosmosMsg{IBC: respHit}, ReplyOn: wasmvmtypes.ReplyNever}}, - }, - }, 0, nil -} - -// OnIBCPacketAcknowledgement handles the packet acknowledgment frame. Stops the game on an any error -func (p player) IBCPacketAck(_ wasmvm.Checksum, _ wasmvmtypes.Env, msg wasmvmtypes.IBCPacketAckMsg, store wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - // parse received data and store - var sentBall hit - if err := json.Unmarshal(msg.OriginalPacket.Data, &sentBall); err != nil { - return nil, 0, err - } - - var ack hitAcknowledgement - if err := json.Unmarshal(msg.Acknowledgement.Data, &ack); err != nil { - return nil, 0, err - } - if ack.Success != nil { - confirmedCount := sentBall[p.actor] - p.t.Logf("[%s] acknowledged %d: %v\n", p.actor, confirmedCount, sentBall) - } else { - p.t.Logf("[%s] received app layer error: %s\n", p.actor, ack.Error) - } - - p.incrementCounter(confirmedBallsCountKey, store) - return &wasmvmtypes.IBCBasicResponse{}, 0, nil -} - -func (p player) IBCPacketTimeout(_ wasmvm.Checksum, _ wasmvmtypes.Env, _ wasmvmtypes.IBCPacketTimeoutMsg, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - panic("implement me") -} - -func (p player) incrementCounter(key []byte, store wasmvm.KVStore) uint64 { - var count uint64 - bz := store.Get(key) - if bz != nil { - count = sdk.BigEndianToUint64(bz) - } - count++ - store.Set(key, sdk.Uint64ToBigEndian(count)) - return count -} - -func (p player) QueryState(key []byte) uint64 { - raw := p.chain.App.WasmKeeper.QueryRaw(p.chain.GetContext(), p.contractAddr, key) - return sdk.BigEndianToUint64(raw) -} - -func counterParty(s string) string { - switch s { - case ping: - return pong - case pong: - return ping - default: - panic(fmt.Sprintf("unsupported: %q", s)) - } -} - -// hit is ibc packet payload -type hit map[string]uint64 - -func NewHit(player string, count uint64) hit { - return map[string]uint64{ - player: count, - } -} - -func (h hit) GetBytes() []byte { - b, err := json.Marshal(h) - if err != nil { - panic(err) - } - return b -} - -func (h hit) String() string { - return fmt.Sprintf("Ball %s", string(h.GetBytes())) -} - -func (h hit) BuildAck() hitAcknowledgement { - return hitAcknowledgement{Success: &h} -} - -func (h hit) BuildError(errMsg string) hitAcknowledgement { - return hitAcknowledgement{Error: errMsg} -} - -// hitAcknowledgement is ibc acknowledgment payload -type hitAcknowledgement struct { - Error string `json:"error,omitempty"` - Success *hit `json:"success,omitempty"` -} - -func (a hitAcknowledgement) GetBytes() []byte { - b, err := json.Marshal(a) - if err != nil { - panic(err) - } - return b -} - -// startGame is an execute message payload -type startGame struct { - ChannelID string - Value uint64 - // limit above the game is aborted - MaxValue uint64 `json:"max_value,omitempty"` -} - -func (g startGame) GetBytes() wasmtypes.RawContractMessage { - b, err := json.Marshal(g) - if err != nil { - panic(err) - } - return b -} diff --git a/x/wasm/relay_test.go b/x/wasm/relay_test.go deleted file mode 100644 index 583f506..0000000 --- a/x/wasm/relay_test.go +++ /dev/null @@ -1,824 +0,0 @@ -package wasm_test - -import ( - "encoding/json" - "errors" - "testing" - "time" - - errorsmod "cosmossdk.io/errors" - "cosmossdk.io/math" - wasmvm "github.com/CosmWasm/wasmvm" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - sdk "github.com/cosmos/cosmos-sdk/types" - ibctransfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" - clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - ibctesting "github.com/cosmos/ibc-go/v7/testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - wasmibctesting "github.com/terpnetwork/terp-core/x/wasm/ibctesting" - wasmkeeper "github.com/terpnetwork/terp-core/x/wasm/keeper" - wasmtesting "github.com/terpnetwork/terp-core/x/wasm/keeper/wasmtesting" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestFromIBCTransferToContract(t *testing.T) { - // scenario: given two chains, - // with a contract on chain B - // then the contract can handle the receiving side of an ics20 transfer - // that was started on chain A via ibc transfer module - - transferAmount := sdk.NewInt(1) - specs := map[string]struct { - contract wasmtesting.IBCContractCallbacks - setupContract func(t *testing.T, contract wasmtesting.IBCContractCallbacks, chain *wasmibctesting.TestChain) - expChainAPendingSendPackets int - expChainBPendingSendPackets int - expChainABalanceDiff math.Int - expChainBBalanceDiff math.Int - expErr bool - }{ - "ack": { - contract: &ackReceiverContract{}, - setupContract: func(t *testing.T, contract wasmtesting.IBCContractCallbacks, chain *wasmibctesting.TestChain) { - c := contract.(*ackReceiverContract) - c.t = t - c.chain = chain - }, - expChainAPendingSendPackets: 0, - expChainBPendingSendPackets: 0, - expChainABalanceDiff: transferAmount.Neg(), - expChainBBalanceDiff: transferAmount, - }, - "nack": { - contract: &nackReceiverContract{}, - setupContract: func(t *testing.T, contract wasmtesting.IBCContractCallbacks, chain *wasmibctesting.TestChain) { - c := contract.(*nackReceiverContract) - c.t = t - }, - expChainAPendingSendPackets: 0, - expChainBPendingSendPackets: 0, - expChainABalanceDiff: sdk.ZeroInt(), - expChainBBalanceDiff: sdk.ZeroInt(), - }, - "error": { - contract: &errorReceiverContract{}, - setupContract: func(t *testing.T, contract wasmtesting.IBCContractCallbacks, chain *wasmibctesting.TestChain) { - c := contract.(*errorReceiverContract) - c.t = t - }, - expChainAPendingSendPackets: 1, - expChainBPendingSendPackets: 0, - expChainABalanceDiff: transferAmount.Neg(), - expChainBBalanceDiff: sdk.ZeroInt(), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - var ( - chainAOpts = []wasmkeeper.Option{wasmkeeper.WithWasmEngine( - wasmtesting.NewIBCContractMockWasmer(spec.contract), - )} - coordinator = wasmibctesting.NewCoordinator(t, 2, []wasmkeeper.Option{}, chainAOpts) - chainA = coordinator.GetChain(wasmibctesting.GetChainID(1)) - chainB = coordinator.GetChain(wasmibctesting.GetChainID(2)) - ) - coordinator.CommitBlock(chainA, chainB) - myContractAddr := chainB.SeedNewContractInstance() - contractBPortID := chainB.ContractInfo(myContractAddr).IBCPortID - - spec.setupContract(t, spec.contract, chainB) - - path := wasmibctesting.NewPath(chainA, chainB) - path.EndpointA.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: "transfer", - Version: ibctransfertypes.Version, - Order: channeltypes.UNORDERED, - } - path.EndpointB.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: contractBPortID, - Version: ibctransfertypes.Version, - Order: channeltypes.UNORDERED, - } - - coordinator.SetupConnections(path) - coordinator.CreateChannels(path) - - originalChainABalance := chainA.Balance(chainA.SenderAccount.GetAddress(), sdk.DefaultBondDenom) - // when transfer via sdk transfer from A (module) -> B (contract) - coinToSendToB := sdk.NewCoin(sdk.DefaultBondDenom, transferAmount) - timeoutHeight := clienttypes.NewHeight(1, 110) - - msg := ibctransfertypes.NewMsgTransfer(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID, coinToSendToB, chainA.SenderAccount.GetAddress().String(), chainB.SenderAccount.GetAddress().String(), timeoutHeight, 0, "") - _, err := chainA.SendMsgs(msg) - require.NoError(t, err) - require.NoError(t, path.EndpointB.UpdateClient()) - - // then - require.Equal(t, 1, len(chainA.PendingSendPackets)) - require.Equal(t, 0, len(chainB.PendingSendPackets)) - - // and when relay to chain B and handle Ack on chain A - err = coordinator.RelayAndAckPendingPackets(path) - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - - // then - require.Equal(t, spec.expChainAPendingSendPackets, len(chainA.PendingSendPackets)) - require.Equal(t, spec.expChainBPendingSendPackets, len(chainB.PendingSendPackets)) - - // and source chain balance was decreased - newChainABalance := chainA.Balance(chainA.SenderAccount.GetAddress(), sdk.DefaultBondDenom) - assert.Equal(t, originalChainABalance.Amount.Add(spec.expChainABalanceDiff), newChainABalance.Amount) - - // and dest chain balance contains voucher - expBalance := ibctransfertypes.GetTransferCoin(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID, coinToSendToB.Denom, spec.expChainBBalanceDiff) - gotBalance := chainB.Balance(chainB.SenderAccount.GetAddress(), expBalance.Denom) - assert.Equal(t, expBalance, gotBalance, "got total balance: %s", chainB.AllBalances(chainB.SenderAccount.GetAddress())) - }) - } -} - -func TestContractCanInitiateIBCTransferMsg(t *testing.T) { - // scenario: given two chains, - // with a contract on chain A - // then the contract can start an ibc transfer via ibctransfertypes.NewMsgTransfer - // that is handled on chain A by the ibc transfer module and - // received on chain B via ibc transfer module as well - - myContract := &sendViaIBCTransferContract{t: t} - var ( - chainAOpts = []wasmkeeper.Option{ - wasmkeeper.WithWasmEngine( - wasmtesting.NewIBCContractMockWasmer(myContract)), - } - coordinator = wasmibctesting.NewCoordinator(t, 2, chainAOpts) - chainA = coordinator.GetChain(wasmibctesting.GetChainID(1)) - chainB = coordinator.GetChain(wasmibctesting.GetChainID(2)) - ) - myContractAddr := chainA.SeedNewContractInstance() - coordinator.CommitBlock(chainA, chainB) - - path := wasmibctesting.NewPath(chainA, chainB) - path.EndpointA.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: ibctransfertypes.PortID, - Version: ibctransfertypes.Version, - Order: channeltypes.UNORDERED, - } - path.EndpointB.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: ibctransfertypes.PortID, - Version: ibctransfertypes.Version, - Order: channeltypes.UNORDERED, - } - coordinator.SetupConnections(path) - coordinator.CreateChannels(path) - - // when contract is triggered to send IBCTransferMsg - receiverAddress := chainB.SenderAccount.GetAddress() - coinToSendToB := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)) - - // start transfer from chainA to chainB - startMsg := &types.MsgExecuteContract{ - Sender: chainA.SenderAccount.GetAddress().String(), - Contract: myContractAddr.String(), - Msg: startTransfer{ - ChannelID: path.EndpointA.ChannelID, - CoinsToSend: coinToSendToB, - ReceiverAddr: receiverAddress.String(), - }.GetBytes(), - } - // trigger contract to start the transfer - _, err := chainA.SendMsgs(startMsg) - require.NoError(t, err) - - // then - require.Equal(t, 1, len(chainA.PendingSendPackets)) - require.Equal(t, 0, len(chainB.PendingSendPackets)) - - // and when relay to chain B and handle Ack on chain A - err = coordinator.RelayAndAckPendingPackets(path) - require.NoError(t, err) - - // then - require.Equal(t, 0, len(chainA.PendingSendPackets)) - require.Equal(t, 0, len(chainB.PendingSendPackets)) - - // and dest chain balance contains voucher - bankKeeperB := chainB.App.BankKeeper - expBalance := ibctransfertypes.GetTransferCoin(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID, coinToSendToB.Denom, coinToSendToB.Amount) - gotBalance := chainB.Balance(chainB.SenderAccount.GetAddress(), expBalance.Denom) - assert.Equal(t, expBalance, gotBalance, "got total balance: %s", bankKeeperB.GetAllBalances(chainB.GetContext(), chainB.SenderAccount.GetAddress())) -} - -func TestContractCanEmulateIBCTransferMessage(t *testing.T) { - // scenario: given two chains, - // with a contract on chain A - // then the contract can emulate the ibc transfer module in the contract to send an ibc packet - // which is received on chain B via ibc transfer module - - myContract := &sendEmulatedIBCTransferContract{t: t} - - var ( - chainAOpts = []wasmkeeper.Option{ - wasmkeeper.WithWasmEngine( - wasmtesting.NewIBCContractMockWasmer(myContract)), - } - coordinator = wasmibctesting.NewCoordinator(t, 2, chainAOpts) - - chainA = coordinator.GetChain(wasmibctesting.GetChainID(1)) - chainB = coordinator.GetChain(wasmibctesting.GetChainID(2)) - ) - myContractAddr := chainA.SeedNewContractInstance() - myContract.contractAddr = myContractAddr.String() - - path := wasmibctesting.NewPath(chainA, chainB) - path.EndpointA.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: chainA.ContractInfo(myContractAddr).IBCPortID, - Version: ibctransfertypes.Version, - Order: channeltypes.UNORDERED, - } - path.EndpointB.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: ibctransfertypes.PortID, - Version: ibctransfertypes.Version, - Order: channeltypes.UNORDERED, - } - coordinator.SetupConnections(path) - coordinator.CreateChannels(path) - - // when contract is triggered to send the ibc package to chain B - timeout := uint64(chainB.LastHeader.Header.Time.Add(time.Hour).UnixNano()) // enough time to not timeout - receiverAddress := chainB.SenderAccount.GetAddress() - coinToSendToB := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)) - - // start transfer from chainA to chainB - startMsg := &types.MsgExecuteContract{ - Sender: chainA.SenderAccount.GetAddress().String(), - Contract: myContractAddr.String(), - Msg: startTransfer{ - ChannelID: path.EndpointA.ChannelID, - CoinsToSend: coinToSendToB, - ReceiverAddr: receiverAddress.String(), - ContractIBCPort: chainA.ContractInfo(myContractAddr).IBCPortID, - Timeout: timeout, - }.GetBytes(), - Funds: sdk.NewCoins(coinToSendToB), - } - _, err := chainA.SendMsgs(startMsg) - require.NoError(t, err) - - // then - require.Equal(t, 1, len(chainA.PendingSendPackets)) - require.Equal(t, 0, len(chainB.PendingSendPackets)) - - // and when relay to chain B and handle Ack on chain A - err = coordinator.RelayAndAckPendingPackets(path) - require.NoError(t, err) - - // then - require.Equal(t, 0, len(chainA.PendingSendPackets)) - require.Equal(t, 0, len(chainB.PendingSendPackets)) - - // and dest chain balance contains voucher - bankKeeperB := chainB.App.BankKeeper - expBalance := ibctransfertypes.GetTransferCoin(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID, coinToSendToB.Denom, coinToSendToB.Amount) - gotBalance := chainB.Balance(chainB.SenderAccount.GetAddress(), expBalance.Denom) - assert.Equal(t, expBalance, gotBalance, "got total balance: %s", bankKeeperB.GetAllBalances(chainB.GetContext(), chainB.SenderAccount.GetAddress())) -} - -func TestContractCanEmulateIBCTransferMessageWithTimeout(t *testing.T) { - // scenario: given two chains, - // with a contract on chain A - // then the contract can emulate the ibc transfer module in the contract to send an ibc packet - // which is not received on chain B and times out - - myContract := &sendEmulatedIBCTransferContract{t: t} - - var ( - chainAOpts = []wasmkeeper.Option{ - wasmkeeper.WithWasmEngine( - wasmtesting.NewIBCContractMockWasmer(myContract)), - } - coordinator = wasmibctesting.NewCoordinator(t, 2, chainAOpts) - - chainA = coordinator.GetChain(wasmibctesting.GetChainID(1)) - chainB = coordinator.GetChain(wasmibctesting.GetChainID(2)) - ) - coordinator.CommitBlock(chainA, chainB) - myContractAddr := chainA.SeedNewContractInstance() - myContract.contractAddr = myContractAddr.String() - - path := wasmibctesting.NewPath(chainA, chainB) - path.EndpointA.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: chainA.ContractInfo(myContractAddr).IBCPortID, - Version: ibctransfertypes.Version, - Order: channeltypes.UNORDERED, - } - path.EndpointB.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: ibctransfertypes.PortID, - Version: ibctransfertypes.Version, - Order: channeltypes.UNORDERED, - } - coordinator.SetupConnections(path) - coordinator.CreateChannels(path) - coordinator.UpdateTime() - - // when contract is triggered to send the ibc package to chain B - timeout := uint64(chainB.LastHeader.Header.Time.Add(time.Nanosecond).UnixNano()) // will timeout - receiverAddress := chainB.SenderAccount.GetAddress() - coinToSendToB := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)) - initialContractBalance := chainA.Balance(myContractAddr, sdk.DefaultBondDenom) - initialSenderBalance := chainA.Balance(chainA.SenderAccount.GetAddress(), sdk.DefaultBondDenom) - - // custom payload data to be transferred into a proper ICS20 ibc packet - startMsg := &types.MsgExecuteContract{ - Sender: chainA.SenderAccount.GetAddress().String(), - Contract: myContractAddr.String(), - Msg: startTransfer{ - ChannelID: path.EndpointA.ChannelID, - CoinsToSend: coinToSendToB, - ReceiverAddr: receiverAddress.String(), - ContractIBCPort: chainA.ContractInfo(myContractAddr).IBCPortID, - Timeout: timeout, - }.GetBytes(), - Funds: sdk.NewCoins(coinToSendToB), - } - _, err := chainA.SendMsgs(startMsg) - require.NoError(t, err) - coordinator.CommitBlock(chainA, chainB) - // then - require.Equal(t, 1, len(chainA.PendingSendPackets)) - require.Equal(t, 0, len(chainB.PendingSendPackets)) - newContractBalance := chainA.Balance(myContractAddr, sdk.DefaultBondDenom) - assert.Equal(t, initialContractBalance.Add(coinToSendToB), newContractBalance) // hold in escrow - - // when timeout packet send (by the relayer) - err = coordinator.TimeoutPendingPackets(path) - require.NoError(t, err) - coordinator.CommitBlock(chainA) - - // then - require.Equal(t, 0, len(chainA.PendingSendPackets)) - require.Equal(t, 0, len(chainB.PendingSendPackets)) - - // and then verify account balances restored - newContractBalance = chainA.Balance(myContractAddr, sdk.DefaultBondDenom) - assert.Equal(t, initialContractBalance.String(), newContractBalance.String()) - newSenderBalance := chainA.Balance(chainA.SenderAccount.GetAddress(), sdk.DefaultBondDenom) - assert.Equal(t, initialSenderBalance.String(), newSenderBalance.String()) -} - -func TestContractEmulateIBCTransferMessageOnDiffContractIBCChannel(t *testing.T) { - // scenario: given two chains, A and B - // with 2 contract A1 and A2 on chain A - // then the contract A2 try to send an ibc packet via IBC Channel that create by A1 and B - myContractA1 := &sendEmulatedIBCTransferContract{} - myContractA2 := &sendEmulatedIBCTransferContract{} - - var ( - chainAOpts = []wasmkeeper.Option{ - wasmkeeper.WithWasmEngine( - wasmtesting.NewIBCContractMockWasmer(myContractA1), - ), - wasmkeeper.WithWasmEngine( - wasmtesting.NewIBCContractMockWasmer(myContractA2), - ), - } - - coordinator = wasmibctesting.NewCoordinator(t, 2, chainAOpts) - - chainA = coordinator.GetChain(wasmibctesting.GetChainID(1)) - chainB = coordinator.GetChain(wasmibctesting.GetChainID(2)) - ) - - coordinator.CommitBlock(chainA, chainB) - myContractAddr1 := chainA.SeedNewContractInstance() - myContractA1.contractAddr = myContractAddr1.String() - myContractAddr2 := chainA.SeedNewContractInstance() - myContractA2.contractAddr = myContractAddr2.String() - - path := wasmibctesting.NewPath(chainA, chainB) - path.EndpointA.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: chainA.ContractInfo(myContractAddr1).IBCPortID, - Version: ibctransfertypes.Version, - Order: channeltypes.UNORDERED, - } - path.EndpointB.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: ibctransfertypes.PortID, - Version: ibctransfertypes.Version, - Order: channeltypes.UNORDERED, - } - coordinator.SetupConnections(path) - coordinator.CreateChannels(path) - - // when contract is triggered to send the ibc package to chain B - timeout := uint64(chainB.LastHeader.Header.Time.Add(time.Hour).UnixNano()) // enough time to not timeout - receiverAddress := chainB.SenderAccount.GetAddress() - coinToSendToB := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)) - - // start transfer from chainA - A2 to chainB via IBC channel - startMsg := &types.MsgExecuteContract{ - Sender: chainA.SenderAccount.GetAddress().String(), - Contract: myContractAddr2.String(), - Msg: startTransfer{ - ChannelID: path.EndpointA.ChannelID, - CoinsToSend: coinToSendToB, - ReceiverAddr: receiverAddress.String(), - Timeout: timeout, - }.GetBytes(), - Funds: sdk.NewCoins(coinToSendToB), - } - _, err := chainA.SendMsgs(startMsg) - require.Error(t, err) -} - -func TestContractHandlesChannelClose(t *testing.T) { - // scenario: a contract is the sending side of an ics20 transfer but the packet was not received - // on the destination chain within the timeout boundaries - myContractA := &captureCloseContract{} - myContractB := &captureCloseContract{} - - var ( - chainAOpts = []wasmkeeper.Option{ - wasmkeeper.WithWasmEngine( - wasmtesting.NewIBCContractMockWasmer(myContractA)), - } - chainBOpts = []wasmkeeper.Option{ - wasmkeeper.WithWasmEngine( - wasmtesting.NewIBCContractMockWasmer(myContractB)), - } - coordinator = wasmibctesting.NewCoordinator(t, 2, chainAOpts, chainBOpts) - - chainA = coordinator.GetChain(wasmibctesting.GetChainID(1)) - chainB = coordinator.GetChain(wasmibctesting.GetChainID(2)) - ) - - coordinator.CommitBlock(chainA, chainB) - myContractAddrA := chainA.SeedNewContractInstance() - _ = chainB.SeedNewContractInstance() // skip one instance - myContractAddrB := chainB.SeedNewContractInstance() - - path := wasmibctesting.NewPath(chainA, chainB) - path.EndpointA.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: chainA.ContractInfo(myContractAddrA).IBCPortID, - Version: ibctransfertypes.Version, - Order: channeltypes.UNORDERED, - } - path.EndpointB.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: chainB.ContractInfo(myContractAddrB).IBCPortID, - Version: ibctransfertypes.Version, - Order: channeltypes.UNORDERED, - } - coordinator.SetupConnections(path) - coordinator.CreateChannels(path) - coordinator.CloseChannel(path) - assert.True(t, myContractB.closeCalled) -} - -func TestContractHandlesChannelCloseNotOwned(t *testing.T) { - // scenario: given two chains, - // with a contract A1, A2 on chain A, contract B on chain B - // contract A2 try to close ibc channel that create between A1 and B - - myContractA1 := &closeChannelContract{} - myContractA2 := &closeChannelContract{} - myContractB := &closeChannelContract{} - - var ( - chainAOpts = []wasmkeeper.Option{ - wasmkeeper.WithWasmEngine( - wasmtesting.NewIBCContractMockWasmer(myContractA1)), - wasmkeeper.WithWasmEngine( - wasmtesting.NewIBCContractMockWasmer(myContractA2)), - } - chainBOpts = []wasmkeeper.Option{ - wasmkeeper.WithWasmEngine( - wasmtesting.NewIBCContractMockWasmer(myContractB)), - } - coordinator = wasmibctesting.NewCoordinator(t, 2, chainAOpts, chainBOpts) - - chainA = coordinator.GetChain(wasmibctesting.GetChainID(1)) - chainB = coordinator.GetChain(wasmibctesting.GetChainID(2)) - ) - - coordinator.CommitBlock(chainA, chainB) - myContractAddrA1 := chainA.SeedNewContractInstance() - myContractAddrA2 := chainA.SeedNewContractInstance() - _ = chainB.SeedNewContractInstance() // skip one instance - _ = chainB.SeedNewContractInstance() // skip one instance - myContractAddrB := chainB.SeedNewContractInstance() - - path := wasmibctesting.NewPath(chainA, chainB) - path.EndpointA.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: chainA.ContractInfo(myContractAddrA1).IBCPortID, - Version: ibctransfertypes.Version, - Order: channeltypes.UNORDERED, - } - path.EndpointB.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: chainB.ContractInfo(myContractAddrB).IBCPortID, - Version: ibctransfertypes.Version, - Order: channeltypes.UNORDERED, - } - coordinator.SetupConnections(path) - coordinator.CreateChannels(path) - - closeIBCChannelMsg := &types.MsgExecuteContract{ - Sender: chainA.SenderAccount.GetAddress().String(), - Contract: myContractAddrA2.String(), - Msg: closeIBCChannel{ - ChannelID: path.EndpointA.ChannelID, - }.GetBytes(), - Funds: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))), - } - - _, err := chainA.SendMsgs(closeIBCChannelMsg) - require.Error(t, err) -} - -var _ wasmtesting.IBCContractCallbacks = &captureCloseContract{} - -// contract that sets a flag on IBC channel close only. -type captureCloseContract struct { - contractStub - closeCalled bool -} - -func (c *captureCloseContract) IBCChannelClose(_ wasmvm.Checksum, _ wasmvmtypes.Env, _ wasmvmtypes.IBCChannelCloseMsg, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - c.closeCalled = true - return &wasmvmtypes.IBCBasicResponse{}, 1, nil -} - -var _ wasmtesting.IBCContractCallbacks = &sendViaIBCTransferContract{} - -// contract that initiates an ics-20 transfer on execute via sdk message -type sendViaIBCTransferContract struct { - contractStub - t *testing.T -} - -func (s *sendViaIBCTransferContract) Execute(_ wasmvm.Checksum, _ wasmvmtypes.Env, _ wasmvmtypes.MessageInfo, executeMsg []byte, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - var in startTransfer - if err := json.Unmarshal(executeMsg, &in); err != nil { - return nil, 0, err - } - ibcMsg := &wasmvmtypes.IBCMsg{ - Transfer: &wasmvmtypes.TransferMsg{ - ToAddress: in.ReceiverAddr, - Amount: wasmvmtypes.NewCoin(in.CoinsToSend.Amount.Uint64(), in.CoinsToSend.Denom), - ChannelID: in.ChannelID, - Timeout: wasmvmtypes.IBCTimeout{Block: &wasmvmtypes.IBCTimeoutBlock{ - Revision: 1, - Height: 110, - }}, - }, - } - - return &wasmvmtypes.Response{Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{IBC: ibcMsg}}}}, 0, nil -} - -var _ wasmtesting.IBCContractCallbacks = &sendEmulatedIBCTransferContract{} - -// contract that interacts as an ics20 sending side via IBC packets -// It can also handle the timeout. -type sendEmulatedIBCTransferContract struct { - contractStub - t *testing.T - contractAddr string -} - -func (s *sendEmulatedIBCTransferContract) Execute(_ wasmvm.Checksum, _ wasmvmtypes.Env, info wasmvmtypes.MessageInfo, executeMsg []byte, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - var in startTransfer - if err := json.Unmarshal(executeMsg, &in); err != nil { - return nil, 0, err - } - require.Len(s.t, info.Funds, 1) - require.Equal(s.t, in.CoinsToSend.Amount.String(), info.Funds[0].Amount) - require.Equal(s.t, in.CoinsToSend.Denom, info.Funds[0].Denom) - dataPacket := ibctransfertypes.NewFungibleTokenPacketData( - in.CoinsToSend.Denom, in.CoinsToSend.Amount.String(), info.Sender, in.ReceiverAddr, "memo", - ) - if err := dataPacket.ValidateBasic(); err != nil { - return nil, 0, err - } - - ibcMsg := &wasmvmtypes.IBCMsg{ - SendPacket: &wasmvmtypes.SendPacketMsg{ - ChannelID: in.ChannelID, - Data: dataPacket.GetBytes(), - Timeout: wasmvmtypes.IBCTimeout{Timestamp: in.Timeout}, - }, - } - return &wasmvmtypes.Response{Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{IBC: ibcMsg}}}}, 0, nil -} - -func (s *sendEmulatedIBCTransferContract) IBCPacketTimeout(_ wasmvm.Checksum, _ wasmvmtypes.Env, msg wasmvmtypes.IBCPacketTimeoutMsg, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - packet := msg.Packet - - var data ibctransfertypes.FungibleTokenPacketData - if err := ibctransfertypes.ModuleCdc.UnmarshalJSON(packet.Data, &data); err != nil { - return nil, 0, err - } - if err := data.ValidateBasic(); err != nil { - return nil, 0, err - } - amount, _ := sdk.NewIntFromString(data.Amount) - - returnTokens := &wasmvmtypes.BankMsg{ - Send: &wasmvmtypes.SendMsg{ - ToAddress: data.Sender, - Amount: wasmvmtypes.Coins{wasmvmtypes.NewCoin(amount.Uint64(), data.Denom)}, - }, - } - - return &wasmvmtypes.IBCBasicResponse{Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: returnTokens}}}}, 0, nil -} - -var _ wasmtesting.IBCContractCallbacks = &closeChannelContract{} - -type closeChannelContract struct { - contractStub -} - -func (c *closeChannelContract) IBCChannelClose(_ wasmvm.Checksum, _ wasmvmtypes.Env, _ wasmvmtypes.IBCChannelCloseMsg, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - return &wasmvmtypes.IBCBasicResponse{}, 1, nil -} - -func (c *closeChannelContract) Execute(_ wasmvm.Checksum, _ wasmvmtypes.Env, _ wasmvmtypes.MessageInfo, executeMsg []byte, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - var in closeIBCChannel - if err := json.Unmarshal(executeMsg, &in); err != nil { - return nil, 0, err - } - ibcMsg := &wasmvmtypes.IBCMsg{ - CloseChannel: &wasmvmtypes.CloseChannelMsg{ - ChannelID: in.ChannelID, - }, - } - - return &wasmvmtypes.Response{Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{IBC: ibcMsg}}}}, 0, nil -} - -type closeIBCChannel struct { - ChannelID string -} - -func (g closeIBCChannel) GetBytes() types.RawContractMessage { - b, err := json.Marshal(g) - if err != nil { - panic(err) - } - return b -} - -// custom contract execute payload -type startTransfer struct { - ChannelID string - CoinsToSend sdk.Coin - ReceiverAddr string - ContractIBCPort string - Timeout uint64 -} - -func (g startTransfer) GetBytes() types.RawContractMessage { - b, err := json.Marshal(g) - if err != nil { - panic(err) - } - return b -} - -var _ wasmtesting.IBCContractCallbacks = &ackReceiverContract{} - -// contract that acts as the receiving side for an ics-20 transfer. -type ackReceiverContract struct { - contractStub - t *testing.T - chain *wasmibctesting.TestChain -} - -func (c *ackReceiverContract) IBCPacketReceive(_ wasmvm.Checksum, _ wasmvmtypes.Env, msg wasmvmtypes.IBCPacketReceiveMsg, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCReceiveResult, uint64, error) { - packet := msg.Packet - - var src ibctransfertypes.FungibleTokenPacketData - if err := ibctransfertypes.ModuleCdc.UnmarshalJSON(packet.Data, &src); err != nil { - return nil, 0, err - } - require.NoError(c.t, src.ValidateBasic()) - - // call original ibctransfer keeper to not copy all code into this - ibcPacket := toIBCPacket(packet) - ctx := c.chain.GetContext() // HACK: please note that this is not reverted after checkTX - err := c.chain.App.TransferKeeper.OnRecvPacket(ctx, ibcPacket, src) - if err != nil { - return nil, 0, errorsmod.Wrap(err, "within our smart contract") - } - - var log []wasmvmtypes.EventAttribute // note: all events are under `wasm` event type - ack := channeltypes.NewResultAcknowledgement([]byte{byte(1)}).Acknowledgement() - return &wasmvmtypes.IBCReceiveResult{Ok: &wasmvmtypes.IBCReceiveResponse{Acknowledgement: ack, Attributes: log}}, 0, nil -} - -func (c *ackReceiverContract) IBCPacketAck(_ wasmvm.Checksum, _ wasmvmtypes.Env, msg wasmvmtypes.IBCPacketAckMsg, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - var data ibctransfertypes.FungibleTokenPacketData - if err := ibctransfertypes.ModuleCdc.UnmarshalJSON(msg.OriginalPacket.Data, &data); err != nil { - return nil, 0, err - } - // call original ibctransfer keeper to not copy all code into this - - var ack channeltypes.Acknowledgement - if err := ibctransfertypes.ModuleCdc.UnmarshalJSON(msg.Acknowledgement.Data, &ack); err != nil { - return nil, 0, err - } - - // call original ibctransfer keeper to not copy all code into this - ctx := c.chain.GetContext() // HACK: please note that this is not reverted after checkTX - ibcPacket := toIBCPacket(msg.OriginalPacket) - err := c.chain.App.TransferKeeper.OnAcknowledgementPacket(ctx, ibcPacket, data, ack) - if err != nil { - return nil, 0, errorsmod.Wrap(err, "within our smart contract") - } - - return &wasmvmtypes.IBCBasicResponse{}, 0, nil -} - -// contract that acts as the receiving side for an ics-20 transfer and always returns a nack. -type nackReceiverContract struct { - contractStub - t *testing.T -} - -func (c *nackReceiverContract) IBCPacketReceive(_ wasmvm.Checksum, _ wasmvmtypes.Env, msg wasmvmtypes.IBCPacketReceiveMsg, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCReceiveResult, uint64, error) { - packet := msg.Packet - - var src ibctransfertypes.FungibleTokenPacketData - if err := ibctransfertypes.ModuleCdc.UnmarshalJSON(packet.Data, &src); err != nil { - return nil, 0, err - } - require.NoError(c.t, src.ValidateBasic()) - return &wasmvmtypes.IBCReceiveResult{Err: "nack-testing"}, 0, nil -} - -// contract that acts as the receiving side for an ics-20 transfer and always returns an error. -type errorReceiverContract struct { - contractStub - t *testing.T -} - -func (c *errorReceiverContract) IBCPacketReceive(_ wasmvm.Checksum, _ wasmvmtypes.Env, msg wasmvmtypes.IBCPacketReceiveMsg, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCReceiveResult, uint64, error) { - packet := msg.Packet - - var src ibctransfertypes.FungibleTokenPacketData - if err := ibctransfertypes.ModuleCdc.UnmarshalJSON(packet.Data, &src); err != nil { - return nil, 0, err - } - require.NoError(c.t, src.ValidateBasic()) - return nil, 0, errors.New("error-testing") -} - -// simple helper struct that implements connection setup methods. -type contractStub struct{} - -func (s *contractStub) IBCChannelOpen(_ wasmvm.Checksum, _ wasmvmtypes.Env, _ wasmvmtypes.IBCChannelOpenMsg, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBC3ChannelOpenResponse, uint64, error) { - return &wasmvmtypes.IBC3ChannelOpenResponse{}, 0, nil -} - -func (s *contractStub) IBCChannelConnect(_ wasmvm.Checksum, _ wasmvmtypes.Env, _ wasmvmtypes.IBCChannelConnectMsg, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - return &wasmvmtypes.IBCBasicResponse{}, 0, nil -} - -func (s *contractStub) IBCChannelClose(_ wasmvm.Checksum, _ wasmvmtypes.Env, _ wasmvmtypes.IBCChannelCloseMsg, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - panic("implement me") -} - -func (s *contractStub) IBCPacketReceive(_ wasmvm.Checksum, _ wasmvmtypes.Env, _ wasmvmtypes.IBCPacketReceiveMsg, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCReceiveResult, uint64, error) { - panic("implement me") -} - -func (s *contractStub) IBCPacketAck(_ wasmvm.Checksum, _ wasmvmtypes.Env, _ wasmvmtypes.IBCPacketAckMsg, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - return &wasmvmtypes.IBCBasicResponse{}, 0, nil -} - -func (s *contractStub) IBCPacketTimeout(_ wasmvm.Checksum, _ wasmvmtypes.Env, _ wasmvmtypes.IBCPacketTimeoutMsg, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - panic("implement me") -} - -func toIBCPacket(p wasmvmtypes.IBCPacket) channeltypes.Packet { - var height clienttypes.Height - if p.Timeout.Block != nil { - height = clienttypes.NewHeight(p.Timeout.Block.Revision, p.Timeout.Block.Height) - } - return channeltypes.Packet{ - Sequence: p.Sequence, - SourcePort: p.Src.PortID, - SourceChannel: p.Src.ChannelID, - DestinationPort: p.Dest.PortID, - DestinationChannel: p.Dest.ChannelID, - Data: p.Data, - TimeoutHeight: height, - TimeoutTimestamp: p.Timeout.Timestamp, - } -} diff --git a/x/wasm/simulation/genesis.go b/x/wasm/simulation/genesis.go deleted file mode 100644 index 47a18ca..0000000 --- a/x/wasm/simulation/genesis.go +++ /dev/null @@ -1,27 +0,0 @@ -package simulation - -import ( - "github.com/cosmos/cosmos-sdk/types/module" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// RandomizeGenState generates a random GenesisState for wasm -func RandomizedGenState(simstate *module.SimulationState) { - params := types.DefaultParams() - wasmGenesis := types.GenesisState{ - Params: params, - Codes: nil, - Contracts: nil, - Sequences: []types.Sequence{ - {IDKey: types.KeyLastCodeID, Value: simstate.Rand.Uint64()}, - }, - } - - _, err := simstate.Cdc.MarshalJSON(&wasmGenesis) - if err != nil { - panic(err) - } - - simstate.GenState[types.ModuleName] = simstate.Cdc.MustMarshalJSON(&wasmGenesis) -} diff --git a/x/wasm/simulation/operations.go b/x/wasm/simulation/operations.go deleted file mode 100644 index 5ff14e4..0000000 --- a/x/wasm/simulation/operations.go +++ /dev/null @@ -1,566 +0,0 @@ -package simulation - -import ( - "encoding/json" - "math/rand" - "os" - - errorsmod "cosmossdk.io/errors" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/auth/tx" - "github.com/cosmos/cosmos-sdk/x/simulation" - - "github.com/terpnetwork/terp-core/app/params" - wasmkeeper "github.com/terpnetwork/terp-core/x/wasm/keeper" - "github.com/terpnetwork/terp-core/x/wasm/keeper/testdata" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// Simulation operation weights constants -// -//nolint:gosec -const ( - OpWeightMsgStoreCode = "op_weight_msg_store_code" - OpWeightMsgInstantiateContract = "op_weight_msg_instantiate_contract" - OpWeightMsgExecuteContract = "op_weight_msg_execute_contract" - OpWeightMsgUpdateAdmin = "op_weight_msg_update_admin" - OpWeightMsgClearAdmin = "op_weight_msg_clear_admin" - OpWeightMsgMigrateContract = "op_weight_msg_migrate_contract" - OpReflectContractPath = "op_reflect_contract_path" -) - -// WasmKeeper is a subset of the wasm keeper used by simulations -type WasmKeeper interface { - GetAuthority() string - GetParams(ctx sdk.Context) types.Params - IterateCodeInfos(ctx sdk.Context, cb func(uint64, types.CodeInfo) bool) - IterateContractInfo(ctx sdk.Context, cb func(sdk.AccAddress, types.ContractInfo) bool) - QuerySmart(ctx sdk.Context, contractAddr sdk.AccAddress, req []byte) ([]byte, error) - PeekAutoIncrementID(ctx sdk.Context, lastIDKey []byte) uint64 -} -type BankKeeper interface { - simulation.BankKeeper - IsSendEnabledCoin(ctx sdk.Context, coin sdk.Coin) bool -} - -// WeightedOperations returns all the operations from the module with their respective weights -func WeightedOperations( - simstate *module.SimulationState, - ak types.AccountKeeper, - bk BankKeeper, - wasmKeeper WasmKeeper, -) simulation.WeightedOperations { - var ( - weightMsgStoreCode int - weightMsgInstantiateContract int - weightMsgExecuteContract int - weightMsgUpdateAdmin int - weightMsgClearAdmin int - weightMsgMigrateContract int - wasmContractPath string - ) - - simstate.AppParams.GetOrGenerate(simstate.Cdc, OpWeightMsgStoreCode, &weightMsgStoreCode, nil, - func(_ *rand.Rand) { - weightMsgStoreCode = params.DefaultWeightMsgStoreCode - }, - ) - simstate.AppParams.GetOrGenerate(simstate.Cdc, OpWeightMsgInstantiateContract, &weightMsgInstantiateContract, nil, - func(_ *rand.Rand) { - weightMsgInstantiateContract = params.DefaultWeightMsgInstantiateContract - }, - ) - simstate.AppParams.GetOrGenerate(simstate.Cdc, OpWeightMsgExecuteContract, &weightMsgInstantiateContract, nil, - func(_ *rand.Rand) { - weightMsgExecuteContract = params.DefaultWeightMsgExecuteContract - }, - ) - simstate.AppParams.GetOrGenerate(simstate.Cdc, OpWeightMsgUpdateAdmin, &weightMsgUpdateAdmin, nil, - func(_ *rand.Rand) { - weightMsgUpdateAdmin = params.DefaultWeightMsgUpdateAdmin - }, - ) - simstate.AppParams.GetOrGenerate(simstate.Cdc, OpWeightMsgClearAdmin, &weightMsgClearAdmin, nil, - func(_ *rand.Rand) { - weightMsgClearAdmin = params.DefaultWeightMsgClearAdmin - }, - ) - simstate.AppParams.GetOrGenerate(simstate.Cdc, OpWeightMsgMigrateContract, &weightMsgMigrateContract, nil, - func(_ *rand.Rand) { - weightMsgMigrateContract = params.DefaultWeightMsgMigrateContract - }, - ) - simstate.AppParams.GetOrGenerate(simstate.Cdc, OpReflectContractPath, &wasmContractPath, nil, - func(_ *rand.Rand) { - wasmContractPath = "" - }, - ) - - var wasmBz []byte - if wasmContractPath == "" { - wasmBz = testdata.MigrateReflectContractWasm() - } else { - var err error - wasmBz, err = os.ReadFile(wasmContractPath) - if err != nil { - panic(err) - } - } - return simulation.WeightedOperations{ - simulation.NewWeightedOperation( - weightMsgStoreCode, - SimulateMsgStoreCode(ak, bk, wasmKeeper, wasmBz), - ), - simulation.NewWeightedOperation( - weightMsgInstantiateContract, - SimulateMsgInstantiateContract(ak, bk, wasmKeeper, DefaultSimulationCodeIDSelector), - ), - simulation.NewWeightedOperation( - weightMsgExecuteContract, - SimulateMsgExecuteContract( - ak, - bk, - wasmKeeper, - DefaultSimulationExecuteContractSelector, - DefaultSimulationExecuteSenderSelector, - DefaultSimulationExecutePayloader, - ), - ), - simulation.NewWeightedOperation( - weightMsgUpdateAdmin, - SimulateMsgUpdateAmin( - ak, - bk, - wasmKeeper, - DefaultSimulationUpdateAdminContractSelector, - ), - ), - simulation.NewWeightedOperation( - weightMsgClearAdmin, - SimulateMsgClearAdmin( - ak, - bk, - wasmKeeper, - DefaultSimulationClearAdminContractSelector, - ), - ), - simulation.NewWeightedOperation( - weightMsgMigrateContract, - SimulateMsgMigrateContract( - ak, - bk, - wasmKeeper, - DefaultSimulationMigrateContractSelector, - DefaultSimulationMigrateCodeIDSelector, - ), - ), - } -} - -type ( - MsgMigrateContractSelector func(sdk.Context, WasmKeeper, string) (sdk.AccAddress, types.ContractInfo) - MsgMigrateCodeIDSelector func(sdk.Context, WasmKeeper, uint64) uint64 -) - -func DefaultSimulationMigrateContractSelector(ctx sdk.Context, wasmKeeper WasmKeeper, adminAddress string) (sdk.AccAddress, types.ContractInfo) { - var contractAddress sdk.AccAddress - var contractInfo types.ContractInfo - wasmKeeper.IterateContractInfo(ctx, func(address sdk.AccAddress, info types.ContractInfo) bool { - if info.Admin != adminAddress { - return false - } - contractAddress = address - contractInfo = info - return true - }) - return contractAddress, contractInfo -} - -func DefaultSimulationMigrateCodeIDSelector(ctx sdk.Context, wasmKeeper WasmKeeper, currentCodeID uint64) uint64 { - var codeID uint64 - wasmKeeper.IterateCodeInfos(ctx, func(u uint64, info types.CodeInfo) bool { - if (info.InstantiateConfig.Permission != types.AccessTypeEverybody) || (u == currentCodeID) { - return false - } - codeID = u - return true - }) - return codeID -} - -func SimulateMsgMigrateContract( - ak types.AccountKeeper, - bk BankKeeper, - wasmKeeper WasmKeeper, - contractSelector MsgMigrateContractSelector, - codeIDSelector MsgMigrateCodeIDSelector, -) simtypes.Operation { - return func( - r *rand.Rand, - app *baseapp.BaseApp, - ctx sdk.Context, - accs []simtypes.Account, - chainID string, - ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - simAccount, _ := simtypes.RandomAcc(r, accs) - ctAddress, info := contractSelector(ctx, wasmKeeper, simAccount.Address.String()) - if ctAddress == nil { - return simtypes.NoOpMsg(types.ModuleName, types.MsgMigrateContract{}.Type(), "no contract instance available"), nil, nil - } - - codeID := codeIDSelector(ctx, wasmKeeper, info.CodeID) - if codeID == 0 { - return simtypes.NoOpMsg(types.ModuleName, types.MsgMigrateContract{}.Type(), "no target contract available"), nil, nil - } - migrateMsg := types.MsgMigrateContract{ - Sender: simAccount.Address.String(), - Contract: ctAddress.String(), - CodeID: codeID, - Msg: []byte(`{}`), - } - - txCtx := BuildOperationInput(r, app, ctx, &migrateMsg, simAccount, ak, bk, nil) - return simulation.GenAndDeliverTxWithRandFees(txCtx) - } -} - -type MsgClearAdminContractSelector func(sdk.Context, WasmKeeper, string) sdk.AccAddress - -func DefaultSimulationClearAdminContractSelector(ctx sdk.Context, wasmKeeper WasmKeeper, adminAddress string) sdk.AccAddress { - var ctAddress sdk.AccAddress - wasmKeeper.IterateContractInfo(ctx, func(addr sdk.AccAddress, info types.ContractInfo) bool { - if info.Admin != adminAddress { - return false - } - ctAddress = addr - return true - }) - return ctAddress -} - -func SimulateMsgClearAdmin( - ak types.AccountKeeper, - bk BankKeeper, - wasmKeeper WasmKeeper, - contractSelector MsgClearAdminContractSelector, -) simtypes.Operation { - return func( - r *rand.Rand, - app *baseapp.BaseApp, - ctx sdk.Context, - accounts []simtypes.Account, - chainID string, - ) (OperationMsg simtypes.OperationMsg, futureOps []simtypes.FutureOperation, err error) { - simAccount, _ := simtypes.RandomAcc(r, accounts) - ctAddress := contractSelector(ctx, wasmKeeper, simAccount.Address.String()) - if ctAddress == nil { - return simtypes.NoOpMsg(types.ModuleName, types.MsgClearAdmin{}.Type(), "no contract instance available"), nil, nil - } - - msg := types.MsgClearAdmin{ - Sender: simAccount.Address.String(), - Contract: ctAddress.String(), - } - txCtx := BuildOperationInput(r, app, ctx, &msg, simAccount, ak, bk, nil) - return simulation.GenAndDeliverTxWithRandFees(txCtx) - } -} - -type MsgUpdateAdminContractSelector func(sdk.Context, WasmKeeper, string) (sdk.AccAddress, types.ContractInfo) - -// DefaultSimulationUpdateAdminContractSelector picks the first contract which Admin != "" -func DefaultSimulationUpdateAdminContractSelector(ctx sdk.Context, wasmKeeper WasmKeeper, adminAddress string) (sdk.AccAddress, types.ContractInfo) { - var contractAddress sdk.AccAddress - var contractInfo types.ContractInfo - wasmKeeper.IterateContractInfo(ctx, func(address sdk.AccAddress, info types.ContractInfo) bool { - if info.Admin != adminAddress { - return false - } - contractAddress = address - contractInfo = info - return true - }) - return contractAddress, contractInfo -} - -func SimulateMsgUpdateAmin( - ak types.AccountKeeper, - bk BankKeeper, - wasmKeeper WasmKeeper, - contractSelector MsgUpdateAdminContractSelector, -) simtypes.Operation { - return func( - r *rand.Rand, - app *baseapp.BaseApp, - ctx sdk.Context, - accs []simtypes.Account, - chainID string, - ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - simAccount, _ := simtypes.RandomAcc(r, accs) - ctAddress, _ := contractSelector(ctx, wasmKeeper, simAccount.Address.String()) - if ctAddress == nil { - return simtypes.NoOpMsg(types.ModuleName, types.MsgUpdateAdmin{}.Type(), "no contract instance available"), nil, nil - } - - newAdmin, _ := simtypes.RandomAcc(r, accs) - if newAdmin.Address.String() == simAccount.Address.String() { - return simtypes.NoOpMsg(types.ModuleName, types.MsgUpdateAdmin{}.Type(), "new admin cannot be the same as current admin"), nil, nil - } - - msg := types.MsgUpdateAdmin{ - Sender: simAccount.Address.String(), - NewAdmin: newAdmin.Address.String(), - Contract: ctAddress.String(), - } - txCtx := BuildOperationInput(r, app, ctx, &msg, simAccount, ak, bk, nil) - return simulation.GenAndDeliverTxWithRandFees(txCtx) - } -} - -// SimulateMsgStoreCode generates a MsgStoreCode with random values -func SimulateMsgStoreCode( - ak types.AccountKeeper, - bk BankKeeper, - wasmKeeper WasmKeeper, - wasmBz []byte, -) simtypes.Operation { - return func( - r *rand.Rand, - app *baseapp.BaseApp, - ctx sdk.Context, - accs []simtypes.Account, - chainID string, - ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - if wasmKeeper.GetParams(ctx).CodeUploadAccess.Permission != types.AccessTypeEverybody { - return simtypes.NoOpMsg(types.ModuleName, types.MsgStoreCode{}.Type(), "no chain permission"), nil, nil - } - - simAccount, _ := simtypes.RandomAcc(r, accs) - - permission := wasmKeeper.GetParams(ctx).InstantiateDefaultPermission - config := permission.With(simAccount.Address) - - msg := types.MsgStoreCode{ - Sender: simAccount.Address.String(), - WASMByteCode: wasmBz, - InstantiatePermission: &config, - } - txCtx := BuildOperationInput(r, app, ctx, &msg, simAccount, ak, bk, nil) - return simulation.GenAndDeliverTxWithRandFees(txCtx) - } -} - -// CodeIDSelector returns code id to be used in simulations -type CodeIDSelector = func(ctx sdk.Context, wasmKeeper WasmKeeper) uint64 - -// DefaultSimulationCodeIDSelector picks the first code id -func DefaultSimulationCodeIDSelector(ctx sdk.Context, wasmKeeper WasmKeeper) uint64 { - var codeID uint64 - wasmKeeper.IterateCodeInfos(ctx, func(u uint64, info types.CodeInfo) bool { - if info.InstantiateConfig.Permission != types.AccessTypeEverybody { - return false - } - codeID = u - return true - }) - return codeID -} - -// SimulateMsgInstantiateContract generates a MsgInstantiateContract with random values -func SimulateMsgInstantiateContract( - ak types.AccountKeeper, - bk BankKeeper, - wasmKeeper WasmKeeper, - codeSelector CodeIDSelector, -) simtypes.Operation { - return func( - r *rand.Rand, - app *baseapp.BaseApp, - ctx sdk.Context, - accs []simtypes.Account, - chainID string, - ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - simAccount, _ := simtypes.RandomAcc(r, accs) - - codeID := codeSelector(ctx, wasmKeeper) - if codeID == 0 { - return simtypes.NoOpMsg(types.ModuleName, types.MsgInstantiateContract{}.Type(), "no codes with permission available"), nil, nil - } - deposit := sdk.Coins{} - spendableCoins := bk.SpendableCoins(ctx, simAccount.Address) - for _, v := range spendableCoins { - if bk.IsSendEnabledCoin(ctx, v) { - deposit = deposit.Add(simtypes.RandSubsetCoins(r, sdk.NewCoins(v))...) - } - } - - adminAccount, _ := simtypes.RandomAcc(r, accs) - - msg := types.MsgInstantiateContract{ - Sender: simAccount.Address.String(), - Admin: adminAccount.Address.String(), - CodeID: codeID, - Label: simtypes.RandStringOfLength(r, 10), - Msg: []byte(`{}`), - Funds: deposit, - } - txCtx := BuildOperationInput(r, app, ctx, &msg, simAccount, ak, bk, deposit) - return simulation.GenAndDeliverTxWithRandFees(txCtx) - } -} - -// MsgExecuteContractSelector returns contract address to be used in simulations -type MsgExecuteContractSelector = func(ctx sdk.Context, wasmKeeper WasmKeeper) sdk.AccAddress - -// MsgExecutePayloader extension point to modify msg with custom payload -type MsgExecutePayloader func(msg *types.MsgExecuteContract) error - -// MsgExecuteSenderSelector extension point that returns the sender address -type MsgExecuteSenderSelector func(wasmKeeper WasmKeeper, ctx sdk.Context, contractAddr sdk.AccAddress, accs []simtypes.Account) (simtypes.Account, error) - -// SimulateMsgExecuteContract create a execute message a reflect contract instance -func SimulateMsgExecuteContract( - ak types.AccountKeeper, - bk BankKeeper, - wasmKeeper WasmKeeper, - contractSelector MsgExecuteContractSelector, - senderSelector MsgExecuteSenderSelector, - payloader MsgExecutePayloader, -) simtypes.Operation { - return func( - r *rand.Rand, - app *baseapp.BaseApp, - ctx sdk.Context, - accs []simtypes.Account, - chainID string, - ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - contractAddr := contractSelector(ctx, wasmKeeper) - if contractAddr == nil { - return simtypes.NoOpMsg(types.ModuleName, types.MsgExecuteContract{}.Type(), "no contract instance available"), nil, nil - } - simAccount, err := senderSelector(wasmKeeper, ctx, contractAddr, accs) - if err != nil { - return simtypes.NoOpMsg(types.ModuleName, types.MsgExecuteContract{}.Type(), "query contract owner"), nil, err - } - - deposit := sdk.Coins{} - spendableCoins := bk.SpendableCoins(ctx, simAccount.Address) - for _, v := range spendableCoins { - if bk.IsSendEnabledCoin(ctx, v) { - deposit = deposit.Add(simtypes.RandSubsetCoins(r, sdk.NewCoins(v))...) - } - } - if deposit.IsZero() { - return simtypes.NoOpMsg(types.ModuleName, types.MsgExecuteContract{}.Type(), "broke account"), nil, nil - } - msg := types.MsgExecuteContract{ - Sender: simAccount.Address.String(), - Contract: contractAddr.String(), - Funds: deposit, - } - if err := payloader(&msg); err != nil { - return simtypes.NoOpMsg(types.ModuleName, types.MsgExecuteContract{}.Type(), "contract execute payload"), nil, err - } - - txCtx := BuildOperationInput(r, app, ctx, &msg, simAccount, ak, bk, deposit) - return simulation.GenAndDeliverTxWithRandFees(txCtx) - } -} - -// BuildOperationInput helper to build object -func BuildOperationInput( - r *rand.Rand, - app *baseapp.BaseApp, - ctx sdk.Context, - msg interface { - sdk.Msg - Type() string - }, - simAccount simtypes.Account, - ak types.AccountKeeper, - bk BankKeeper, - deposit sdk.Coins, -) simulation.OperationInput { - interfaceRegistry := codectypes.NewInterfaceRegistry() - txConfig := tx.NewTxConfig(codec.NewProtoCodec(interfaceRegistry), tx.DefaultSignModes) - return simulation.OperationInput{ - R: r, - App: app, - TxGen: txConfig, - Cdc: nil, - Msg: msg, - MsgType: msg.Type(), - Context: ctx, - SimAccount: simAccount, - AccountKeeper: ak, - Bankkeeper: bk, - ModuleName: types.ModuleName, - CoinsSpentInMsg: deposit, - } -} - -// DefaultSimulationExecuteContractSelector picks the first contract address -func DefaultSimulationExecuteContractSelector(ctx sdk.Context, wasmKeeper WasmKeeper) sdk.AccAddress { - var r sdk.AccAddress - wasmKeeper.IterateContractInfo(ctx, func(address sdk.AccAddress, info types.ContractInfo) bool { - r = address - return true - }) - return r -} - -// DefaultSimulationExecuteSenderSelector queries reflect contract for owner address and selects accounts -func DefaultSimulationExecuteSenderSelector(wasmKeeper WasmKeeper, ctx sdk.Context, contractAddr sdk.AccAddress, accs []simtypes.Account) (simtypes.Account, error) { - var none simtypes.Account - bz, err := json.Marshal(testdata.ReflectQueryMsg{Owner: &struct{}{}}) - if err != nil { - return none, errorsmod.Wrap(err, "build smart query") - } - got, err := wasmKeeper.QuerySmart(ctx, contractAddr, bz) - if err != nil { - return none, errorsmod.Wrap(err, "exec smart query") - } - var ownerRes testdata.OwnerResponse - if err := json.Unmarshal(got, &ownerRes); err != nil || ownerRes.Owner == "" { - return none, errorsmod.Wrap(err, "parse smart query response") - } - ownerAddr, err := sdk.AccAddressFromBech32(ownerRes.Owner) - if err != nil { - return none, errorsmod.Wrap(err, "parse contract owner address") - } - simAccount, ok := simtypes.FindAccount(accs, ownerAddr) - if !ok { - return none, errorsmod.Wrap(err, "unknown contract owner address") - } - return simAccount, nil -} - -// DefaultSimulationExecutePayloader implements a bank msg to send the -// tokens from contract account back to original sender -func DefaultSimulationExecutePayloader(msg *types.MsgExecuteContract) error { - reflectSend := testdata.ReflectHandleMsg{ - Reflect: &testdata.ReflectPayload{ - Msgs: []wasmvmtypes.CosmosMsg{{ - Bank: &wasmvmtypes.BankMsg{ - Send: &wasmvmtypes.SendMsg{ - ToAddress: msg.Sender, // - Amount: wasmkeeper.ConvertSdkCoinsToWasmCoins(msg.Funds), - }, - }, - }}, - }, - } - reflectSendBz, err := json.Marshal(reflectSend) - if err != nil { - return err - } - msg.Msg = reflectSendBz - return nil -} diff --git a/x/wasm/simulation/proposals.go b/x/wasm/simulation/proposals.go deleted file mode 100644 index 04a4c08..0000000 --- a/x/wasm/simulation/proposals.go +++ /dev/null @@ -1,369 +0,0 @@ -package simulation - -import ( - "math/rand" - - sdk "github.com/cosmos/cosmos-sdk/types" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/simulation" - - "github.com/terpnetwork/terp-core/app/params" - "github.com/terpnetwork/terp-core/x/wasm/keeper/testdata" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -const ( - WeightStoreCodeProposal = "weight_store_code_proposal" - WeightInstantiateContractProposal = "weight_instantiate_contract_proposal" - WeightUpdateAdminProposal = "weight_update_admin_proposal" - WeightExeContractProposal = "weight_execute_contract_proposal" - WeightClearAdminProposal = "weight_clear_admin_proposal" - WeightMigrateContractProposal = "weight_migrate_contract_proposal" - WeightSudoContractProposal = "weight_sudo_contract_proposal" - WeightPinCodesProposal = "weight_pin_codes_proposal" - WeightUnpinCodesProposal = "weight_unpin_codes_proposal" - WeightUpdateInstantiateConfigProposal = "weight_update_instantiate_config_proposal" - WeightStoreAndInstantiateContractProposal = "weight_store_and_instantiate_contract_proposal" -) - -func ProposalMsgs(bk BankKeeper, wasmKeeper WasmKeeper) []simtypes.WeightedProposalMsg { - return []simtypes.WeightedProposalMsg{ - simulation.NewWeightedProposalMsg( - WeightInstantiateContractProposal, - params.DefaultWeightInstantiateContractProposal, - SimulateInstantiateContractProposal( - bk, - wasmKeeper, - DefaultSimulationCodeIDSelector, - ), - ), - simulation.NewWeightedProposalMsg( - WeightUpdateAdminProposal, - params.DefaultWeightUpdateAdminProposal, - SimulateUpdateAdminProposal( - wasmKeeper, - DefaultSimulateUpdateAdminProposalContractSelector, - ), - ), - simulation.NewWeightedProposalMsg( - WeightExeContractProposal, - params.DefaultWeightExecuteContractProposal, - SimulateExecuteContractProposal( - bk, - wasmKeeper, - DefaultSimulationExecuteContractSelector, - DefaultSimulationExecuteSenderSelector, - DefaultSimulationExecutePayloader, - ), - ), - simulation.NewWeightedProposalMsg( - WeightClearAdminProposal, - params.DefaultWeightClearAdminProposal, - SimulateClearAdminProposal( - wasmKeeper, - DefaultSimulateContractSelector, - ), - ), - simulation.NewWeightedProposalMsg( - WeightMigrateContractProposal, - params.DefaultWeightMigrateContractProposal, - SimulateMigrateContractProposal( - wasmKeeper, - DefaultSimulateContractSelector, - DefaultSimulationCodeIDSelector, - ), - ), - simulation.NewWeightedProposalMsg( - WeightPinCodesProposal, - params.DefaultWeightPinCodesProposal, - SimulatePinContractProposal( - wasmKeeper, - DefaultSimulationCodeIDSelector, - ), - ), - simulation.NewWeightedProposalMsg( - WeightUnpinCodesProposal, - params.DefaultWeightUnpinCodesProposal, - SimulateUnpinContractProposal( - wasmKeeper, - DefaultSimulationCodeIDSelector, - ), - ), - simulation.NewWeightedProposalMsg( - WeightUpdateInstantiateConfigProposal, - params.DefaultWeightUpdateInstantiateConfigProposal, - SimulateUpdateInstantiateConfigProposal( - wasmKeeper, - DefaultSimulationCodeIDSelector, - ), - ), - } -} - -// simulate store code proposal (unused now) -// Current problem: out of gas (defaul gaswanted config of gov SimulateMsgSubmitProposal is 10_000_000) -// but this proposal may need more than it -func SimulateStoreCodeProposal(wasmKeeper WasmKeeper) simtypes.MsgSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) sdk.Msg { - authority := wasmKeeper.GetAuthority() - - simAccount, _ := simtypes.RandomAcc(r, accs) - - wasmBz := testdata.ReflectContractWasm() - - permission := wasmKeeper.GetParams(ctx).InstantiateDefaultPermission.With(simAccount.Address) - - return &types.MsgStoreCode{ - Sender: authority, - WASMByteCode: wasmBz, - InstantiatePermission: &permission, - } - } -} - -// Simulate instantiate contract proposal -func SimulateInstantiateContractProposal(bk BankKeeper, wasmKeeper WasmKeeper, codeSelector CodeIDSelector) simtypes.MsgSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) sdk.Msg { - authority := wasmKeeper.GetAuthority() - - // admin - adminAccount, _ := simtypes.RandomAcc(r, accs) - // get codeID - codeID := codeSelector(ctx, wasmKeeper) - if codeID == 0 { - return nil - } - - return &types.MsgInstantiateContract{ - Sender: authority, - Admin: adminAccount.Address.String(), - CodeID: codeID, - Label: simtypes.RandStringOfLength(r, 10), - Msg: []byte(`{}`), - Funds: sdk.Coins{}, - } - } -} - -// Simulate execute contract proposal -func SimulateExecuteContractProposal( - _ BankKeeper, - wasmKeeper WasmKeeper, - contractSelector MsgExecuteContractSelector, - senderSelector MsgExecuteSenderSelector, - payloader MsgExecutePayloader, -) simtypes.MsgSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) sdk.Msg { - authority := wasmKeeper.GetAuthority() - - ctAddress := contractSelector(ctx, wasmKeeper) - if ctAddress == nil { - return nil - } - - msg := &types.MsgExecuteContract{ - Sender: authority, - Contract: ctAddress.String(), - Funds: sdk.Coins{}, - } - - if err := payloader(msg); err != nil { - return nil - } - - return msg - } -} - -type UpdateAdminContractSelector func(sdk.Context, WasmKeeper, string) (sdk.AccAddress, types.ContractInfo) - -func DefaultSimulateUpdateAdminProposalContractSelector( - ctx sdk.Context, - wasmKeeper WasmKeeper, - adminAddress string, -) (sdk.AccAddress, types.ContractInfo) { - var contractAddr sdk.AccAddress - var contractInfo types.ContractInfo - wasmKeeper.IterateContractInfo(ctx, func(address sdk.AccAddress, info types.ContractInfo) bool { - if info.Admin != adminAddress { - return false - } - contractAddr = address - contractInfo = info - return true - }) - return contractAddr, contractInfo -} - -// Simulate update admin contract proposal -func SimulateUpdateAdminProposal(wasmKeeper WasmKeeper, contractSelector UpdateAdminContractSelector) simtypes.MsgSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) sdk.Msg { - authority := wasmKeeper.GetAuthority() - simAccount, _ := simtypes.RandomAcc(r, accs) - ctAddress, _ := contractSelector(ctx, wasmKeeper, simAccount.Address.String()) - if ctAddress == nil { - return nil - } - - return &types.MsgUpdateAdmin{ - Sender: authority, - NewAdmin: simtypes.RandomAccounts(r, 1)[0].Address.String(), - Contract: ctAddress.String(), - } - } -} - -type ClearAdminContractSelector func(sdk.Context, WasmKeeper) sdk.AccAddress - -func DefaultSimulateContractSelector( - ctx sdk.Context, - wasmKeeper WasmKeeper, -) sdk.AccAddress { - var contractAddr sdk.AccAddress - wasmKeeper.IterateContractInfo(ctx, func(address sdk.AccAddress, info types.ContractInfo) bool { - contractAddr = address - return true - }) - return contractAddr -} - -// Simulate clear admin proposal -func SimulateClearAdminProposal(wasmKeeper WasmKeeper, contractSelector ClearAdminContractSelector) simtypes.MsgSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) sdk.Msg { - authority := wasmKeeper.GetAuthority() - - ctAddress := contractSelector(ctx, wasmKeeper) - if ctAddress == nil { - return nil - } - return &types.MsgClearAdmin{ - Sender: authority, - Contract: ctAddress.String(), - } - } -} - -type MigrateContractProposalContractSelector func(sdk.Context, WasmKeeper) sdk.AccAddress - -// Simulate migrate contract proposal -func SimulateMigrateContractProposal(wasmKeeper WasmKeeper, contractSelector MigrateContractProposalContractSelector, codeSelector CodeIDSelector) simtypes.MsgSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) sdk.Msg { - authority := wasmKeeper.GetAuthority() - - ctAddress := contractSelector(ctx, wasmKeeper) - if ctAddress == nil { - return nil - } - - codeID := codeSelector(ctx, wasmKeeper) - if codeID == 0 { - return nil - } - - return &types.MsgMigrateContract{ - Sender: authority, - Contract: ctAddress.String(), - CodeID: codeID, - Msg: []byte(`{}`), - } - } -} - -type SudoContractProposalContractSelector func(sdk.Context, WasmKeeper) sdk.AccAddress - -// Simulate sudo contract proposal -func SimulateSudoContractProposal(wasmKeeper WasmKeeper, contractSelector SudoContractProposalContractSelector) simtypes.MsgSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) sdk.Msg { - authority := wasmKeeper.GetAuthority() - - ctAddress := contractSelector(ctx, wasmKeeper) - if ctAddress == nil { - return nil - } - - return &types.MsgSudoContract{ - Authority: authority, - Contract: ctAddress.String(), - Msg: []byte(`{}`), - } - } -} - -// Simulate pin contract proposal -func SimulatePinContractProposal(wasmKeeper WasmKeeper, codeSelector CodeIDSelector) simtypes.MsgSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) sdk.Msg { - authority := wasmKeeper.GetAuthority() - - codeID := codeSelector(ctx, wasmKeeper) - if codeID == 0 { - return nil - } - - return &types.MsgPinCodes{ - Authority: authority, - CodeIDs: []uint64{codeID}, - } - } -} - -// Simulate unpin contract proposal -func SimulateUnpinContractProposal(wasmKeeper WasmKeeper, codeSelector CodeIDSelector) simtypes.MsgSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) sdk.Msg { - authority := wasmKeeper.GetAuthority() - - codeID := codeSelector(ctx, wasmKeeper) - if codeID == 0 { - return nil - } - - return &types.MsgUnpinCodes{ - Authority: authority, - CodeIDs: []uint64{codeID}, - } - } -} - -// Simulate update instantiate config proposal -func SimulateUpdateInstantiateConfigProposal(wasmKeeper WasmKeeper, codeSelector CodeIDSelector) simtypes.MsgSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) sdk.Msg { - authority := wasmKeeper.GetAuthority() - - codeID := codeSelector(ctx, wasmKeeper) - if codeID == 0 { - return nil - } - - simAccount, _ := simtypes.RandomAcc(r, accs) - permission := wasmKeeper.GetParams(ctx).InstantiateDefaultPermission - config := permission.With(simAccount.Address) - - return &types.MsgUpdateInstantiateConfig{ - Sender: authority, - CodeID: codeID, - NewInstantiatePermission: &config, - } - } -} - -func SimulateStoreAndInstantiateContractProposal(wasmKeeper WasmKeeper) simtypes.MsgSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) sdk.Msg { - authority := wasmKeeper.GetAuthority() - - simAccount, _ := simtypes.RandomAcc(r, accs) - adminAccount, _ := simtypes.RandomAcc(r, accs) - - wasmBz := testdata.ReflectContractWasm() - permission := wasmKeeper.GetParams(ctx).InstantiateDefaultPermission.With(simAccount.Address) - - return &types.MsgStoreAndInstantiateContract{ - Authority: authority, - WASMByteCode: wasmBz, - InstantiatePermission: &permission, - UnpinCode: false, - Admin: adminAccount.Address.String(), - Label: simtypes.RandStringOfLength(r, 10), - Msg: []byte(`{}`), - Funds: sdk.Coins{}, - } - } -} diff --git a/x/wasm/testdata/escrow_0.7.wasm b/x/wasm/testdata/escrow_0.7.wasm deleted file mode 100644 index 668aa74..0000000 Binary files a/x/wasm/testdata/escrow_0.7.wasm and /dev/null differ diff --git a/x/wasm/types/ante.go b/x/wasm/types/ante.go deleted file mode 100644 index 4c76efd..0000000 --- a/x/wasm/types/ante.go +++ /dev/null @@ -1,24 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" -) - -type contextKey int - -const ( - // private type creates an interface key for Context that cannot be accessed by any other package - contextKeyTXCount contextKey = iota -) - -// WithTXCounter stores a transaction counter value in the context -func WithTXCounter(ctx sdk.Context, counter uint32) sdk.Context { - return ctx.WithValue(contextKeyTXCount, counter) -} - -// TXCounter returns the tx counter value and found bool from the context. -// The result will be (0, false) for external queries or simulations where no counter available. -func TXCounter(ctx sdk.Context) (uint32, bool) { - val, ok := ctx.Value(contextKeyTXCount).(uint32) - return val, ok -} diff --git a/x/wasm/types/authz.go b/x/wasm/types/authz.go deleted file mode 100644 index 9692088..0000000 --- a/x/wasm/types/authz.go +++ /dev/null @@ -1,533 +0,0 @@ -package types - -import ( - "strings" - - errorsmod "cosmossdk.io/errors" - cdctypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - authztypes "github.com/cosmos/cosmos-sdk/x/authz" - "github.com/cosmos/gogoproto/proto" -) - -const gasDeserializationCostPerByte = uint64(1) - -var ( - _ authztypes.Authorization = &ContractExecutionAuthorization{} - _ authztypes.Authorization = &ContractMigrationAuthorization{} - _ cdctypes.UnpackInterfacesMessage = &ContractExecutionAuthorization{} - _ cdctypes.UnpackInterfacesMessage = &ContractMigrationAuthorization{} -) - -// AuthzableWasmMsg is abstract wasm tx message that is supported in authz -type AuthzableWasmMsg interface { - GetFunds() sdk.Coins - GetMsg() RawContractMessage - GetContract() string - ValidateBasic() error -} - -// NewContractExecutionAuthorization constructor -func NewContractExecutionAuthorization(grants ...ContractGrant) *ContractExecutionAuthorization { - return &ContractExecutionAuthorization{ - Grants: grants, - } -} - -// MsgTypeURL implements Authorization.MsgTypeURL. -func (a ContractExecutionAuthorization) MsgTypeURL() string { - return sdk.MsgTypeURL(&MsgExecuteContract{}) -} - -// NewAuthz factory method to create an Authorization with updated grants -func (a ContractExecutionAuthorization) NewAuthz(g []ContractGrant) authztypes.Authorization { - return NewContractExecutionAuthorization(g...) -} - -// Accept implements Authorization.Accept. -func (a *ContractExecutionAuthorization) Accept(ctx sdk.Context, msg sdk.Msg) (authztypes.AcceptResponse, error) { - return AcceptGrantedMessage[*MsgExecuteContract](ctx, a.Grants, msg, a) -} - -// ValidateBasic implements Authorization.ValidateBasic. -func (a ContractExecutionAuthorization) ValidateBasic() error { - return validateGrants(a.Grants) -} - -// UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (a ContractExecutionAuthorization) UnpackInterfaces(unpacker cdctypes.AnyUnpacker) error { - for _, g := range a.Grants { - if err := g.UnpackInterfaces(unpacker); err != nil { - return err - } - } - return nil -} - -// NewContractMigrationAuthorization constructor -func NewContractMigrationAuthorization(grants ...ContractGrant) *ContractMigrationAuthorization { - return &ContractMigrationAuthorization{ - Grants: grants, - } -} - -// MsgTypeURL implements Authorization.MsgTypeURL. -func (a ContractMigrationAuthorization) MsgTypeURL() string { - return sdk.MsgTypeURL(&MsgMigrateContract{}) -} - -// Accept implements Authorization.Accept. -func (a *ContractMigrationAuthorization) Accept(ctx sdk.Context, msg sdk.Msg) (authztypes.AcceptResponse, error) { - return AcceptGrantedMessage[*MsgMigrateContract](ctx, a.Grants, msg, a) -} - -// NewAuthz factory method to create an Authorization with updated grants -func (a ContractMigrationAuthorization) NewAuthz(g []ContractGrant) authztypes.Authorization { - return NewContractMigrationAuthorization(g...) -} - -// ValidateBasic implements Authorization.ValidateBasic. -func (a ContractMigrationAuthorization) ValidateBasic() error { - return validateGrants(a.Grants) -} - -// UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (a ContractMigrationAuthorization) UnpackInterfaces(unpacker cdctypes.AnyUnpacker) error { - for _, g := range a.Grants { - if err := g.UnpackInterfaces(unpacker); err != nil { - return err - } - } - return nil -} - -func validateGrants(g []ContractGrant) error { - if len(g) == 0 { - return ErrEmpty.Wrap("grants") - } - for i, v := range g { - if err := v.ValidateBasic(); err != nil { - return errorsmod.Wrapf(err, "position %d", i) - } - } - // allow multiple grants for a contract: - // contractA:doThis:1,doThat:* has with different counters for different methods - return nil -} - -// ContractAuthzFactory factory to create an updated Authorization object -type ContractAuthzFactory interface { - NewAuthz([]ContractGrant) authztypes.Authorization -} - -// AcceptGrantedMessage determines whether this grant permits the provided sdk.Msg to be performed, -// and if so provides an upgraded authorization instance. -func AcceptGrantedMessage[T AuthzableWasmMsg](ctx sdk.Context, grants []ContractGrant, msg sdk.Msg, factory ContractAuthzFactory) (authztypes.AcceptResponse, error) { - exec, ok := msg.(T) - if !ok { - return authztypes.AcceptResponse{}, sdkerrors.ErrInvalidType.Wrap("type mismatch") - } - if exec.GetMsg() == nil { - return authztypes.AcceptResponse{}, sdkerrors.ErrInvalidType.Wrap("empty message") - } - if err := exec.ValidateBasic(); err != nil { - return authztypes.AcceptResponse{}, err - } - - // iterate though all grants - for i, g := range grants { - if g.Contract != exec.GetContract() { - continue - } - - // first check limits - result, err := g.GetLimit().Accept(ctx, exec) - switch { - case err != nil: - return authztypes.AcceptResponse{}, errorsmod.Wrap(err, "limit") - case result == nil: // sanity check - return authztypes.AcceptResponse{}, sdkerrors.ErrInvalidType.Wrap("limit result must not be nil") - case !result.Accepted: - // not applicable, continue with next grant - continue - } - - // then check permission set - ok, err := g.GetFilter().Accept(ctx, exec.GetMsg()) - switch { - case err != nil: - return authztypes.AcceptResponse{}, errorsmod.Wrap(err, "filter") - case !ok: - // no limit update and continue with next grant - continue - } - - // finally do limit state updates in result - switch { - case result.DeleteLimit: - updatedGrants := append(grants[0:i], grants[i+1:]...) //nolint:gocritic - if len(updatedGrants) == 0 { // remove when empty - return authztypes.AcceptResponse{Accept: true, Delete: true}, nil - } - newAuthz := factory.NewAuthz(updatedGrants) - if err := newAuthz.ValidateBasic(); err != nil { // sanity check - return authztypes.AcceptResponse{}, ErrInvalid.Wrapf("new grant state: %s", err) - } - return authztypes.AcceptResponse{Accept: true, Updated: newAuthz}, nil - case result.UpdateLimit != nil: - obj, err := g.WithNewLimits(result.UpdateLimit) - if err != nil { - return authztypes.AcceptResponse{}, err - } - newAuthz := factory.NewAuthz(append(append(grants[0:i], *obj), grants[i+1:]...)) - if err := newAuthz.ValidateBasic(); err != nil { // sanity check - return authztypes.AcceptResponse{}, ErrInvalid.Wrapf("new grant state: %s", err) - } - return authztypes.AcceptResponse{Accept: true, Updated: newAuthz}, nil - default: // accepted without a limit state update - return authztypes.AcceptResponse{Accept: true}, nil - } - } - return authztypes.AcceptResponse{Accept: false}, nil -} - -// ContractAuthzLimitX define execution limits that are enforced and updated when the grant -// is applied. When the limit lapsed the grant is removed. -type ContractAuthzLimitX interface { - Accept(ctx sdk.Context, msg AuthzableWasmMsg) (*ContractAuthzLimitAcceptResult, error) - ValidateBasic() error -} - -// ContractAuthzLimitAcceptResult result of the ContractAuthzLimitX.Accept method -type ContractAuthzLimitAcceptResult struct { - // Accepted is true when limit applies - Accepted bool - // DeleteLimit when set it is the end of life for this limit. Grant is removed from persistent store - DeleteLimit bool - // UpdateLimit update persistent state with new value - UpdateLimit ContractAuthzLimitX -} - -// ContractAuthzFilterX define more fine-grained control on the message payload passed -// to the contract in the operation. When no filter applies on execution, the -// operation is prohibited. -type ContractAuthzFilterX interface { - // Accept returns applicable or error - Accept(ctx sdk.Context, msg RawContractMessage) (bool, error) - ValidateBasic() error -} - -var _ cdctypes.UnpackInterfacesMessage = &ContractGrant{} - -// NewContractGrant constructor -func NewContractGrant(contract sdk.AccAddress, limit ContractAuthzLimitX, filter ContractAuthzFilterX) (*ContractGrant, error) { - pFilter, ok := filter.(proto.Message) - if !ok { - return nil, sdkerrors.ErrInvalidType.Wrap("filter is not a proto type") - } - anyFilter, err := cdctypes.NewAnyWithValue(pFilter) - if err != nil { - return nil, errorsmod.Wrap(err, "filter") - } - return ContractGrant{ - Contract: contract.String(), - Filter: anyFilter, - }.WithNewLimits(limit) -} - -// WithNewLimits factory method to create a new grant with given limit -func (g ContractGrant) WithNewLimits(limit ContractAuthzLimitX) (*ContractGrant, error) { - pLimit, ok := limit.(proto.Message) - if !ok { - return nil, sdkerrors.ErrInvalidType.Wrap("limit is not a proto type") - } - anyLimit, err := cdctypes.NewAnyWithValue(pLimit) - if err != nil { - return nil, errorsmod.Wrap(err, "limit") - } - - return &ContractGrant{ - Contract: g.Contract, - Limit: anyLimit, - Filter: g.Filter, - }, nil -} - -// UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (g ContractGrant) UnpackInterfaces(unpacker cdctypes.AnyUnpacker) error { - var f ContractAuthzFilterX - if err := unpacker.UnpackAny(g.Filter, &f); err != nil { - return errorsmod.Wrap(err, "filter") - } - var l ContractAuthzLimitX - if err := unpacker.UnpackAny(g.Limit, &l); err != nil { - return errorsmod.Wrap(err, "limit") - } - return nil -} - -// GetLimit returns the cached value from the ContractGrant.Limit if present. -func (g ContractGrant) GetLimit() ContractAuthzLimitX { - if g.Limit == nil { - return &UndefinedLimit{} - } - a, ok := g.Limit.GetCachedValue().(ContractAuthzLimitX) - if !ok { - return &UndefinedLimit{} - } - return a -} - -// GetFilter returns the cached value from the ContractGrant.Filter if present. -func (g ContractGrant) GetFilter() ContractAuthzFilterX { - if g.Filter == nil { - return &UndefinedFilter{} - } - a, ok := g.Filter.GetCachedValue().(ContractAuthzFilterX) - if !ok { - return &UndefinedFilter{} - } - return a -} - -// ValidateBasic validates the grant -func (g ContractGrant) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(g.Contract); err != nil { - return errorsmod.Wrap(err, "contract") - } - // execution limits - if err := g.GetLimit().ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "limit") - } - // filter - if err := g.GetFilter().ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "filter") - } - return nil -} - -// UndefinedFilter null object that is always rejected in execution -type UndefinedFilter struct{} - -// Accept always returns error -func (f *UndefinedFilter) Accept(_ sdk.Context, _ RawContractMessage) (bool, error) { - return false, sdkerrors.ErrNotFound.Wrapf("undefined filter") -} - -// ValidateBasic always returns error -func (f UndefinedFilter) ValidateBasic() error { - return sdkerrors.ErrInvalidType.Wrapf("undefined filter") -} - -// NewAllowAllMessagesFilter constructor -func NewAllowAllMessagesFilter() *AllowAllMessagesFilter { - return &AllowAllMessagesFilter{} -} - -// Accept accepts any valid json message content. -func (f *AllowAllMessagesFilter) Accept(_ sdk.Context, msg RawContractMessage) (bool, error) { - return true, msg.ValidateBasic() -} - -// ValidateBasic returns always nil -func (f AllowAllMessagesFilter) ValidateBasic() error { - return nil -} - -// NewAcceptedMessageKeysFilter constructor -func NewAcceptedMessageKeysFilter(acceptedKeys ...string) *AcceptedMessageKeysFilter { - return &AcceptedMessageKeysFilter{Keys: acceptedKeys} -} - -// Accept only payload messages which contain one of the accepted key names in the json object. -func (f *AcceptedMessageKeysFilter) Accept(ctx sdk.Context, msg RawContractMessage) (bool, error) { - gasForDeserialization := gasDeserializationCostPerByte * uint64(len(msg)) - ctx.GasMeter().ConsumeGas(gasForDeserialization, "contract authorization") - - ok, err := isJSONObjectWithTopLevelKey(msg, f.Keys) - if err != nil { - return false, sdkerrors.ErrUnauthorized.Wrapf("not an allowed msg: %s", err.Error()) - } - return ok, nil -} - -// ValidateBasic validates the filter -func (f AcceptedMessageKeysFilter) ValidateBasic() error { - if len(f.Keys) == 0 { - return ErrEmpty.Wrap("keys") - } - idx := make(map[string]struct{}, len(f.Keys)) - for _, m := range f.Keys { - if m == "" { - return ErrEmpty.Wrap("key") - } - if m != strings.TrimSpace(m) { - return ErrInvalid.Wrapf("key %q contains whitespaces", m) - } - if _, exists := idx[m]; exists { - return ErrDuplicate.Wrapf("key %q", m) - } - idx[m] = struct{}{} - } - return nil -} - -// NewAcceptedMessagesFilter constructor -func NewAcceptedMessagesFilter(msgs ...RawContractMessage) *AcceptedMessagesFilter { - return &AcceptedMessagesFilter{Messages: msgs} -} - -// Accept only payload messages which are equal to the granted one. -func (f *AcceptedMessagesFilter) Accept(_ sdk.Context, msg RawContractMessage) (bool, error) { - for _, v := range f.Messages { - if v.Equal(msg) { - return true, nil - } - } - return false, nil -} - -// ValidateBasic validates the filter -func (f AcceptedMessagesFilter) ValidateBasic() error { - if len(f.Messages) == 0 { - return ErrEmpty.Wrap("messages") - } - idx := make(map[string]struct{}, len(f.Messages)) - for _, m := range f.Messages { - if len(m) == 0 { - return ErrEmpty.Wrap("message") - } - if err := m.ValidateBasic(); err != nil { - return err - } - if _, exists := idx[string(m)]; exists { - return ErrDuplicate.Wrap("message") - } - idx[string(m)] = struct{}{} - } - return nil -} - -var ( - _ ContractAuthzLimitX = &UndefinedLimit{} - _ ContractAuthzLimitX = &MaxCallsLimit{} - _ ContractAuthzLimitX = &MaxFundsLimit{} - _ ContractAuthzLimitX = &CombinedLimit{} -) - -// UndefinedLimit null object that is always rejected in execution -type UndefinedLimit struct{} - -// ValidateBasic always returns error -func (u UndefinedLimit) ValidateBasic() error { - return sdkerrors.ErrInvalidType.Wrapf("undefined limit") -} - -// Accept always returns error -func (u UndefinedLimit) Accept(_ sdk.Context, _ AuthzableWasmMsg) (*ContractAuthzLimitAcceptResult, error) { - return nil, sdkerrors.ErrNotFound.Wrapf("undefined filter") -} - -// NewMaxCallsLimit constructor -func NewMaxCallsLimit(number uint64) *MaxCallsLimit { - return &MaxCallsLimit{Remaining: number} -} - -// Accept only the defined number of message calls. No token transfers to the contract allowed. -func (m MaxCallsLimit) Accept(_ sdk.Context, msg AuthzableWasmMsg) (*ContractAuthzLimitAcceptResult, error) { - if !msg.GetFunds().Empty() { - return &ContractAuthzLimitAcceptResult{Accepted: false}, nil - } - switch n := m.Remaining; n { - case 0: // sanity check - return nil, sdkerrors.ErrUnauthorized.Wrap("no calls left") - case 1: - return &ContractAuthzLimitAcceptResult{Accepted: true, DeleteLimit: true}, nil - default: - return &ContractAuthzLimitAcceptResult{Accepted: true, UpdateLimit: &MaxCallsLimit{Remaining: n - 1}}, nil - } -} - -// ValidateBasic validates the limit -func (m MaxCallsLimit) ValidateBasic() error { - if m.Remaining == 0 { - return ErrEmpty.Wrap("remaining calls") - } - return nil -} - -// NewMaxFundsLimit constructor -// A panic will occur if the coin set is not valid. -func NewMaxFundsLimit(max ...sdk.Coin) *MaxFundsLimit { - return &MaxFundsLimit{Amounts: sdk.NewCoins(max...)} -} - -// Accept until the defined budget for token transfers to the contract is spent -func (m MaxFundsLimit) Accept(_ sdk.Context, msg AuthzableWasmMsg) (*ContractAuthzLimitAcceptResult, error) { - if msg.GetFunds().Empty() { // no state changes required - return &ContractAuthzLimitAcceptResult{Accepted: true}, nil - } - if !msg.GetFunds().IsAllLTE(m.Amounts) { - return &ContractAuthzLimitAcceptResult{Accepted: false}, nil - } - newAmounts := m.Amounts.Sub(msg.GetFunds()...) - if newAmounts.IsZero() { - return &ContractAuthzLimitAcceptResult{Accepted: true, DeleteLimit: true}, nil - } - return &ContractAuthzLimitAcceptResult{Accepted: true, UpdateLimit: &MaxFundsLimit{Amounts: newAmounts}}, nil -} - -// ValidateBasic validates the limit -func (m MaxFundsLimit) ValidateBasic() error { - if err := m.Amounts.Validate(); err != nil { - return err - } - if m.Amounts.IsZero() { - return ErrEmpty.Wrap("amounts") - } - return nil -} - -// NewCombinedLimit constructor -// A panic will occur if the coin set is not valid. -func NewCombinedLimit(maxCalls uint64, maxAmounts ...sdk.Coin) *CombinedLimit { - return &CombinedLimit{CallsRemaining: maxCalls, Amounts: sdk.NewCoins(maxAmounts...)} -} - -// Accept until the max calls is reached or the token budget is spent. -func (l CombinedLimit) Accept(_ sdk.Context, msg AuthzableWasmMsg) (*ContractAuthzLimitAcceptResult, error) { - transferFunds := msg.GetFunds() - if !transferFunds.IsAllLTE(l.Amounts) { - return &ContractAuthzLimitAcceptResult{Accepted: false}, nil // does not apply - } - switch n := l.CallsRemaining; n { - case 0: // sanity check - return nil, sdkerrors.ErrUnauthorized.Wrap("no calls left") - case 1: - return &ContractAuthzLimitAcceptResult{Accepted: true, DeleteLimit: true}, nil - default: - remainingAmounts := l.Amounts.Sub(transferFunds...) - if remainingAmounts.IsZero() { - return &ContractAuthzLimitAcceptResult{Accepted: true, DeleteLimit: true}, nil - } - return &ContractAuthzLimitAcceptResult{ - Accepted: true, - UpdateLimit: NewCombinedLimit(n-1, remainingAmounts...), - }, nil - } -} - -// ValidateBasic validates the limit -func (l CombinedLimit) ValidateBasic() error { - if l.CallsRemaining == 0 { - return ErrEmpty.Wrap("remaining calls") - } - if l.Amounts.IsZero() { - return ErrEmpty.Wrap("amounts") - } - if err := l.Amounts.Validate(); err != nil { - return errorsmod.Wrap(err, "amounts") - } - return nil -} diff --git a/x/wasm/types/authz.pb.go b/x/wasm/types/authz.pb.go deleted file mode 100644 index 2d76723..0000000 --- a/x/wasm/types/authz.pb.go +++ /dev/null @@ -1,1870 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmwasm/wasm/v1/authz.proto - -package types - -import ( - fmt "fmt" - io "io" - math "math" - math_bits "math/bits" - - _ "github.com/cosmos/cosmos-proto" - types "github.com/cosmos/cosmos-sdk/codec/types" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types1 "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/cosmos-sdk/types/tx/amino" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = proto.Marshal - _ = fmt.Errorf - _ = math.Inf -) - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// ContractExecutionAuthorization defines authorization for wasm execute. -// Since: wasmd 0.30 -type ContractExecutionAuthorization struct { - // Grants for contract executions - Grants []ContractGrant `protobuf:"bytes,1,rep,name=grants,proto3" json:"grants"` -} - -func (m *ContractExecutionAuthorization) Reset() { *m = ContractExecutionAuthorization{} } -func (m *ContractExecutionAuthorization) String() string { return proto.CompactTextString(m) } -func (*ContractExecutionAuthorization) ProtoMessage() {} -func (*ContractExecutionAuthorization) Descriptor() ([]byte, []int) { - return fileDescriptor_36ff3a20cf32b258, []int{0} -} - -func (m *ContractExecutionAuthorization) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *ContractExecutionAuthorization) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ContractExecutionAuthorization.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *ContractExecutionAuthorization) XXX_Merge(src proto.Message) { - xxx_messageInfo_ContractExecutionAuthorization.Merge(m, src) -} - -func (m *ContractExecutionAuthorization) XXX_Size() int { - return m.Size() -} - -func (m *ContractExecutionAuthorization) XXX_DiscardUnknown() { - xxx_messageInfo_ContractExecutionAuthorization.DiscardUnknown(m) -} - -var xxx_messageInfo_ContractExecutionAuthorization proto.InternalMessageInfo - -// ContractMigrationAuthorization defines authorization for wasm contract -// migration. Since: wasmd 0.30 -type ContractMigrationAuthorization struct { - // Grants for contract migrations - Grants []ContractGrant `protobuf:"bytes,1,rep,name=grants,proto3" json:"grants"` -} - -func (m *ContractMigrationAuthorization) Reset() { *m = ContractMigrationAuthorization{} } -func (m *ContractMigrationAuthorization) String() string { return proto.CompactTextString(m) } -func (*ContractMigrationAuthorization) ProtoMessage() {} -func (*ContractMigrationAuthorization) Descriptor() ([]byte, []int) { - return fileDescriptor_36ff3a20cf32b258, []int{1} -} - -func (m *ContractMigrationAuthorization) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *ContractMigrationAuthorization) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ContractMigrationAuthorization.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *ContractMigrationAuthorization) XXX_Merge(src proto.Message) { - xxx_messageInfo_ContractMigrationAuthorization.Merge(m, src) -} - -func (m *ContractMigrationAuthorization) XXX_Size() int { - return m.Size() -} - -func (m *ContractMigrationAuthorization) XXX_DiscardUnknown() { - xxx_messageInfo_ContractMigrationAuthorization.DiscardUnknown(m) -} - -var xxx_messageInfo_ContractMigrationAuthorization proto.InternalMessageInfo - -// ContractGrant a granted permission for a single contract -// Since: wasmd 0.30 -type ContractGrant struct { - // Contract is the bech32 address of the smart contract - Contract string `protobuf:"bytes,1,opt,name=contract,proto3" json:"contract,omitempty"` - // Limit defines execution limits that are enforced and updated when the grant - // is applied. When the limit lapsed the grant is removed. - Limit *types.Any `protobuf:"bytes,2,opt,name=limit,proto3" json:"limit,omitempty"` - // Filter define more fine-grained control on the message payload passed - // to the contract in the operation. When no filter applies on execution, the - // operation is prohibited. - Filter *types.Any `protobuf:"bytes,3,opt,name=filter,proto3" json:"filter,omitempty"` -} - -func (m *ContractGrant) Reset() { *m = ContractGrant{} } -func (m *ContractGrant) String() string { return proto.CompactTextString(m) } -func (*ContractGrant) ProtoMessage() {} -func (*ContractGrant) Descriptor() ([]byte, []int) { - return fileDescriptor_36ff3a20cf32b258, []int{2} -} - -func (m *ContractGrant) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *ContractGrant) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ContractGrant.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *ContractGrant) XXX_Merge(src proto.Message) { - xxx_messageInfo_ContractGrant.Merge(m, src) -} - -func (m *ContractGrant) XXX_Size() int { - return m.Size() -} - -func (m *ContractGrant) XXX_DiscardUnknown() { - xxx_messageInfo_ContractGrant.DiscardUnknown(m) -} - -var xxx_messageInfo_ContractGrant proto.InternalMessageInfo - -// MaxCallsLimit limited number of calls to the contract. No funds transferable. -// Since: wasmd 0.30 -type MaxCallsLimit struct { - // Remaining number that is decremented on each execution - Remaining uint64 `protobuf:"varint,1,opt,name=remaining,proto3" json:"remaining,omitempty"` -} - -func (m *MaxCallsLimit) Reset() { *m = MaxCallsLimit{} } -func (m *MaxCallsLimit) String() string { return proto.CompactTextString(m) } -func (*MaxCallsLimit) ProtoMessage() {} -func (*MaxCallsLimit) Descriptor() ([]byte, []int) { - return fileDescriptor_36ff3a20cf32b258, []int{3} -} - -func (m *MaxCallsLimit) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MaxCallsLimit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MaxCallsLimit.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *MaxCallsLimit) XXX_Merge(src proto.Message) { - xxx_messageInfo_MaxCallsLimit.Merge(m, src) -} - -func (m *MaxCallsLimit) XXX_Size() int { - return m.Size() -} - -func (m *MaxCallsLimit) XXX_DiscardUnknown() { - xxx_messageInfo_MaxCallsLimit.DiscardUnknown(m) -} - -var xxx_messageInfo_MaxCallsLimit proto.InternalMessageInfo - -// MaxFundsLimit defines the maximal amounts that can be sent to the contract. -// Since: wasmd 0.30 -type MaxFundsLimit struct { - // Amounts is the maximal amount of tokens transferable to the contract. - Amounts github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,1,rep,name=amounts,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amounts"` -} - -func (m *MaxFundsLimit) Reset() { *m = MaxFundsLimit{} } -func (m *MaxFundsLimit) String() string { return proto.CompactTextString(m) } -func (*MaxFundsLimit) ProtoMessage() {} -func (*MaxFundsLimit) Descriptor() ([]byte, []int) { - return fileDescriptor_36ff3a20cf32b258, []int{4} -} - -func (m *MaxFundsLimit) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MaxFundsLimit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MaxFundsLimit.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *MaxFundsLimit) XXX_Merge(src proto.Message) { - xxx_messageInfo_MaxFundsLimit.Merge(m, src) -} - -func (m *MaxFundsLimit) XXX_Size() int { - return m.Size() -} - -func (m *MaxFundsLimit) XXX_DiscardUnknown() { - xxx_messageInfo_MaxFundsLimit.DiscardUnknown(m) -} - -var xxx_messageInfo_MaxFundsLimit proto.InternalMessageInfo - -// CombinedLimit defines the maximal amounts that can be sent to a contract and -// the maximal number of calls executable. Both need to remain >0 to be valid. -// Since: wasmd 0.30 -type CombinedLimit struct { - // Remaining number that is decremented on each execution - CallsRemaining uint64 `protobuf:"varint,1,opt,name=calls_remaining,json=callsRemaining,proto3" json:"calls_remaining,omitempty"` - // Amounts is the maximal amount of tokens transferable to the contract. - Amounts github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=amounts,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amounts"` -} - -func (m *CombinedLimit) Reset() { *m = CombinedLimit{} } -func (m *CombinedLimit) String() string { return proto.CompactTextString(m) } -func (*CombinedLimit) ProtoMessage() {} -func (*CombinedLimit) Descriptor() ([]byte, []int) { - return fileDescriptor_36ff3a20cf32b258, []int{5} -} - -func (m *CombinedLimit) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *CombinedLimit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CombinedLimit.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *CombinedLimit) XXX_Merge(src proto.Message) { - xxx_messageInfo_CombinedLimit.Merge(m, src) -} - -func (m *CombinedLimit) XXX_Size() int { - return m.Size() -} - -func (m *CombinedLimit) XXX_DiscardUnknown() { - xxx_messageInfo_CombinedLimit.DiscardUnknown(m) -} - -var xxx_messageInfo_CombinedLimit proto.InternalMessageInfo - -// AllowAllMessagesFilter is a wildcard to allow any type of contract payload -// message. -// Since: wasmd 0.30 -type AllowAllMessagesFilter struct{} - -func (m *AllowAllMessagesFilter) Reset() { *m = AllowAllMessagesFilter{} } -func (m *AllowAllMessagesFilter) String() string { return proto.CompactTextString(m) } -func (*AllowAllMessagesFilter) ProtoMessage() {} -func (*AllowAllMessagesFilter) Descriptor() ([]byte, []int) { - return fileDescriptor_36ff3a20cf32b258, []int{6} -} - -func (m *AllowAllMessagesFilter) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *AllowAllMessagesFilter) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AllowAllMessagesFilter.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *AllowAllMessagesFilter) XXX_Merge(src proto.Message) { - xxx_messageInfo_AllowAllMessagesFilter.Merge(m, src) -} - -func (m *AllowAllMessagesFilter) XXX_Size() int { - return m.Size() -} - -func (m *AllowAllMessagesFilter) XXX_DiscardUnknown() { - xxx_messageInfo_AllowAllMessagesFilter.DiscardUnknown(m) -} - -var xxx_messageInfo_AllowAllMessagesFilter proto.InternalMessageInfo - -// AcceptedMessageKeysFilter accept only the specific contract message keys in -// the json object to be executed. -// Since: wasmd 0.30 -type AcceptedMessageKeysFilter struct { - // Messages is the list of unique keys - Keys []string `protobuf:"bytes,1,rep,name=keys,proto3" json:"keys,omitempty"` -} - -func (m *AcceptedMessageKeysFilter) Reset() { *m = AcceptedMessageKeysFilter{} } -func (m *AcceptedMessageKeysFilter) String() string { return proto.CompactTextString(m) } -func (*AcceptedMessageKeysFilter) ProtoMessage() {} -func (*AcceptedMessageKeysFilter) Descriptor() ([]byte, []int) { - return fileDescriptor_36ff3a20cf32b258, []int{7} -} - -func (m *AcceptedMessageKeysFilter) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *AcceptedMessageKeysFilter) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AcceptedMessageKeysFilter.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *AcceptedMessageKeysFilter) XXX_Merge(src proto.Message) { - xxx_messageInfo_AcceptedMessageKeysFilter.Merge(m, src) -} - -func (m *AcceptedMessageKeysFilter) XXX_Size() int { - return m.Size() -} - -func (m *AcceptedMessageKeysFilter) XXX_DiscardUnknown() { - xxx_messageInfo_AcceptedMessageKeysFilter.DiscardUnknown(m) -} - -var xxx_messageInfo_AcceptedMessageKeysFilter proto.InternalMessageInfo - -// AcceptedMessagesFilter accept only the specific raw contract messages to be -// executed. -// Since: wasmd 0.30 -type AcceptedMessagesFilter struct { - // Messages is the list of raw contract messages - Messages []RawContractMessage `protobuf:"bytes,1,rep,name=messages,proto3,casttype=RawContractMessage" json:"messages,omitempty"` -} - -func (m *AcceptedMessagesFilter) Reset() { *m = AcceptedMessagesFilter{} } -func (m *AcceptedMessagesFilter) String() string { return proto.CompactTextString(m) } -func (*AcceptedMessagesFilter) ProtoMessage() {} -func (*AcceptedMessagesFilter) Descriptor() ([]byte, []int) { - return fileDescriptor_36ff3a20cf32b258, []int{8} -} - -func (m *AcceptedMessagesFilter) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *AcceptedMessagesFilter) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AcceptedMessagesFilter.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *AcceptedMessagesFilter) XXX_Merge(src proto.Message) { - xxx_messageInfo_AcceptedMessagesFilter.Merge(m, src) -} - -func (m *AcceptedMessagesFilter) XXX_Size() int { - return m.Size() -} - -func (m *AcceptedMessagesFilter) XXX_DiscardUnknown() { - xxx_messageInfo_AcceptedMessagesFilter.DiscardUnknown(m) -} - -var xxx_messageInfo_AcceptedMessagesFilter proto.InternalMessageInfo - -func init() { - proto.RegisterType((*ContractExecutionAuthorization)(nil), "cosmwasm.wasm.v1.ContractExecutionAuthorization") - proto.RegisterType((*ContractMigrationAuthorization)(nil), "cosmwasm.wasm.v1.ContractMigrationAuthorization") - proto.RegisterType((*ContractGrant)(nil), "cosmwasm.wasm.v1.ContractGrant") - proto.RegisterType((*MaxCallsLimit)(nil), "cosmwasm.wasm.v1.MaxCallsLimit") - proto.RegisterType((*MaxFundsLimit)(nil), "cosmwasm.wasm.v1.MaxFundsLimit") - proto.RegisterType((*CombinedLimit)(nil), "cosmwasm.wasm.v1.CombinedLimit") - proto.RegisterType((*AllowAllMessagesFilter)(nil), "cosmwasm.wasm.v1.AllowAllMessagesFilter") - proto.RegisterType((*AcceptedMessageKeysFilter)(nil), "cosmwasm.wasm.v1.AcceptedMessageKeysFilter") - proto.RegisterType((*AcceptedMessagesFilter)(nil), "cosmwasm.wasm.v1.AcceptedMessagesFilter") -} - -func init() { proto.RegisterFile("cosmwasm/wasm/v1/authz.proto", fileDescriptor_36ff3a20cf32b258) } - -var fileDescriptor_36ff3a20cf32b258 = []byte{ - // 671 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x55, 0x4d, 0x4f, 0x13, 0x41, - 0x18, 0xee, 0x00, 0x22, 0x1d, 0xc4, 0x8f, 0x0d, 0x21, 0x05, 0xc9, 0x96, 0xac, 0x1a, 0x2b, 0x49, - 0x77, 0x53, 0x8c, 0x97, 0x5e, 0x4c, 0x4b, 0xc4, 0x18, 0xc0, 0xc3, 0xc6, 0x44, 0xe2, 0x85, 0xcc, - 0x6e, 0x87, 0x65, 0x64, 0x77, 0xa6, 0xd9, 0x99, 0xa5, 0x94, 0xc4, 0x3f, 0xe0, 0xc9, 0x9b, 0x7f, - 0xc1, 0x78, 0xe2, 0xd0, 0xa3, 0x3f, 0x80, 0x70, 0xe2, 0x68, 0x3c, 0xa0, 0x42, 0x0c, 0xff, 0xc1, - 0x93, 0xd9, 0x99, 0xd9, 0x42, 0x09, 0x34, 0xc8, 0x89, 0xcb, 0x74, 0xde, 0xf7, 0x9d, 0x79, 0x9e, - 0xe7, 0xfd, 0xd8, 0x29, 0x9c, 0xf6, 0x19, 0x8f, 0x5a, 0x88, 0x47, 0x8e, 0x5c, 0x36, 0x2b, 0x0e, - 0x4a, 0xc4, 0xfa, 0xb6, 0xdd, 0x8c, 0x99, 0x60, 0xc6, 0xdd, 0x2c, 0x6a, 0xcb, 0x65, 0xb3, 0x32, - 0x35, 0x1e, 0xb0, 0x80, 0xc9, 0xa0, 0x93, 0xee, 0xd4, 0xb9, 0xa9, 0xc9, 0xf4, 0x1c, 0xe3, 0xab, - 0x2a, 0xa0, 0x0c, 0x1d, 0x32, 0x95, 0xe5, 0x78, 0x88, 0x63, 0x67, 0xb3, 0xe2, 0x61, 0x81, 0x2a, - 0x8e, 0xcf, 0x08, 0xcd, 0xae, 0x06, 0x8c, 0x05, 0x21, 0x76, 0xa4, 0xe5, 0x25, 0x6b, 0x0e, 0xa2, - 0x6d, 0x1d, 0xba, 0x87, 0x22, 0x42, 0x99, 0x23, 0x57, 0xe5, 0xb2, 0x3a, 0x00, 0x9a, 0xf3, 0x8c, - 0x8a, 0x18, 0xf9, 0xe2, 0xc5, 0x16, 0xf6, 0x13, 0x41, 0x18, 0xad, 0x25, 0x62, 0x9d, 0xc5, 0x64, - 0x1b, 0xa5, 0x86, 0x51, 0x87, 0xc3, 0x41, 0x8c, 0xa8, 0xe0, 0x05, 0x30, 0x33, 0x58, 0x1a, 0x9d, - 0x2b, 0xda, 0x67, 0x93, 0xb0, 0x33, 0x84, 0x97, 0xe9, 0xb9, 0x7a, 0x7e, 0xf7, 0xa0, 0x98, 0xfb, - 0x72, 0xbc, 0x33, 0x0b, 0x5c, 0x7d, 0xb3, 0xfa, 0x7a, 0xaf, 0x53, 0xb6, 0x74, 0x1a, 0xaa, 0x1e, - 0x5a, 0xb9, 0xdd, 0xc3, 0xf5, 0xf1, 0x78, 0x67, 0xf6, 0x81, 0xac, 0x5b, 0x7f, 0x4d, 0x3d, 0xb2, - 0x97, 0x49, 0x10, 0xa3, 0x6b, 0x26, 0xfb, 0x7c, 0x4d, 0xd6, 0x0f, 0x00, 0xc7, 0x7a, 0x48, 0x8d, - 0x29, 0x38, 0xe2, 0x6b, 0x47, 0x01, 0xcc, 0x80, 0x52, 0xde, 0xed, 0xda, 0xc6, 0x1b, 0x78, 0x23, - 0x24, 0x11, 0x11, 0x85, 0x81, 0x19, 0x50, 0x1a, 0x9d, 0x1b, 0xb7, 0x55, 0x67, 0xed, 0xac, 0xb3, - 0x76, 0x8d, 0xb6, 0xeb, 0xa5, 0xbd, 0x4e, 0xf9, 0xe1, 0x85, 0x99, 0xa5, 0xf4, 0xdb, 0x4b, 0x29, - 0xc8, 0x8a, 0xab, 0xc0, 0x8c, 0xb7, 0x70, 0x78, 0x8d, 0x84, 0x02, 0xc7, 0x85, 0xc1, 0x3e, 0xb0, - 0x4f, 0xf6, 0x3a, 0xe5, 0x47, 0xfd, 0x61, 0x17, 0x24, 0xca, 0x8a, 0xab, 0xe1, 0x2c, 0x0a, 0xc7, - 0x96, 0xd1, 0xd6, 0x3c, 0x0a, 0x43, 0x2e, 0x19, 0x8d, 0x69, 0x98, 0x8f, 0x71, 0x84, 0x08, 0x25, - 0x34, 0x90, 0xc9, 0x0d, 0xb9, 0x27, 0x8e, 0xea, 0xf3, 0xcb, 0x0a, 0x4f, 0xab, 0x6b, 0xc8, 0xea, - 0xf6, 0xc0, 0x5b, 0xdf, 0x80, 0x24, 0x5c, 0x48, 0x68, 0x43, 0x13, 0xbe, 0x87, 0x37, 0x51, 0xc4, - 0x92, 0x93, 0x9e, 0x4f, 0xda, 0xba, 0x79, 0xe9, 0xc7, 0xd2, 0xed, 0xdd, 0x3c, 0x23, 0xb4, 0xfe, - 0x2c, 0xed, 0xf6, 0xd7, 0x9f, 0xc5, 0x52, 0x40, 0xc4, 0x7a, 0xe2, 0xd9, 0x3e, 0x8b, 0xf4, 0x77, - 0xa6, 0x7f, 0xca, 0xbc, 0xb1, 0xe1, 0x88, 0x76, 0x13, 0x73, 0x79, 0x81, 0xab, 0xc9, 0xc8, 0x08, - 0xae, 0x28, 0xff, 0x44, 0xac, 0xf5, 0x47, 0xce, 0x42, 0xe4, 0x11, 0x8a, 0x1b, 0x4a, 0xfe, 0x63, - 0x78, 0xc7, 0x4f, 0xd3, 0x5b, 0x3d, 0x5b, 0xb5, 0xdb, 0xd2, 0xed, 0x66, 0xde, 0xd3, 0x79, 0x0e, - 0x5c, 0xc3, 0x3c, 0x7b, 0xb2, 0xb2, 0x7c, 0x38, 0x51, 0x0b, 0x43, 0xd6, 0xaa, 0x85, 0xe1, 0x32, - 0xe6, 0x1c, 0x05, 0x98, 0xab, 0xc9, 0xa9, 0xbe, 0xba, 0xf4, 0x8c, 0xa5, 0xd8, 0xf7, 0x25, 0xf6, - 0xf9, 0x50, 0xd6, 0x07, 0x38, 0x59, 0xf3, 0x7d, 0xdc, 0x14, 0xb8, 0xa1, 0x23, 0x8b, 0xb8, 0xad, - 0x83, 0x86, 0x01, 0x87, 0x36, 0x70, 0x5b, 0xcd, 0x44, 0xde, 0x95, 0xfb, 0xea, 0xd2, 0x7f, 0x71, - 0x9b, 0x8a, 0xfb, 0x22, 0x06, 0xeb, 0x33, 0x80, 0x13, 0x67, 0xa2, 0x19, 0xf9, 0x1c, 0x1c, 0x89, - 0xb4, 0x47, 0x0a, 0xb8, 0x55, 0x9f, 0xf8, 0x7b, 0x50, 0x34, 0x5c, 0xd4, 0xea, 0xbe, 0x15, 0x2a, - 0xec, 0x76, 0xcf, 0x5d, 0xad, 0x30, 0xe7, 0xd2, 0xd7, 0x17, 0x77, 0x7f, 0x9b, 0xb9, 0xdd, 0x43, - 0x13, 0xec, 0x1f, 0x9a, 0xe0, 0xd7, 0xa1, 0x09, 0x3e, 0x1d, 0x99, 0xb9, 0xfd, 0x23, 0x33, 0xf7, - 0xfd, 0xc8, 0xcc, 0xbd, 0x2b, 0x9f, 0x1a, 0x0a, 0x81, 0xe3, 0x26, 0xc5, 0xa2, 0xc5, 0xe2, 0x0d, - 0xb9, 0x2f, 0xfb, 0x2c, 0xc6, 0xce, 0x96, 0xfa, 0x1b, 0x93, 0xf3, 0xe1, 0x0d, 0xcb, 0x27, 0xe2, - 0xe9, 0xbf, 0x00, 0x00, 0x00, 0xff, 0xff, 0x4e, 0xa7, 0xb1, 0x51, 0xe4, 0x06, 0x00, 0x00, -} - -func (m *ContractExecutionAuthorization) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *ContractExecutionAuthorization) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ContractExecutionAuthorization) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Grants) > 0 { - for iNdEx := len(m.Grants) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Grants[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAuthz(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *ContractMigrationAuthorization) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *ContractMigrationAuthorization) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ContractMigrationAuthorization) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Grants) > 0 { - for iNdEx := len(m.Grants) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Grants[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAuthz(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *ContractGrant) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *ContractGrant) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ContractGrant) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Filter != nil { - { - size, err := m.Filter.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAuthz(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - if m.Limit != nil { - { - size, err := m.Limit.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAuthz(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.Contract) > 0 { - i -= len(m.Contract) - copy(dAtA[i:], m.Contract) - i = encodeVarintAuthz(dAtA, i, uint64(len(m.Contract))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MaxCallsLimit) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MaxCallsLimit) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MaxCallsLimit) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Remaining != 0 { - i = encodeVarintAuthz(dAtA, i, uint64(m.Remaining)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *MaxFundsLimit) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MaxFundsLimit) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MaxFundsLimit) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Amounts) > 0 { - for iNdEx := len(m.Amounts) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amounts[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAuthz(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *CombinedLimit) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *CombinedLimit) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CombinedLimit) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Amounts) > 0 { - for iNdEx := len(m.Amounts) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amounts[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAuthz(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if m.CallsRemaining != 0 { - i = encodeVarintAuthz(dAtA, i, uint64(m.CallsRemaining)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *AllowAllMessagesFilter) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *AllowAllMessagesFilter) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AllowAllMessagesFilter) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *AcceptedMessageKeysFilter) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *AcceptedMessageKeysFilter) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AcceptedMessageKeysFilter) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Keys) > 0 { - for iNdEx := len(m.Keys) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.Keys[iNdEx]) - copy(dAtA[i:], m.Keys[iNdEx]) - i = encodeVarintAuthz(dAtA, i, uint64(len(m.Keys[iNdEx]))) - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *AcceptedMessagesFilter) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *AcceptedMessagesFilter) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AcceptedMessagesFilter) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Messages) > 0 { - for iNdEx := len(m.Messages) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.Messages[iNdEx]) - copy(dAtA[i:], m.Messages[iNdEx]) - i = encodeVarintAuthz(dAtA, i, uint64(len(m.Messages[iNdEx]))) - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func encodeVarintAuthz(dAtA []byte, offset int, v uint64) int { - offset -= sovAuthz(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} - -func (m *ContractExecutionAuthorization) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Grants) > 0 { - for _, e := range m.Grants { - l = e.Size() - n += 1 + l + sovAuthz(uint64(l)) - } - } - return n -} - -func (m *ContractMigrationAuthorization) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Grants) > 0 { - for _, e := range m.Grants { - l = e.Size() - n += 1 + l + sovAuthz(uint64(l)) - } - } - return n -} - -func (m *ContractGrant) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Contract) - if l > 0 { - n += 1 + l + sovAuthz(uint64(l)) - } - if m.Limit != nil { - l = m.Limit.Size() - n += 1 + l + sovAuthz(uint64(l)) - } - if m.Filter != nil { - l = m.Filter.Size() - n += 1 + l + sovAuthz(uint64(l)) - } - return n -} - -func (m *MaxCallsLimit) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Remaining != 0 { - n += 1 + sovAuthz(uint64(m.Remaining)) - } - return n -} - -func (m *MaxFundsLimit) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Amounts) > 0 { - for _, e := range m.Amounts { - l = e.Size() - n += 1 + l + sovAuthz(uint64(l)) - } - } - return n -} - -func (m *CombinedLimit) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.CallsRemaining != 0 { - n += 1 + sovAuthz(uint64(m.CallsRemaining)) - } - if len(m.Amounts) > 0 { - for _, e := range m.Amounts { - l = e.Size() - n += 1 + l + sovAuthz(uint64(l)) - } - } - return n -} - -func (m *AllowAllMessagesFilter) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *AcceptedMessageKeysFilter) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Keys) > 0 { - for _, s := range m.Keys { - l = len(s) - n += 1 + l + sovAuthz(uint64(l)) - } - } - return n -} - -func (m *AcceptedMessagesFilter) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Messages) > 0 { - for _, b := range m.Messages { - l = len(b) - n += 1 + l + sovAuthz(uint64(l)) - } - } - return n -} - -func sovAuthz(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} - -func sozAuthz(x uint64) (n int) { - return sovAuthz(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} - -func (m *ContractExecutionAuthorization) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuthz - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: ContractExecutionAuthorization: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ContractExecutionAuthorization: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Grants", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuthz - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuthz - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuthz - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Grants = append(m.Grants, ContractGrant{}) - if err := m.Grants[len(m.Grants)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipAuthz(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAuthz - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *ContractMigrationAuthorization) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuthz - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: ContractMigrationAuthorization: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ContractMigrationAuthorization: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Grants", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuthz - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuthz - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuthz - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Grants = append(m.Grants, ContractGrant{}) - if err := m.Grants[len(m.Grants)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipAuthz(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAuthz - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *ContractGrant) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuthz - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: ContractGrant: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ContractGrant: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Contract", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuthz - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthAuthz - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthAuthz - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Contract = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Limit", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuthz - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuthz - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuthz - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Limit == nil { - m.Limit = &types.Any{} - } - if err := m.Limit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Filter", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuthz - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuthz - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuthz - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Filter == nil { - m.Filter = &types.Any{} - } - if err := m.Filter.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipAuthz(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAuthz - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MaxCallsLimit) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuthz - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MaxCallsLimit: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MaxCallsLimit: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Remaining", wireType) - } - m.Remaining = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuthz - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Remaining |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipAuthz(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAuthz - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MaxFundsLimit) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuthz - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MaxFundsLimit: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MaxFundsLimit: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amounts", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuthz - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuthz - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuthz - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amounts = append(m.Amounts, types1.Coin{}) - if err := m.Amounts[len(m.Amounts)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipAuthz(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAuthz - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *CombinedLimit) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuthz - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CombinedLimit: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CombinedLimit: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CallsRemaining", wireType) - } - m.CallsRemaining = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuthz - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CallsRemaining |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amounts", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuthz - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuthz - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuthz - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amounts = append(m.Amounts, types1.Coin{}) - if err := m.Amounts[len(m.Amounts)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipAuthz(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAuthz - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *AllowAllMessagesFilter) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuthz - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: AllowAllMessagesFilter: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AllowAllMessagesFilter: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipAuthz(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAuthz - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *AcceptedMessageKeysFilter) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuthz - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: AcceptedMessageKeysFilter: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AcceptedMessageKeysFilter: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Keys", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuthz - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthAuthz - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthAuthz - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Keys = append(m.Keys, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipAuthz(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAuthz - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *AcceptedMessagesFilter) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuthz - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: AcceptedMessagesFilter: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AcceptedMessagesFilter: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Messages", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuthz - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthAuthz - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthAuthz - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Messages = append(m.Messages, make([]byte, postIndex-iNdEx)) - copy(m.Messages[len(m.Messages)-1], dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipAuthz(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAuthz - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func skipAuthz(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowAuthz - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowAuthz - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowAuthz - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthAuthz - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupAuthz - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthAuthz - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthAuthz = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowAuthz = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupAuthz = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/wasm/types/authz_test.go b/x/wasm/types/authz_test.go deleted file mode 100644 index 79d279b..0000000 --- a/x/wasm/types/authz_test.go +++ /dev/null @@ -1,729 +0,0 @@ -package types - -import ( - "math" - "testing" - - errorsmod "cosmossdk.io/errors" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - authztypes "github.com/cosmos/cosmos-sdk/x/authz" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestContractAuthzFilterValidate(t *testing.T) { - specs := map[string]struct { - src ContractAuthzFilterX - expErr bool - }{ - "allow all": { - src: &AllowAllMessagesFilter{}, - }, - "allow keys - single": { - src: NewAcceptedMessageKeysFilter("foo"), - }, - "allow keys - multi": { - src: NewAcceptedMessageKeysFilter("foo", "bar"), - }, - "allow keys - empty": { - src: NewAcceptedMessageKeysFilter(), - expErr: true, - }, - "allow keys - duplicates": { - src: NewAcceptedMessageKeysFilter("foo", "foo"), - expErr: true, - }, - "allow keys - whitespaces": { - src: NewAcceptedMessageKeysFilter(" foo"), - expErr: true, - }, - "allow keys - empty key": { - src: NewAcceptedMessageKeysFilter("", "bar"), - expErr: true, - }, - "allow keys - whitespace key": { - src: NewAcceptedMessageKeysFilter(" ", "bar"), - expErr: true, - }, - "allow message - single": { - src: NewAcceptedMessagesFilter([]byte(`{}`)), - }, - "allow message - multiple": { - src: NewAcceptedMessagesFilter([]byte(`{}`), []byte(`{"foo":"bar"}`)), - }, - "allow message - multiple with empty": { - src: NewAcceptedMessagesFilter([]byte(`{}`), nil), - expErr: true, - }, - "allow message - duplicate": { - src: NewAcceptedMessagesFilter([]byte(`{}`), []byte(`{}`)), - expErr: true, - }, - "allow message - non json": { - src: NewAcceptedMessagesFilter([]byte("non-json")), - expErr: true, - }, - "allow message - empty": { - src: NewAcceptedMessagesFilter(), - expErr: true, - }, - "allow all message - always valid": { - src: NewAllowAllMessagesFilter(), - }, - "undefined - always invalid": { - src: &UndefinedFilter{}, - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - gotErr := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - }) - } -} - -func TestContractAuthzFilterAccept(t *testing.T) { - specs := map[string]struct { - filter ContractAuthzFilterX - src RawContractMessage - exp bool - expGasConsumed sdk.Gas - expErr bool - }{ - "allow all - accepts json obj": { - filter: &AllowAllMessagesFilter{}, - src: []byte(`{}`), - exp: true, - }, - "allow all - accepts json array": { - filter: &AllowAllMessagesFilter{}, - src: []byte(`[{},{}]`), - exp: true, - }, - "allow all - rejects non json msg": { - filter: &AllowAllMessagesFilter{}, - src: []byte(``), - expErr: true, - }, - "allowed key - single": { - filter: NewAcceptedMessageKeysFilter("foo"), - src: []byte(`{"foo": "bar"}`), - exp: true, - expGasConsumed: sdk.Gas(len(`{"foo": "bar"}`)), - }, - "allowed key - multiple": { - filter: NewAcceptedMessageKeysFilter("foo", "other"), - src: []byte(`{"other": "value"}`), - exp: true, - expGasConsumed: sdk.Gas(len(`{"other": "value"}`)), - }, - "allowed key - non accepted key": { - filter: NewAcceptedMessageKeysFilter("foo"), - src: []byte(`{"bar": "value"}`), - exp: false, - expGasConsumed: sdk.Gas(len(`{"bar": "value"}`)), - }, - "allowed key - unsupported array msg": { - filter: NewAcceptedMessageKeysFilter("foo", "other"), - src: []byte(`[{"foo":"bar"}]`), - expErr: false, - expGasConsumed: sdk.Gas(len(`[{"foo":"bar"}]`)), - }, - "allowed key - invalid msg": { - filter: NewAcceptedMessageKeysFilter("foo", "other"), - src: []byte(`not a json msg`), - expErr: true, - }, - "allow message - single": { - filter: NewAcceptedMessagesFilter([]byte(`{}`)), - src: []byte(`{}`), - exp: true, - }, - "allow message - multiple": { - filter: NewAcceptedMessagesFilter([]byte(`[{"foo":"bar"}]`), []byte(`{"other":"value"}`)), - src: []byte(`[{"foo":"bar"}]`), - exp: true, - }, - "allow message - no match": { - filter: NewAcceptedMessagesFilter([]byte(`{"foo":"bar"}`)), - src: []byte(`{"other":"value"}`), - exp: false, - }, - "allow all message - always accept valid": { - filter: NewAllowAllMessagesFilter(), - src: []byte(`{"other":"value"}`), - exp: true, - }, - "allow all message - always reject invalid json": { - filter: NewAllowAllMessagesFilter(), - src: []byte(`not json`), - expErr: true, - }, - "undefined - always errors": { - filter: &UndefinedFilter{}, - src: []byte(`{"foo":"bar"}`), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - gm := sdk.NewGasMeter(1_000_000) - allowed, gotErr := spec.filter.Accept(sdk.Context{}.WithGasMeter(gm), spec.src) - - // then - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - assert.Equal(t, spec.exp, allowed) - assert.Equal(t, spec.expGasConsumed, gm.GasConsumed()) - }) - } -} - -func TestContractAuthzLimitValidate(t *testing.T) { - oneToken := sdk.NewCoin(sdk.DefaultBondDenom, sdk.OneInt()) - specs := map[string]struct { - src ContractAuthzLimitX - expErr bool - }{ - "max calls": { - src: NewMaxCallsLimit(1), - }, - "max calls - max uint64": { - src: NewMaxCallsLimit(math.MaxUint64), - }, - "max calls - empty": { - src: NewMaxCallsLimit(0), - expErr: true, - }, - "max funds": { - src: NewMaxFundsLimit(oneToken), - }, - "max funds - empty coins": { - src: NewMaxFundsLimit(), - expErr: true, - }, - "max funds - duplicates": { - src: &MaxFundsLimit{Amounts: sdk.Coins{oneToken, oneToken}}, - expErr: true, - }, - "max funds - contains empty value": { - src: &MaxFundsLimit{Amounts: sdk.Coins{oneToken, sdk.NewCoin("other", sdk.ZeroInt())}.Sort()}, - expErr: true, - }, - "max funds - unsorted": { - src: &MaxFundsLimit{Amounts: sdk.Coins{oneToken, sdk.NewCoin("other", sdk.OneInt())}}, - expErr: true, - }, - "combined": { - src: NewCombinedLimit(1, oneToken), - }, - "combined - empty calls": { - src: NewCombinedLimit(0, oneToken), - expErr: true, - }, - "combined - empty amounts": { - src: NewCombinedLimit(1), - expErr: true, - }, - "combined - invalid amounts": { - src: &CombinedLimit{CallsRemaining: 1, Amounts: sdk.Coins{oneToken, oneToken}}, - expErr: true, - }, - "undefined": { - src: &UndefinedLimit{}, - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - gotErr := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - }) - } -} - -func TestContractAuthzLimitAccept(t *testing.T) { - oneToken := sdk.NewCoin(sdk.DefaultBondDenom, sdk.OneInt()) - otherToken := sdk.NewCoin("other", sdk.OneInt()) - specs := map[string]struct { - limit ContractAuthzLimitX - src AuthzableWasmMsg - exp *ContractAuthzLimitAcceptResult - expErr bool - }{ - "max calls - updated": { - limit: NewMaxCallsLimit(2), - src: &MsgExecuteContract{}, - exp: &ContractAuthzLimitAcceptResult{Accepted: true, UpdateLimit: NewMaxCallsLimit(1)}, - }, - "max calls - removed": { - limit: NewMaxCallsLimit(1), - src: &MsgExecuteContract{}, - exp: &ContractAuthzLimitAcceptResult{Accepted: true, DeleteLimit: true}, - }, - "max calls - accepted with zero fund set": { - limit: NewMaxCallsLimit(1), - src: &MsgExecuteContract{Funds: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.ZeroInt()))}, - exp: &ContractAuthzLimitAcceptResult{Accepted: true, DeleteLimit: true}, - }, - "max calls - rejected with some fund transfer": { - limit: NewMaxCallsLimit(1), - src: &MsgExecuteContract{Funds: sdk.NewCoins(oneToken)}, - exp: &ContractAuthzLimitAcceptResult{Accepted: false}, - }, - "max calls - invalid": { - limit: &MaxCallsLimit{}, - src: &MsgExecuteContract{}, - expErr: true, - }, - "max funds - single updated": { - limit: NewMaxFundsLimit(oneToken.Add(oneToken)), - src: &MsgExecuteContract{Funds: sdk.NewCoins(oneToken)}, - exp: &ContractAuthzLimitAcceptResult{Accepted: true, UpdateLimit: NewMaxFundsLimit(oneToken)}, - }, - "max funds - single removed": { - limit: NewMaxFundsLimit(oneToken), - src: &MsgExecuteContract{Funds: sdk.NewCoins(oneToken)}, - exp: &ContractAuthzLimitAcceptResult{Accepted: true, DeleteLimit: true}, - }, - "max funds - single with unknown token": { - limit: NewMaxFundsLimit(oneToken), - src: &MsgExecuteContract{Funds: sdk.NewCoins(otherToken)}, - exp: &ContractAuthzLimitAcceptResult{Accepted: false}, - }, - "max funds - single exceeds limit": { - limit: NewMaxFundsLimit(oneToken), - src: &MsgExecuteContract{Funds: sdk.NewCoins(oneToken.Add(oneToken))}, - exp: &ContractAuthzLimitAcceptResult{Accepted: false}, - }, - "max funds - single with additional token send": { - limit: NewMaxFundsLimit(oneToken), - src: &MsgExecuteContract{Funds: sdk.NewCoins(oneToken, otherToken)}, - exp: &ContractAuthzLimitAcceptResult{Accepted: false}, - }, - "max funds - multi with other left": { - limit: NewMaxFundsLimit(oneToken, otherToken), - src: &MsgExecuteContract{Funds: sdk.NewCoins(oneToken)}, - exp: &ContractAuthzLimitAcceptResult{Accepted: true, UpdateLimit: NewMaxFundsLimit(otherToken)}, - }, - "max funds - multi with all used": { - limit: NewMaxFundsLimit(oneToken, otherToken), - src: &MsgExecuteContract{Funds: sdk.NewCoins(oneToken, otherToken)}, - exp: &ContractAuthzLimitAcceptResult{Accepted: true, DeleteLimit: true}, - }, - "max funds - multi with no tokens sent": { - limit: NewMaxFundsLimit(oneToken, otherToken), - src: &MsgExecuteContract{}, - exp: &ContractAuthzLimitAcceptResult{Accepted: true}, - }, - "max funds - multi with other exceeds limit": { - limit: NewMaxFundsLimit(oneToken, otherToken), - src: &MsgExecuteContract{Funds: sdk.NewCoins(oneToken, otherToken.Add(otherToken))}, - exp: &ContractAuthzLimitAcceptResult{Accepted: false}, - }, - "max combined - multi amounts one consumed": { - limit: NewCombinedLimit(2, oneToken, otherToken), - src: &MsgExecuteContract{Funds: sdk.NewCoins(oneToken)}, - exp: &ContractAuthzLimitAcceptResult{Accepted: true, UpdateLimit: NewCombinedLimit(1, otherToken)}, - }, - "max combined - multi amounts none consumed": { - limit: NewCombinedLimit(2, oneToken, otherToken), - src: &MsgExecuteContract{}, - exp: &ContractAuthzLimitAcceptResult{Accepted: true, UpdateLimit: NewCombinedLimit(1, oneToken, otherToken)}, - }, - "max combined - removed on last execution": { - limit: NewCombinedLimit(1, oneToken, otherToken), - src: &MsgExecuteContract{Funds: sdk.NewCoins(oneToken)}, - exp: &ContractAuthzLimitAcceptResult{Accepted: true, DeleteLimit: true}, - }, - "max combined - removed on last token": { - limit: NewCombinedLimit(2, oneToken), - src: &MsgExecuteContract{Funds: sdk.NewCoins(oneToken)}, - exp: &ContractAuthzLimitAcceptResult{Accepted: true, DeleteLimit: true}, - }, - "max combined - update with token and calls remaining": { - limit: NewCombinedLimit(2, oneToken, otherToken), - src: &MsgExecuteContract{Funds: sdk.NewCoins(oneToken)}, - exp: &ContractAuthzLimitAcceptResult{Accepted: true, UpdateLimit: NewCombinedLimit(1, otherToken)}, - }, - "max combined - multi with other exceeds limit": { - limit: NewCombinedLimit(2, oneToken, otherToken), - src: &MsgExecuteContract{Funds: sdk.NewCoins(oneToken, otherToken.Add(otherToken))}, - exp: &ContractAuthzLimitAcceptResult{Accepted: false}, - }, - "max combined - with unknown token": { - limit: NewCombinedLimit(2, oneToken), - src: &MsgExecuteContract{Funds: sdk.NewCoins(otherToken)}, - exp: &ContractAuthzLimitAcceptResult{Accepted: false}, - }, - "undefined": { - limit: &UndefinedLimit{}, - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - gotResult, gotErr := spec.limit.Accept(sdk.Context{}, spec.src) - // then - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - assert.Equal(t, spec.exp, gotResult) - }) - } -} - -func TestValidateContractGrant(t *testing.T) { - specs := map[string]struct { - setup func(t *testing.T) ContractGrant - expErr bool - }{ - "all good": { - setup: func(t *testing.T) ContractGrant { - return mustGrant(randBytes(ContractAddrLen), NewMaxCallsLimit(1), NewAllowAllMessagesFilter()) - }, - }, - "invalid address": { - setup: func(t *testing.T) ContractGrant { - return mustGrant([]byte{}, NewMaxCallsLimit(1), NewAllowAllMessagesFilter()) - }, - expErr: true, - }, - "invalid limit": { - setup: func(t *testing.T) ContractGrant { - return mustGrant(randBytes(ContractAddrLen), NewMaxCallsLimit(0), NewAllowAllMessagesFilter()) - }, - expErr: true, - }, - - "invalid filter ": { - setup: func(t *testing.T) ContractGrant { - return mustGrant(randBytes(ContractAddrLen), NewMaxCallsLimit(1), NewAcceptedMessageKeysFilter()) - }, - expErr: true, - }, - "empty limit": { - setup: func(t *testing.T) ContractGrant { - r := mustGrant(randBytes(ContractAddrLen), NewMaxCallsLimit(0), NewAllowAllMessagesFilter()) - r.Limit = nil - return r - }, - expErr: true, - }, - - "empty filter ": { - setup: func(t *testing.T) ContractGrant { - r := mustGrant(randBytes(ContractAddrLen), NewMaxCallsLimit(1), NewAcceptedMessageKeysFilter()) - r.Filter = nil - return r - }, - expErr: true, - }, - "wrong limit type": { - setup: func(t *testing.T) ContractGrant { - r := mustGrant(randBytes(ContractAddrLen), NewMaxCallsLimit(0), NewAllowAllMessagesFilter()) - r.Limit = r.Filter - return r - }, - expErr: true, - }, - - "wrong filter type": { - setup: func(t *testing.T) ContractGrant { - r := mustGrant(randBytes(ContractAddrLen), NewMaxCallsLimit(1), NewAcceptedMessageKeysFilter()) - r.Filter = r.Limit - return r - }, - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - gotErr := spec.setup(t).ValidateBasic() - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - }) - } -} - -func TestValidateContractAuthorization(t *testing.T) { - validGrant, err := NewContractGrant(randBytes(SDKAddrLen), NewMaxCallsLimit(1), NewAllowAllMessagesFilter()) - require.NoError(t, err) - invalidGrant, err := NewContractGrant(randBytes(SDKAddrLen), NewMaxCallsLimit(1), NewAllowAllMessagesFilter()) - require.NoError(t, err) - invalidGrant.Limit = nil - - specs := map[string]struct { - setup func(t *testing.T) validatable - expErr bool - }{ - "contract execution": { - setup: func(t *testing.T) validatable { - return NewContractMigrationAuthorization(*validGrant) - }, - }, - "contract execution - duplicate grants": { - setup: func(t *testing.T) validatable { - return NewContractMigrationAuthorization(*validGrant, *validGrant) - }, - }, - "contract execution - invalid grant": { - setup: func(t *testing.T) validatable { - return NewContractMigrationAuthorization(*validGrant, *invalidGrant) - }, - expErr: true, - }, - "contract execution - empty grants": { - setup: func(t *testing.T) validatable { - return NewContractMigrationAuthorization() - }, - expErr: true, - }, - "contract migration": { - setup: func(t *testing.T) validatable { - return NewContractMigrationAuthorization(*validGrant) - }, - }, - "contract migration - duplicate grants": { - setup: func(t *testing.T) validatable { - return NewContractMigrationAuthorization(*validGrant, *validGrant) - }, - }, - "contract migration - invalid grant": { - setup: func(t *testing.T) validatable { - return NewContractMigrationAuthorization(*validGrant, *invalidGrant) - }, - expErr: true, - }, - "contract migration - empty grant": { - setup: func(t *testing.T) validatable { - return NewContractMigrationAuthorization() - }, - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - gotErr := spec.setup(t).ValidateBasic() - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - }) - } -} - -func TestAcceptGrantedMessage(t *testing.T) { - myContractAddr := sdk.AccAddress(randBytes(SDKAddrLen)) - otherContractAddr := sdk.AccAddress(randBytes(SDKAddrLen)) - specs := map[string]struct { - auth authztypes.Authorization - msg sdk.Msg - expResult authztypes.AcceptResponse - expErr *errorsmod.Error - }{ - "accepted and updated - contract execution": { - auth: NewContractExecutionAuthorization(mustGrant(myContractAddr, NewMaxCallsLimit(2), NewAllowAllMessagesFilter())), - msg: &MsgExecuteContract{ - Sender: sdk.AccAddress(randBytes(SDKAddrLen)).String(), - Contract: myContractAddr.String(), - Msg: []byte(`{"foo":"bar"}`), - }, - expResult: authztypes.AcceptResponse{ - Accept: true, - Updated: NewContractExecutionAuthorization(mustGrant(myContractAddr, NewMaxCallsLimit(1), NewAllowAllMessagesFilter())), - }, - }, - "accepted and not updated - limit not touched": { - auth: NewContractExecutionAuthorization(mustGrant(myContractAddr, NewMaxFundsLimit(sdk.NewCoin(sdk.DefaultBondDenom, sdk.OneInt())), NewAllowAllMessagesFilter())), - msg: &MsgExecuteContract{ - Sender: sdk.AccAddress(randBytes(SDKAddrLen)).String(), - Contract: myContractAddr.String(), - Msg: []byte(`{"foo":"bar"}`), - }, - expResult: authztypes.AcceptResponse{Accept: true}, - }, - "accepted and removed - single": { - auth: NewContractExecutionAuthorization(mustGrant(myContractAddr, NewMaxCallsLimit(1), NewAllowAllMessagesFilter())), - msg: &MsgExecuteContract{ - Sender: sdk.AccAddress(randBytes(SDKAddrLen)).String(), - Contract: myContractAddr.String(), - Msg: []byte(`{"foo":"bar"}`), - }, - expResult: authztypes.AcceptResponse{Accept: true, Delete: true}, - }, - "accepted and updated - multi, one removed": { - auth: NewContractExecutionAuthorization( - mustGrant(myContractAddr, NewMaxCallsLimit(1), NewAllowAllMessagesFilter()), - mustGrant(myContractAddr, NewMaxCallsLimit(1), NewAllowAllMessagesFilter()), - ), - msg: &MsgExecuteContract{ - Sender: sdk.AccAddress(randBytes(SDKAddrLen)).String(), - Contract: myContractAddr.String(), - Msg: []byte(`{"foo":"bar"}`), - }, - expResult: authztypes.AcceptResponse{ - Accept: true, - Updated: NewContractExecutionAuthorization(mustGrant(myContractAddr, NewMaxCallsLimit(1), NewAllowAllMessagesFilter())), - }, - }, - "accepted and updated - multi, one updated": { - auth: NewContractExecutionAuthorization( - mustGrant(otherContractAddr, NewMaxCallsLimit(1), NewAllowAllMessagesFilter()), - mustGrant(myContractAddr, NewMaxFundsLimit(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(2))), NewAcceptedMessageKeysFilter("bar")), - mustGrant(myContractAddr, NewCombinedLimit(2, sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(2))), NewAcceptedMessageKeysFilter("foo")), - ), - msg: &MsgExecuteContract{ - Sender: sdk.AccAddress(randBytes(SDKAddrLen)).String(), - Contract: myContractAddr.String(), - Msg: []byte(`{"foo":"bar"}`), - Funds: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.OneInt())), - }, - expResult: authztypes.AcceptResponse{ - Accept: true, - Updated: NewContractExecutionAuthorization( - mustGrant(otherContractAddr, NewMaxCallsLimit(1), NewAllowAllMessagesFilter()), - mustGrant(myContractAddr, NewMaxFundsLimit(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(2))), NewAcceptedMessageKeysFilter("bar")), - mustGrant(myContractAddr, NewCombinedLimit(1, sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))), NewAcceptedMessageKeysFilter("foo")), - ), - }, - }, - "not accepted - no matching contract address": { - auth: NewContractExecutionAuthorization(mustGrant(myContractAddr, NewMaxCallsLimit(1), NewAllowAllMessagesFilter())), - msg: &MsgExecuteContract{ - Sender: sdk.AccAddress(randBytes(SDKAddrLen)).String(), - Contract: sdk.AccAddress(randBytes(SDKAddrLen)).String(), - Msg: []byte(`{"foo":"bar"}`), - }, - expResult: authztypes.AcceptResponse{Accept: false}, - }, - "not accepted - max calls but tokens": { - auth: NewContractExecutionAuthorization(mustGrant(myContractAddr, NewMaxCallsLimit(1), NewAllowAllMessagesFilter())), - msg: &MsgExecuteContract{ - Sender: sdk.AccAddress(randBytes(SDKAddrLen)).String(), - Contract: myContractAddr.String(), - Msg: []byte(`{"foo":"bar"}`), - Funds: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.OneInt())), - }, - expResult: authztypes.AcceptResponse{Accept: false}, - }, - "not accepted - funds exceeds limit": { - auth: NewContractExecutionAuthorization(mustGrant(myContractAddr, NewMaxFundsLimit(sdk.NewCoin(sdk.DefaultBondDenom, sdk.OneInt())), NewAllowAllMessagesFilter())), - msg: &MsgExecuteContract{ - Sender: sdk.AccAddress(randBytes(SDKAddrLen)).String(), - Contract: myContractAddr.String(), - Msg: []byte(`{"foo":"bar"}`), - Funds: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(2))), - }, - expResult: authztypes.AcceptResponse{Accept: false}, - }, - "not accepted - no matching filter": { - auth: NewContractExecutionAuthorization(mustGrant(myContractAddr, NewMaxCallsLimit(1), NewAcceptedMessageKeysFilter("other"))), - msg: &MsgExecuteContract{ - Sender: sdk.AccAddress(randBytes(SDKAddrLen)).String(), - Contract: myContractAddr.String(), - Msg: []byte(`{"foo":"bar"}`), - Funds: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.OneInt())), - }, - expResult: authztypes.AcceptResponse{Accept: false}, - }, - "invalid msg type - contract execution": { - auth: NewContractExecutionAuthorization(mustGrant(myContractAddr, NewMaxCallsLimit(1), NewAllowAllMessagesFilter())), - msg: &MsgMigrateContract{ - Sender: sdk.AccAddress(randBytes(SDKAddrLen)).String(), - Contract: myContractAddr.String(), - CodeID: 1, - Msg: []byte(`{"foo":"bar"}`), - }, - expErr: sdkerrors.ErrInvalidType, - }, - "payload is empty": { - auth: NewContractExecutionAuthorization(mustGrant(myContractAddr, NewMaxCallsLimit(1), NewAllowAllMessagesFilter())), - msg: &MsgExecuteContract{ - Sender: sdk.AccAddress(randBytes(SDKAddrLen)).String(), - Contract: myContractAddr.String(), - }, - expErr: sdkerrors.ErrInvalidType, - }, - "payload is invalid": { - auth: NewContractExecutionAuthorization(mustGrant(myContractAddr, NewMaxCallsLimit(1), NewAllowAllMessagesFilter())), - msg: &MsgExecuteContract{ - Sender: sdk.AccAddress(randBytes(SDKAddrLen)).String(), - Contract: myContractAddr.String(), - Msg: []byte(`not json`), - }, - expErr: ErrInvalid, - }, - "invalid grant": { - auth: NewContractExecutionAuthorization(ContractGrant{Contract: myContractAddr.String()}), - msg: &MsgExecuteContract{ - Sender: sdk.AccAddress(randBytes(SDKAddrLen)).String(), - Contract: myContractAddr.String(), - Msg: []byte(`{"foo":"bar"}`), - }, - expErr: sdkerrors.ErrNotFound, - }, - "invalid msg type - contract migration": { - auth: NewContractMigrationAuthorization(mustGrant(myContractAddr, NewMaxCallsLimit(1), NewAllowAllMessagesFilter())), - msg: &MsgExecuteContract{ - Sender: sdk.AccAddress(randBytes(SDKAddrLen)).String(), - Contract: myContractAddr.String(), - Msg: []byte(`{"foo":"bar"}`), - }, - expErr: sdkerrors.ErrInvalidType, - }, - "accepted and updated - contract migration": { - auth: NewContractMigrationAuthorization(mustGrant(myContractAddr, NewMaxCallsLimit(2), NewAllowAllMessagesFilter())), - msg: &MsgMigrateContract{ - Sender: sdk.AccAddress(randBytes(SDKAddrLen)).String(), - Contract: myContractAddr.String(), - CodeID: 1, - Msg: []byte(`{"foo":"bar"}`), - }, - expResult: authztypes.AcceptResponse{ - Accept: true, - Updated: NewContractMigrationAuthorization(mustGrant(myContractAddr, NewMaxCallsLimit(1), NewAllowAllMessagesFilter())), - }, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - ctx := sdk.Context{}.WithGasMeter(sdk.NewInfiniteGasMeter()) - gotResult, gotErr := spec.auth.Accept(ctx, spec.msg) - if spec.expErr != nil { - require.ErrorIs(t, gotErr, spec.expErr) - return - } - require.NoError(t, gotErr) - assert.Equal(t, spec.expResult, gotResult) - }) - } -} - -func mustGrant(contract sdk.AccAddress, limit ContractAuthzLimitX, filter ContractAuthzFilterX) ContractGrant { - g, err := NewContractGrant(contract, limit, filter) - if err != nil { - panic(err) - } - return *g -} diff --git a/x/wasm/types/codec.go b/x/wasm/types/codec.go deleted file mode 100644 index 10ff3af..0000000 --- a/x/wasm/types/codec.go +++ /dev/null @@ -1,141 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/msgservice" - "github.com/cosmos/cosmos-sdk/x/authz" - authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" - govcodec "github.com/cosmos/cosmos-sdk/x/gov/codec" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - groupcodec "github.com/cosmos/cosmos-sdk/x/group/codec" -) - -// RegisterLegacyAminoCodec registers the account types and interface -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - cdc.RegisterConcrete(&MsgStoreCode{}, "wasm/MsgStoreCode", nil) - cdc.RegisterConcrete(&MsgInstantiateContract{}, "wasm/MsgInstantiateContract", nil) - cdc.RegisterConcrete(&MsgInstantiateContract2{}, "wasm/MsgInstantiateContract2", nil) - cdc.RegisterConcrete(&MsgExecuteContract{}, "wasm/MsgExecuteContract", nil) - cdc.RegisterConcrete(&MsgMigrateContract{}, "wasm/MsgMigrateContract", nil) - cdc.RegisterConcrete(&MsgUpdateAdmin{}, "wasm/MsgUpdateAdmin", nil) - cdc.RegisterConcrete(&MsgClearAdmin{}, "wasm/MsgClearAdmin", nil) - cdc.RegisterConcrete(&MsgUpdateInstantiateConfig{}, "wasm/MsgUpdateInstantiateConfig", nil) - cdc.RegisterConcrete(&MsgUpdateParams{}, "wasm/MsgUpdateParams", nil) - cdc.RegisterConcrete(&MsgSudoContract{}, "wasm/MsgSudoContract", nil) - cdc.RegisterConcrete(&MsgPinCodes{}, "wasm/MsgPinCodes", nil) - cdc.RegisterConcrete(&MsgUnpinCodes{}, "wasm/MsgUnpinCodes", nil) - cdc.RegisterConcrete(&MsgStoreAndInstantiateContract{}, "wasm/MsgStoreAndInstantiateContract", nil) - - cdc.RegisterConcrete(&PinCodesProposal{}, "wasm/PinCodesProposal", nil) - cdc.RegisterConcrete(&UnpinCodesProposal{}, "wasm/UnpinCodesProposal", nil) - cdc.RegisterConcrete(&StoreCodeProposal{}, "wasm/StoreCodeProposal", nil) - cdc.RegisterConcrete(&InstantiateContractProposal{}, "wasm/InstantiateContractProposal", nil) - cdc.RegisterConcrete(&InstantiateContract2Proposal{}, "wasm/InstantiateContract2Proposal", nil) - cdc.RegisterConcrete(&MigrateContractProposal{}, "wasm/MigrateContractProposal", nil) - cdc.RegisterConcrete(&SudoContractProposal{}, "wasm/SudoContractProposal", nil) - cdc.RegisterConcrete(&ExecuteContractProposal{}, "wasm/ExecuteContractProposal", nil) - cdc.RegisterConcrete(&UpdateAdminProposal{}, "wasm/UpdateAdminProposal", nil) - cdc.RegisterConcrete(&ClearAdminProposal{}, "wasm/ClearAdminProposal", nil) - cdc.RegisterConcrete(&UpdateInstantiateConfigProposal{}, "wasm/UpdateInstantiateConfigProposal", nil) - cdc.RegisterConcrete(&StoreAndInstantiateContractProposal{}, "wasm/StoreAndInstantiateContractProposal", nil) - - cdc.RegisterInterface((*ContractInfoExtension)(nil), nil) - - cdc.RegisterInterface((*ContractAuthzFilterX)(nil), nil) - cdc.RegisterConcrete(&AllowAllMessagesFilter{}, "wasm/AllowAllMessagesFilter", nil) - cdc.RegisterConcrete(&AcceptedMessageKeysFilter{}, "wasm/AcceptedMessageKeysFilter", nil) - cdc.RegisterConcrete(&AcceptedMessagesFilter{}, "wasm/AcceptedMessagesFilter", nil) - - cdc.RegisterInterface((*ContractAuthzLimitX)(nil), nil) - cdc.RegisterConcrete(&MaxCallsLimit{}, "wasm/MaxCallsLimit", nil) - cdc.RegisterConcrete(&MaxFundsLimit{}, "wasm/MaxFundsLimit", nil) - cdc.RegisterConcrete(&CombinedLimit{}, "wasm/CombinedLimit", nil) - - cdc.RegisterConcrete(&ContractExecutionAuthorization{}, "wasm/ContractExecutionAuthorization", nil) - cdc.RegisterConcrete(&ContractMigrationAuthorization{}, "wasm/ContractMigrationAuthorization", nil) -} - -func RegisterInterfaces(registry types.InterfaceRegistry) { - registry.RegisterImplementations( - (*sdk.Msg)(nil), - &MsgStoreCode{}, - &MsgInstantiateContract{}, - &MsgInstantiateContract2{}, - &MsgExecuteContract{}, - &MsgMigrateContract{}, - &MsgUpdateAdmin{}, - &MsgClearAdmin{}, - &MsgIBCCloseChannel{}, - &MsgIBCSend{}, - &MsgUpdateInstantiateConfig{}, - &MsgUpdateParams{}, - &MsgSudoContract{}, - &MsgPinCodes{}, - &MsgUnpinCodes{}, - &MsgStoreAndInstantiateContract{}, - ) - registry.RegisterImplementations( - (*v1beta1.Content)(nil), - &StoreCodeProposal{}, - &InstantiateContractProposal{}, - &InstantiateContract2Proposal{}, - &MigrateContractProposal{}, - &SudoContractProposal{}, - &ExecuteContractProposal{}, - &UpdateAdminProposal{}, - &ClearAdminProposal{}, - &PinCodesProposal{}, - &UnpinCodesProposal{}, - &UpdateInstantiateConfigProposal{}, - &StoreAndInstantiateContractProposal{}, - ) - - registry.RegisterInterface("cosmwasm.wasm.v1.ContractInfoExtension", (*ContractInfoExtension)(nil)) - - registry.RegisterInterface("cosmwasm.wasm.v1.ContractAuthzFilterX", (*ContractAuthzFilterX)(nil)) - registry.RegisterImplementations( - (*ContractAuthzFilterX)(nil), - &AllowAllMessagesFilter{}, - &AcceptedMessageKeysFilter{}, - &AcceptedMessagesFilter{}, - ) - - registry.RegisterInterface("cosmwasm.wasm.v1.ContractAuthzLimitX", (*ContractAuthzLimitX)(nil)) - registry.RegisterImplementations( - (*ContractAuthzLimitX)(nil), - &MaxCallsLimit{}, - &MaxFundsLimit{}, - &CombinedLimit{}, - ) - - registry.RegisterImplementations( - (*authz.Authorization)(nil), - &ContractExecutionAuthorization{}, - &ContractMigrationAuthorization{}, - ) - - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) -} - -var ( - amino = codec.NewLegacyAmino() - - // ModuleCdc references the global x/wasm module codec. - - ModuleCdc = codec.NewAminoCodec(amino) -) - -func init() { - RegisterLegacyAminoCodec(amino) - cryptocodec.RegisterCrypto(amino) - amino.Seal() - - // Register all Amino interfaces and concrete types on the authz and gov Amino codec so that this can later be - // used to properly serialize MsgGrant, MsgExec and MsgSubmitProposal instances - RegisterLegacyAminoCodec(authzcodec.Amino) - RegisterLegacyAminoCodec(govcodec.Amino) - RegisterLegacyAminoCodec(groupcodec.Amino) -} diff --git a/x/wasm/types/errors.go b/x/wasm/types/errors.go deleted file mode 100644 index 378c25d..0000000 --- a/x/wasm/types/errors.go +++ /dev/null @@ -1,150 +0,0 @@ -package types - -import ( - errorsmod "cosmossdk.io/errors" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" -) - -// Codes for wasm contract errors -var ( - DefaultCodespace = ModuleName - - // Note: never use code 1 for any errors - that is reserved for ErrInternal in the core cosmos sdk - - // ErrCreateFailed error for wasm code that has already been uploaded or failed - ErrCreateFailed = errorsmod.Register(DefaultCodespace, 2, "create wasm contract failed") - - // ErrAccountExists error for a contract account that already exists - ErrAccountExists = errorsmod.Register(DefaultCodespace, 3, "contract account already exists") - - // ErrInstantiateFailed error for rust instantiate contract failure - ErrInstantiateFailed = errorsmod.Register(DefaultCodespace, 4, "instantiate wasm contract failed") - - // ErrExecuteFailed error for rust execution contract failure - ErrExecuteFailed = errorsmod.Register(DefaultCodespace, 5, "execute wasm contract failed") - - // ErrGasLimit error for out of gas - ErrGasLimit = errorsmod.Register(DefaultCodespace, 6, "insufficient gas") - - // ErrInvalidGenesis error for invalid genesis file syntax - ErrInvalidGenesis = errorsmod.Register(DefaultCodespace, 7, "invalid genesis") - - // ErrNotFound error for an entry not found in the store - ErrNotFound = errorsmod.Register(DefaultCodespace, 8, "not found") - - // ErrQueryFailed error for rust smart query contract failure - ErrQueryFailed = errorsmod.Register(DefaultCodespace, 9, "query wasm contract failed") - - // ErrInvalidMsg error when we cannot process the error returned from the contract - ErrInvalidMsg = errorsmod.Register(DefaultCodespace, 10, "invalid CosmosMsg from the contract") - - // ErrMigrationFailed error for rust execution contract failure - ErrMigrationFailed = errorsmod.Register(DefaultCodespace, 11, "migrate wasm contract failed") - - // ErrEmpty error for empty content - ErrEmpty = errorsmod.Register(DefaultCodespace, 12, "empty") - - // ErrLimit error for content that exceeds a limit - ErrLimit = errorsmod.Register(DefaultCodespace, 13, "exceeds limit") - - // ErrInvalid error for content that is invalid in this context - ErrInvalid = errorsmod.Register(DefaultCodespace, 14, "invalid") - - // ErrDuplicate error for content that exists - ErrDuplicate = errorsmod.Register(DefaultCodespace, 15, "duplicate") - - // ErrMaxIBCChannels error for maximum number of ibc channels reached - ErrMaxIBCChannels = errorsmod.Register(DefaultCodespace, 16, "max transfer channels") - - // ErrUnsupportedForContract error when a capability is used that is not supported for/ by this contract - ErrUnsupportedForContract = errorsmod.Register(DefaultCodespace, 17, "unsupported for this contract") - - // ErrPinContractFailed error for pinning contract failures - ErrPinContractFailed = errorsmod.Register(DefaultCodespace, 18, "pinning contract failed") - - // ErrUnpinContractFailed error for unpinning contract failures - ErrUnpinContractFailed = errorsmod.Register(DefaultCodespace, 19, "unpinning contract failed") - - // ErrUnknownMsg error by a message handler to show that it is not responsible for this message type - ErrUnknownMsg = errorsmod.Register(DefaultCodespace, 20, "unknown message from the contract") - - // ErrInvalidEvent error if an attribute/event from the contract is invalid - ErrInvalidEvent = errorsmod.Register(DefaultCodespace, 21, "invalid event") - - // ErrNoSuchContractFn error factory for an error when an address does not belong to a contract - ErrNoSuchContractFn = WasmVMFlavouredErrorFactory(errorsmod.Register(DefaultCodespace, 22, "no such contract"), - func(addr string) error { return wasmvmtypes.NoSuchContract{Addr: addr} }, - ) - - // code 23 -26 were used for json parser - - // ErrExceedMaxQueryStackSize error if max query stack size is exceeded - ErrExceedMaxQueryStackSize = errorsmod.Register(DefaultCodespace, 27, "max query stack size exceeded") - - // ErrNoSuchCodeFn factory for an error when a code id does not belong to a code info - ErrNoSuchCodeFn = WasmVMFlavouredErrorFactory(errorsmod.Register(DefaultCodespace, 28, "no such code"), - func(id uint64) error { return wasmvmtypes.NoSuchCode{CodeID: id} }, - ) -) - -// WasmVMErrorable mapped error type in wasmvm and are not redacted -type WasmVMErrorable interface { - // ToWasmVMError convert instance to wasmvm friendly error if possible otherwise root cause. never nil - ToWasmVMError() error -} - -var _ WasmVMErrorable = WasmVMFlavouredError{} - -// WasmVMFlavouredError wrapper for sdk error that supports wasmvm error types -type WasmVMFlavouredError struct { - sdkErr *errorsmod.Error - wasmVMErr error -} - -// NewWasmVMFlavouredError constructor -func NewWasmVMFlavouredError(sdkErr *errorsmod.Error, wasmVMErr error) WasmVMFlavouredError { - return WasmVMFlavouredError{sdkErr: sdkErr, wasmVMErr: wasmVMErr} -} - -// WasmVMFlavouredErrorFactory is a factory method to build a WasmVMFlavouredError type -func WasmVMFlavouredErrorFactory[T any](sdkErr *errorsmod.Error, wasmVMErrBuilder func(T) error) func(T) WasmVMFlavouredError { - if wasmVMErrBuilder == nil { - panic("builder function required") - } - return func(d T) WasmVMFlavouredError { - return WasmVMFlavouredError{sdkErr: sdkErr, wasmVMErr: wasmVMErrBuilder(d)} - } -} - -// ToWasmVMError implements WasmVMError-able -func (e WasmVMFlavouredError) ToWasmVMError() error { - if e.wasmVMErr != nil { - return e.wasmVMErr - } - return e.sdkErr -} - -// implements stdlib error -func (e WasmVMFlavouredError) Error() string { - return e.sdkErr.Error() -} - -// Unwrap implements the built-in errors.Unwrap -func (e WasmVMFlavouredError) Unwrap() error { - return e.sdkErr -} - -// Cause is the same as unwrap but used by errors.abci -func (e WasmVMFlavouredError) Cause() error { - return e.Unwrap() -} - -// Wrap extends this error with additional information. -// It's a handy function to call Wrap with sdk errors. -func (e WasmVMFlavouredError) Wrap(desc string) error { return errorsmod.Wrap(e, desc) } - -// Wrapf extends this error with additional information. -// It's a handy function to call Wrapf with sdk errors. -func (e WasmVMFlavouredError) Wrapf(desc string, args ...interface{}) error { - return errorsmod.Wrapf(e, desc, args...) -} diff --git a/x/wasm/types/errors_test.go b/x/wasm/types/errors_test.go deleted file mode 100644 index 495f5e8..0000000 --- a/x/wasm/types/errors_test.go +++ /dev/null @@ -1,86 +0,0 @@ -package types - -import ( - "errors" - "testing" - - errorsmod "cosmossdk.io/errors" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestWasmVMFlavouredError(t *testing.T) { - myErr := ErrNoSuchCodeFn(1) - specs := map[string]struct { - exec func(t *testing.T) - }{ - "IsOf": { - exec: func(t *testing.T) { - assert.True(t, errorsmod.IsOf(myErr, myErr.sdkErr)) - assert.Equal(t, myErr.sdkErr, myErr.Unwrap()) - }, - }, - "unwrapped": { - exec: func(t *testing.T) { - assert.Equal(t, myErr.sdkErr, myErr.Unwrap()) - }, - }, - "caused": { - exec: func(t *testing.T) { - assert.Equal(t, myErr.sdkErr, myErr.Cause()) - }, - }, - "wrapped supports WasmVMErrorable": { - exec: func(t *testing.T) { - var wasmvmErr WasmVMErrorable - require.True(t, errors.As(myErr.Wrap("my description"), &wasmvmErr)) - gotErr := wasmvmErr.ToWasmVMError() - assert.Equal(t, wasmvmtypes.NoSuchCode{CodeID: 1}, gotErr) - }, - }, - "wrappedf supports WasmVMErrorable": { - exec: func(t *testing.T) { - var wasmvmErr WasmVMErrorable - require.True(t, errors.As(myErr.Wrapf("my description: %d", 1), &wasmvmErr)) - gotErr := wasmvmErr.ToWasmVMError() - assert.Equal(t, wasmvmtypes.NoSuchCode{CodeID: 1}, gotErr) - }, - }, - "supports WasmVMErrorable": { - exec: func(t *testing.T) { - var wasmvmErr WasmVMErrorable - require.True(t, errors.As(myErr, &wasmvmErr)) - gotErr := wasmvmErr.ToWasmVMError() - assert.Equal(t, wasmvmtypes.NoSuchCode{CodeID: 1}, gotErr) - }, - }, - "fallback to sdk error when wasmvm error unset": { - exec: func(t *testing.T) { - var wasmvmErr WasmVMErrorable - require.True(t, errors.As(WasmVMFlavouredError{sdkErr: ErrEmpty}, &wasmvmErr)) - gotErr := wasmvmErr.ToWasmVMError() - assert.Equal(t, ErrEmpty, gotErr) - }, - }, - "abci info": { - exec: func(t *testing.T) { - codespace, code, log := errorsmod.ABCIInfo(myErr, false) - assert.Equal(t, DefaultCodespace, codespace) - assert.Equal(t, uint32(28), code) - assert.Equal(t, "no such code", log) - }, - }, - "abci info - wrapped": { - exec: func(t *testing.T) { - codespace, code, log := errorsmod.ABCIInfo(myErr.Wrap("my description"), false) - assert.Equal(t, DefaultCodespace, codespace) - assert.Equal(t, uint32(28), code) - assert.Equal(t, "my description: no such code", log) - }, - }, - } - for name, spec := range specs { - t.Run(name, spec.exec) - } -} diff --git a/x/wasm/types/events.go b/x/wasm/types/events.go deleted file mode 100644 index 442c3ed..0000000 --- a/x/wasm/types/events.go +++ /dev/null @@ -1,34 +0,0 @@ -package types - -const ( - // WasmModuleEventType is stored with any contract TX that returns non empty EventAttributes - WasmModuleEventType = "wasm" - // CustomContractEventPrefix contracts can create custom events. To not mix them with other system events they got the `wasm-` prefix. - CustomContractEventPrefix = "wasm-" - - EventTypeStoreCode = "store_code" - EventTypeInstantiate = "instantiate" - EventTypeExecute = "execute" - EventTypeMigrate = "migrate" - EventTypePinCode = "pin_code" - EventTypeUnpinCode = "unpin_code" - EventTypeSudo = "sudo" - EventTypeReply = "reply" - EventTypeGovContractResult = "gov_contract_result" - EventTypeUpdateContractAdmin = "update_contract_admin" - EventTypeUpdateCodeAccessConfig = "update_code_access_config" -) - -// event attributes returned from contract execution -const ( - AttributeReservedPrefix = "_" - - AttributeKeyContractAddr = "_contract_address" - AttributeKeyCodeID = "code_id" - AttributeKeyChecksum = "code_checksum" - AttributeKeyResultDataHex = "result" - AttributeKeyRequiredCapability = "required_capability" - AttributeKeyNewAdmin = "new_admin_address" - AttributeKeyCodePermission = "code_permission" - AttributeKeyAuthorizedAddresses = "authorized_addresses" -) diff --git a/x/wasm/types/expected_keepers.go b/x/wasm/types/expected_keepers.go deleted file mode 100644 index e9b5227..0000000 --- a/x/wasm/types/expected_keepers.go +++ /dev/null @@ -1,118 +0,0 @@ -package types - -import ( - "context" - - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" - distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" - connectiontypes "github.com/cosmos/ibc-go/v7/modules/core/03-connection/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - ibcexported "github.com/cosmos/ibc-go/v7/modules/core/exported" -) - -// BankViewKeeper defines a subset of methods implemented by the cosmos-sdk bank keeper -type BankViewKeeper interface { - GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin - GetSupply(ctx sdk.Context, denom string) sdk.Coin -} - -// Burner is a subset of the sdk bank keeper methods -type Burner interface { - BurnCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error - SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error -} - -// BankKeeper defines a subset of methods implemented by the cosmos-sdk bank keeper -type BankKeeper interface { - BankViewKeeper - Burner - IsSendEnabledCoins(ctx sdk.Context, coins ...sdk.Coin) error - BlockedAddr(addr sdk.AccAddress) bool - SendCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) error -} - -// AccountKeeper defines a subset of methods implemented by the cosmos-sdk account keeper -type AccountKeeper interface { - // Return a new account with the next account number and the specified address. Does not save the new account to the store. - NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddress) authtypes.AccountI - // Retrieve an account from the store. - GetAccount(ctx sdk.Context, addr sdk.AccAddress) authtypes.AccountI - // Set an account in the store. - SetAccount(ctx sdk.Context, acc authtypes.AccountI) -} - -// DistributionKeeper defines a subset of methods implemented by the cosmos-sdk distribution keeper -type DistributionKeeper interface { - DelegationRewards(c context.Context, req *distrtypes.QueryDelegationRewardsRequest) (*distrtypes.QueryDelegationRewardsResponse, error) -} - -// StakingKeeper defines a subset of methods implemented by the cosmos-sdk staking keeper -type StakingKeeper interface { - // BondDenom - Bondable coin denomination - BondDenom(ctx sdk.Context) (res string) - // GetValidator get a single validator - GetValidator(ctx sdk.Context, addr sdk.ValAddress) (validator stakingtypes.Validator, found bool) - // GetBondedValidatorsByPower get the current group of bonded validators sorted by power-rank - GetBondedValidatorsByPower(ctx sdk.Context) []stakingtypes.Validator - // GetAllDelegatorDelegations return all delegations for a delegator - GetAllDelegatorDelegations(ctx sdk.Context, delegator sdk.AccAddress) []stakingtypes.Delegation - // GetDelegation return a specific delegation - GetDelegation(ctx sdk.Context, - delAddr sdk.AccAddress, valAddr sdk.ValAddress) (delegation stakingtypes.Delegation, found bool) - // HasReceivingRedelegation check if validator is receiving a redelegation - HasReceivingRedelegation(ctx sdk.Context, - delAddr sdk.AccAddress, valDstAddr sdk.ValAddress) bool -} - -// ChannelKeeper defines the expected IBC channel keeper -type ChannelKeeper interface { - GetChannel(ctx sdk.Context, srcPort, srcChan string) (channel channeltypes.Channel, found bool) - - // SendPacket is called by a module in order to send an IBC packet on a channel. - // The packet sequence generated for the packet to be sent is returned. An error - // is returned if one occurs. - SendPacket( - ctx sdk.Context, - channelCap *capabilitytypes.Capability, - sourcePort string, - sourceChannel string, - timeoutHeight clienttypes.Height, - timeoutTimestamp uint64, - data []byte, - ) (uint64, error) - ChanCloseInit(ctx sdk.Context, portID, channelID string, chanCap *capabilitytypes.Capability) error - GetAllChannels(ctx sdk.Context) (channels []channeltypes.IdentifiedChannel) - IterateChannels(ctx sdk.Context, cb func(channeltypes.IdentifiedChannel) bool) - SetChannel(ctx sdk.Context, portID, channelID string, channel channeltypes.Channel) -} - -// ClientKeeper defines the expected IBC client keeper -type ClientKeeper interface { - GetClientConsensusState(ctx sdk.Context, clientID string) (connection ibcexported.ConsensusState, found bool) -} - -// ConnectionKeeper defines the expected IBC connection keeper -type ConnectionKeeper interface { - GetConnection(ctx sdk.Context, connectionID string) (connection connectiontypes.ConnectionEnd, found bool) -} - -// PortKeeper defines the expected IBC port keeper -type PortKeeper interface { - BindPort(ctx sdk.Context, portID string) *capabilitytypes.Capability -} - -type CapabilityKeeper interface { - GetCapability(ctx sdk.Context, name string) (*capabilitytypes.Capability, bool) - ClaimCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) error - AuthenticateCapability(ctx sdk.Context, capability *capabilitytypes.Capability, name string) bool -} - -// ICS20TransferPortSource is a subset of the ibc transfer keeper. -type ICS20TransferPortSource interface { - GetPort(ctx sdk.Context) string -} diff --git a/x/wasm/types/exported_keepers.go b/x/wasm/types/exported_keepers.go deleted file mode 100644 index dcf97cb..0000000 --- a/x/wasm/types/exported_keepers.go +++ /dev/null @@ -1,119 +0,0 @@ -package types - -import ( - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - sdk "github.com/cosmos/cosmos-sdk/types" - capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" -) - -// ViewKeeper provides read only operations -type ViewKeeper interface { - GetContractHistory(ctx sdk.Context, contractAddr sdk.AccAddress) []ContractCodeHistoryEntry - QuerySmart(ctx sdk.Context, contractAddr sdk.AccAddress, req []byte) ([]byte, error) - QueryRaw(ctx sdk.Context, contractAddress sdk.AccAddress, key []byte) []byte - HasContractInfo(ctx sdk.Context, contractAddress sdk.AccAddress) bool - GetContractInfo(ctx sdk.Context, contractAddress sdk.AccAddress) *ContractInfo - IterateContractInfo(ctx sdk.Context, cb func(sdk.AccAddress, ContractInfo) bool) - IterateContractsByCreator(ctx sdk.Context, creator sdk.AccAddress, cb func(address sdk.AccAddress) bool) - IterateContractsByCode(ctx sdk.Context, codeID uint64, cb func(address sdk.AccAddress) bool) - IterateContractState(ctx sdk.Context, contractAddress sdk.AccAddress, cb func(key, value []byte) bool) - GetCodeInfo(ctx sdk.Context, codeID uint64) *CodeInfo - IterateCodeInfos(ctx sdk.Context, cb func(uint64, CodeInfo) bool) - GetByteCode(ctx sdk.Context, codeID uint64) ([]byte, error) - IsPinnedCode(ctx sdk.Context, codeID uint64) bool - GetParams(ctx sdk.Context) Params -} - -// ContractOpsKeeper contains mutable operations on a contract. -type ContractOpsKeeper interface { - // Create uploads and compiles a WASM contract, returning a short identifier for the contract - Create(ctx sdk.Context, creator sdk.AccAddress, wasmCode []byte, instantiateAccess *AccessConfig) (codeID uint64, checksum []byte, err error) - - // Instantiate creates an instance of a WASM contract using the classic sequence based address generator - Instantiate( - ctx sdk.Context, - codeID uint64, - creator, admin sdk.AccAddress, - initMsg []byte, - label string, - deposit sdk.Coins, - ) (sdk.AccAddress, []byte, error) - - // Instantiate2 creates an instance of a WASM contract using the predictable address generator - Instantiate2( - ctx sdk.Context, - codeID uint64, - creator, admin sdk.AccAddress, - initMsg []byte, - label string, - deposit sdk.Coins, - salt []byte, - fixMsg bool, - ) (sdk.AccAddress, []byte, error) - - // Execute executes the contract instance - Execute(ctx sdk.Context, contractAddress sdk.AccAddress, caller sdk.AccAddress, msg []byte, coins sdk.Coins) ([]byte, error) - - // Migrate allows to upgrade a contract to a new code with data migration. - Migrate(ctx sdk.Context, contractAddress sdk.AccAddress, caller sdk.AccAddress, newCodeID uint64, msg []byte) ([]byte, error) - - // Sudo allows to call privileged entry point of a contract. - Sudo(ctx sdk.Context, contractAddress sdk.AccAddress, msg []byte) ([]byte, error) - - // UpdateContractAdmin sets the admin value on the ContractInfo. It must be a valid address (use ClearContractAdmin to remove it) - UpdateContractAdmin(ctx sdk.Context, contractAddress sdk.AccAddress, caller sdk.AccAddress, newAdmin sdk.AccAddress) error - - // ClearContractAdmin sets the admin value on the ContractInfo to nil, to disable further migrations/ updates. - ClearContractAdmin(ctx sdk.Context, contractAddress sdk.AccAddress, caller sdk.AccAddress) error - - // PinCode pins the wasm contract in wasmvm cache - PinCode(ctx sdk.Context, codeID uint64) error - - // UnpinCode removes the wasm contract from wasmvm cache - UnpinCode(ctx sdk.Context, codeID uint64) error - - // SetContractInfoExtension updates the extension point data that is stored with the contract info - SetContractInfoExtension(ctx sdk.Context, contract sdk.AccAddress, extra ContractInfoExtension) error - - // SetAccessConfig updates the access config of a code id. - SetAccessConfig(ctx sdk.Context, codeID uint64, caller sdk.AccAddress, newConfig AccessConfig) error -} - -// IBCContractKeeper IBC lifecycle event handler -type IBCContractKeeper interface { - OnOpenChannel( - ctx sdk.Context, - contractAddr sdk.AccAddress, - msg wasmvmtypes.IBCChannelOpenMsg, - ) (string, error) - OnConnectChannel( - ctx sdk.Context, - contractAddr sdk.AccAddress, - msg wasmvmtypes.IBCChannelConnectMsg, - ) error - OnCloseChannel( - ctx sdk.Context, - contractAddr sdk.AccAddress, - msg wasmvmtypes.IBCChannelCloseMsg, - ) error - OnRecvPacket( - ctx sdk.Context, - contractAddr sdk.AccAddress, - msg wasmvmtypes.IBCPacketReceiveMsg, - ) ([]byte, error) - OnAckPacket( - ctx sdk.Context, - contractAddr sdk.AccAddress, - acknowledgement wasmvmtypes.IBCPacketAckMsg, - ) error - OnTimeoutPacket( - ctx sdk.Context, - contractAddr sdk.AccAddress, - msg wasmvmtypes.IBCPacketTimeoutMsg, - ) error - // ClaimCapability allows the transfer module to claim a capability - // that IBC module passes to it - ClaimCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) error - // AuthenticateCapability wraps the scopedKeeper's AuthenticateCapability function - AuthenticateCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) bool -} diff --git a/x/wasm/types/feature_flag.go b/x/wasm/types/feature_flag.go deleted file mode 100644 index 959252c..0000000 --- a/x/wasm/types/feature_flag.go +++ /dev/null @@ -1,4 +0,0 @@ -package types - -// Tests should not fail on gas consumption -const EnableGasVerification = true diff --git a/x/wasm/types/genesis.go b/x/wasm/types/genesis.go deleted file mode 100644 index 8a5a156..0000000 --- a/x/wasm/types/genesis.go +++ /dev/null @@ -1,102 +0,0 @@ -package types - -import ( - errorsmod "cosmossdk.io/errors" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func (s Sequence) ValidateBasic() error { - if len(s.IDKey) == 0 { - return errorsmod.Wrap(ErrEmpty, "id key") - } - return nil -} - -func (s GenesisState) ValidateBasic() error { - if err := s.Params.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "params") - } - for i := range s.Codes { - if err := s.Codes[i].ValidateBasic(); err != nil { - return errorsmod.Wrapf(err, "code: %d", i) - } - } - for i := range s.Contracts { - if err := s.Contracts[i].ValidateBasic(); err != nil { - return errorsmod.Wrapf(err, "contract: %d", i) - } - } - for i := range s.Sequences { - if err := s.Sequences[i].ValidateBasic(); err != nil { - return errorsmod.Wrapf(err, "sequence: %d", i) - } - } - - return nil -} - -func (c Code) ValidateBasic() error { - if c.CodeID == 0 { - return errorsmod.Wrap(ErrEmpty, "code id") - } - if err := c.CodeInfo.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "code info") - } - if err := validateWasmCode(c.CodeBytes, MaxProposalWasmSize); err != nil { - return errorsmod.Wrap(err, "code bytes") - } - return nil -} - -func (c Contract) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(c.ContractAddress); err != nil { - return errorsmod.Wrap(err, "contract address") - } - if err := c.ContractInfo.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "contract info") - } - - if c.ContractInfo.Created == nil { - return errorsmod.Wrap(ErrInvalid, "created must not be empty") - } - for i := range c.ContractState { - if err := c.ContractState[i].ValidateBasic(); err != nil { - return errorsmod.Wrapf(err, "contract state %d", i) - } - } - if len(c.ContractCodeHistory) == 0 { - return ErrEmpty.Wrap("code history") - } - for i, v := range c.ContractCodeHistory { - if err := v.ValidateBasic(); err != nil { - return errorsmod.Wrapf(err, "code history element %d", i) - } - } - return nil -} - -// ValidateGenesis performs basic validation of supply genesis data returning an -// error for any failed validation criteria. -func ValidateGenesis(data GenesisState) error { - return data.ValidateBasic() -} - -var _ codectypes.UnpackInterfacesMessage = GenesisState{} - -// UnpackInterfaces implements codectypes.UnpackInterfaces -func (s GenesisState) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { - for _, v := range s.Contracts { - if err := v.UnpackInterfaces(unpacker); err != nil { - return err - } - } - return nil -} - -var _ codectypes.UnpackInterfacesMessage = &Contract{} - -// UnpackInterfaces implements codectypes.UnpackInterfaces -func (c *Contract) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { - return c.ContractInfo.UnpackInterfaces(unpacker) -} diff --git a/x/wasm/types/genesis.pb.go b/x/wasm/types/genesis.pb.go deleted file mode 100644 index 4a946b0..0000000 --- a/x/wasm/types/genesis.pb.go +++ /dev/null @@ -1,1420 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmwasm/wasm/v1/genesis.proto - -package types - -import ( - fmt "fmt" - io "io" - math "math" - math_bits "math/bits" - - _ "github.com/cosmos/cosmos-sdk/types/tx/amino" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = proto.Marshal - _ = fmt.Errorf - _ = math.Inf -) - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// GenesisState - genesis state of x/wasm -type GenesisState struct { - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` - Codes []Code `protobuf:"bytes,2,rep,name=codes,proto3" json:"codes,omitempty"` - Contracts []Contract `protobuf:"bytes,3,rep,name=contracts,proto3" json:"contracts,omitempty"` - Sequences []Sequence `protobuf:"bytes,4,rep,name=sequences,proto3" json:"sequences,omitempty"` -} - -func (m *GenesisState) Reset() { *m = GenesisState{} } -func (m *GenesisState) String() string { return proto.CompactTextString(m) } -func (*GenesisState) ProtoMessage() {} -func (*GenesisState) Descriptor() ([]byte, []int) { - return fileDescriptor_2ab3f539b23472a6, []int{0} -} - -func (m *GenesisState) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_GenesisState.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *GenesisState) XXX_Merge(src proto.Message) { - xxx_messageInfo_GenesisState.Merge(m, src) -} - -func (m *GenesisState) XXX_Size() int { - return m.Size() -} - -func (m *GenesisState) XXX_DiscardUnknown() { - xxx_messageInfo_GenesisState.DiscardUnknown(m) -} - -var xxx_messageInfo_GenesisState proto.InternalMessageInfo - -func (m *GenesisState) GetParams() Params { - if m != nil { - return m.Params - } - return Params{} -} - -func (m *GenesisState) GetCodes() []Code { - if m != nil { - return m.Codes - } - return nil -} - -func (m *GenesisState) GetContracts() []Contract { - if m != nil { - return m.Contracts - } - return nil -} - -func (m *GenesisState) GetSequences() []Sequence { - if m != nil { - return m.Sequences - } - return nil -} - -// Code struct encompasses CodeInfo and CodeBytes -type Code struct { - CodeID uint64 `protobuf:"varint,1,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` - CodeInfo CodeInfo `protobuf:"bytes,2,opt,name=code_info,json=codeInfo,proto3" json:"code_info"` - CodeBytes []byte `protobuf:"bytes,3,opt,name=code_bytes,json=codeBytes,proto3" json:"code_bytes,omitempty"` - // Pinned to wasmvm cache - Pinned bool `protobuf:"varint,4,opt,name=pinned,proto3" json:"pinned,omitempty"` -} - -func (m *Code) Reset() { *m = Code{} } -func (m *Code) String() string { return proto.CompactTextString(m) } -func (*Code) ProtoMessage() {} -func (*Code) Descriptor() ([]byte, []int) { - return fileDescriptor_2ab3f539b23472a6, []int{1} -} - -func (m *Code) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *Code) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Code.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *Code) XXX_Merge(src proto.Message) { - xxx_messageInfo_Code.Merge(m, src) -} - -func (m *Code) XXX_Size() int { - return m.Size() -} - -func (m *Code) XXX_DiscardUnknown() { - xxx_messageInfo_Code.DiscardUnknown(m) -} - -var xxx_messageInfo_Code proto.InternalMessageInfo - -func (m *Code) GetCodeID() uint64 { - if m != nil { - return m.CodeID - } - return 0 -} - -func (m *Code) GetCodeInfo() CodeInfo { - if m != nil { - return m.CodeInfo - } - return CodeInfo{} -} - -func (m *Code) GetCodeBytes() []byte { - if m != nil { - return m.CodeBytes - } - return nil -} - -func (m *Code) GetPinned() bool { - if m != nil { - return m.Pinned - } - return false -} - -// Contract struct encompasses ContractAddress, ContractInfo, and ContractState -type Contract struct { - ContractAddress string `protobuf:"bytes,1,opt,name=contract_address,json=contractAddress,proto3" json:"contract_address,omitempty"` - ContractInfo ContractInfo `protobuf:"bytes,2,opt,name=contract_info,json=contractInfo,proto3" json:"contract_info"` - ContractState []Model `protobuf:"bytes,3,rep,name=contract_state,json=contractState,proto3" json:"contract_state"` - ContractCodeHistory []ContractCodeHistoryEntry `protobuf:"bytes,4,rep,name=contract_code_history,json=contractCodeHistory,proto3" json:"contract_code_history"` -} - -func (m *Contract) Reset() { *m = Contract{} } -func (m *Contract) String() string { return proto.CompactTextString(m) } -func (*Contract) ProtoMessage() {} -func (*Contract) Descriptor() ([]byte, []int) { - return fileDescriptor_2ab3f539b23472a6, []int{2} -} - -func (m *Contract) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *Contract) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Contract.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *Contract) XXX_Merge(src proto.Message) { - xxx_messageInfo_Contract.Merge(m, src) -} - -func (m *Contract) XXX_Size() int { - return m.Size() -} - -func (m *Contract) XXX_DiscardUnknown() { - xxx_messageInfo_Contract.DiscardUnknown(m) -} - -var xxx_messageInfo_Contract proto.InternalMessageInfo - -func (m *Contract) GetContractAddress() string { - if m != nil { - return m.ContractAddress - } - return "" -} - -func (m *Contract) GetContractInfo() ContractInfo { - if m != nil { - return m.ContractInfo - } - return ContractInfo{} -} - -func (m *Contract) GetContractState() []Model { - if m != nil { - return m.ContractState - } - return nil -} - -func (m *Contract) GetContractCodeHistory() []ContractCodeHistoryEntry { - if m != nil { - return m.ContractCodeHistory - } - return nil -} - -// Sequence key and value of an id generation counter -type Sequence struct { - IDKey []byte `protobuf:"bytes,1,opt,name=id_key,json=idKey,proto3" json:"id_key,omitempty"` - Value uint64 `protobuf:"varint,2,opt,name=value,proto3" json:"value,omitempty"` -} - -func (m *Sequence) Reset() { *m = Sequence{} } -func (m *Sequence) String() string { return proto.CompactTextString(m) } -func (*Sequence) ProtoMessage() {} -func (*Sequence) Descriptor() ([]byte, []int) { - return fileDescriptor_2ab3f539b23472a6, []int{3} -} - -func (m *Sequence) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *Sequence) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Sequence.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *Sequence) XXX_Merge(src proto.Message) { - xxx_messageInfo_Sequence.Merge(m, src) -} - -func (m *Sequence) XXX_Size() int { - return m.Size() -} - -func (m *Sequence) XXX_DiscardUnknown() { - xxx_messageInfo_Sequence.DiscardUnknown(m) -} - -var xxx_messageInfo_Sequence proto.InternalMessageInfo - -func (m *Sequence) GetIDKey() []byte { - if m != nil { - return m.IDKey - } - return nil -} - -func (m *Sequence) GetValue() uint64 { - if m != nil { - return m.Value - } - return 0 -} - -func init() { - proto.RegisterType((*GenesisState)(nil), "cosmwasm.wasm.v1.GenesisState") - proto.RegisterType((*Code)(nil), "cosmwasm.wasm.v1.Code") - proto.RegisterType((*Contract)(nil), "cosmwasm.wasm.v1.Contract") - proto.RegisterType((*Sequence)(nil), "cosmwasm.wasm.v1.Sequence") -} - -func init() { proto.RegisterFile("cosmwasm/wasm/v1/genesis.proto", fileDescriptor_2ab3f539b23472a6) } - -var fileDescriptor_2ab3f539b23472a6 = []byte{ - // 568 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x93, 0x41, 0x6f, 0xd3, 0x30, - 0x14, 0xc7, 0x9b, 0xae, 0x0d, 0xad, 0x57, 0xd8, 0x30, 0x63, 0x44, 0xd5, 0x48, 0xab, 0x72, 0x29, - 0x13, 0x6b, 0xb4, 0x71, 0xe4, 0x44, 0x18, 0x1a, 0x65, 0x02, 0xa1, 0xec, 0xb6, 0x4b, 0x95, 0x26, - 0x6f, 0x5d, 0xb4, 0xc5, 0x0e, 0xb1, 0xdb, 0x91, 0x6f, 0xc1, 0xa7, 0x40, 0x1c, 0xb9, 0xf3, 0x05, - 0x76, 0x63, 0x47, 0x4e, 0x15, 0x6a, 0x0f, 0x48, 0x7c, 0x0a, 0x64, 0x3b, 0xc9, 0xa2, 0x76, 0xbd, - 0x58, 0xc9, 0x7b, 0xff, 0xf7, 0xf3, 0xf3, 0xdf, 0xcf, 0xc8, 0xf4, 0x28, 0x0b, 0xaf, 0x5c, 0x16, - 0x5a, 0x72, 0x99, 0xec, 0x5b, 0x23, 0x20, 0xc0, 0x02, 0xd6, 0x8b, 0x62, 0xca, 0x29, 0xde, 0xcc, - 0xf2, 0x3d, 0xb9, 0x4c, 0xf6, 0x9b, 0x5b, 0x23, 0x3a, 0xa2, 0x32, 0x69, 0x89, 0x2f, 0xa5, 0x6b, - 0xee, 0x2c, 0x71, 0x78, 0x12, 0x41, 0x4a, 0x69, 0x3e, 0x74, 0xc3, 0x80, 0x50, 0x4b, 0xae, 0x2a, - 0xd4, 0xf9, 0x55, 0x46, 0x8d, 0x23, 0xb5, 0xd5, 0x09, 0x77, 0x39, 0xe0, 0x57, 0x48, 0x8f, 0xdc, - 0xd8, 0x0d, 0x99, 0xa1, 0xb5, 0xb5, 0xee, 0xfa, 0x81, 0xd1, 0x5b, 0xdc, 0xba, 0xf7, 0x49, 0xe6, - 0xed, 0xfa, 0xf5, 0xb4, 0x55, 0xfa, 0xfe, 0xf7, 0xc7, 0xae, 0xe6, 0xa4, 0x25, 0xf8, 0x3d, 0xaa, - 0x7a, 0xd4, 0x07, 0x66, 0x94, 0xdb, 0x6b, 0xdd, 0xf5, 0x83, 0xed, 0xe5, 0xda, 0x37, 0xd4, 0x07, - 0x7b, 0x47, 0x54, 0xfe, 0x9b, 0xb6, 0x36, 0xa4, 0xf8, 0x05, 0x0d, 0x03, 0x0e, 0x61, 0xc4, 0x13, - 0x05, 0x53, 0x08, 0x7c, 0x8a, 0xea, 0x1e, 0x25, 0x3c, 0x76, 0x3d, 0xce, 0x8c, 0x35, 0xc9, 0x6b, - 0xde, 0xc5, 0x53, 0x12, 0xbb, 0x9d, 0x32, 0x1f, 0xe5, 0x45, 0x8b, 0xdc, 0x5b, 0x9c, 0x60, 0x33, - 0xf8, 0x3c, 0x06, 0xe2, 0x01, 0x33, 0x2a, 0xab, 0xd8, 0x27, 0xa9, 0xe4, 0x96, 0x9d, 0x17, 0x2d, - 0xb1, 0xf3, 0x4c, 0xe7, 0x9b, 0x86, 0x2a, 0xe2, 0x94, 0xf8, 0x19, 0xba, 0x27, 0x4e, 0x32, 0x08, - 0x7c, 0x69, 0x65, 0xc5, 0x46, 0xb3, 0x69, 0x4b, 0x17, 0xa9, 0xfe, 0xa1, 0xa3, 0x8b, 0x54, 0xdf, - 0xc7, 0xb6, 0x38, 0xa5, 0x10, 0x91, 0x33, 0x6a, 0x94, 0xa5, 0xe3, 0xcd, 0xbb, 0x5d, 0xeb, 0x93, - 0x33, 0x5a, 0xf4, 0xbc, 0xe6, 0xa5, 0x41, 0xfc, 0x14, 0x21, 0xc9, 0x18, 0x26, 0x1c, 0x84, 0x55, - 0x5a, 0xb7, 0xe1, 0x48, 0xaa, 0x2d, 0x02, 0x78, 0x1b, 0xe9, 0x51, 0x40, 0x08, 0xf8, 0x46, 0xa5, - 0xad, 0x75, 0x6b, 0x4e, 0xfa, 0xd7, 0xf9, 0x59, 0x46, 0xb5, 0xcc, 0x3e, 0xfc, 0x1c, 0x6d, 0x66, - 0xf6, 0x0c, 0x5c, 0xdf, 0x8f, 0x81, 0xa9, 0x01, 0xa8, 0x3b, 0x1b, 0x59, 0xfc, 0xb5, 0x0a, 0xe3, - 0x8f, 0xe8, 0x7e, 0x2e, 0x2d, 0xb4, 0x6d, 0xae, 0xbe, 0x9c, 0xc5, 0xd6, 0x1b, 0x5e, 0x21, 0x81, - 0xfb, 0xe8, 0x41, 0xce, 0x63, 0x62, 0x06, 0xd3, 0xdb, 0x7e, 0xb2, 0x0c, 0xfc, 0x40, 0x7d, 0xb8, - 0x2c, 0x92, 0xf2, 0x4e, 0xd4, 0xf0, 0x06, 0xe8, 0x71, 0x8e, 0x92, 0x96, 0x9c, 0x07, 0x8c, 0xd3, - 0x38, 0x49, 0xef, 0x78, 0x77, 0x75, 0x8b, 0xc2, 0xe1, 0x77, 0x4a, 0xfc, 0x96, 0xf0, 0x38, 0x29, - 0x6e, 0x92, 0x8f, 0x54, 0x41, 0xd4, 0xb1, 0x51, 0x2d, 0x9b, 0x0f, 0xdc, 0x46, 0x7a, 0xe0, 0x0f, - 0x2e, 0x20, 0x91, 0x96, 0x35, 0xec, 0xfa, 0x6c, 0xda, 0xaa, 0xf6, 0x0f, 0x8f, 0x21, 0x71, 0xaa, - 0x81, 0x7f, 0x0c, 0x09, 0xde, 0x42, 0xd5, 0x89, 0x7b, 0x39, 0x06, 0xe9, 0x55, 0xc5, 0x51, 0x3f, - 0xf6, 0xd1, 0xf5, 0xcc, 0xd4, 0x6e, 0x66, 0xa6, 0xf6, 0x67, 0x66, 0x6a, 0x5f, 0xe7, 0x66, 0xe9, - 0x66, 0x6e, 0x96, 0x7e, 0xcf, 0xcd, 0xd2, 0xe9, 0xde, 0x28, 0xe0, 0xe7, 0xe3, 0x61, 0xcf, 0xa3, - 0xa1, 0xc5, 0x21, 0x8e, 0x08, 0xf0, 0x2b, 0x1a, 0x5f, 0xc8, 0xef, 0x3d, 0x8f, 0xc6, 0x60, 0x7d, - 0x51, 0x2f, 0x5c, 0x3e, 0xef, 0xa1, 0x2e, 0x1f, 0xf3, 0xcb, 0xff, 0x01, 0x00, 0x00, 0xff, 0xff, - 0x2e, 0x99, 0x42, 0xb2, 0x47, 0x04, 0x00, 0x00, -} - -func (m *GenesisState) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *GenesisState) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Sequences) > 0 { - for iNdEx := len(m.Sequences) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Sequences[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - if len(m.Contracts) > 0 { - for iNdEx := len(m.Contracts) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Contracts[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Codes) > 0 { - for iNdEx := len(m.Codes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Codes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *Code) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Code) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Code) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pinned { - i-- - if m.Pinned { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x20 - } - if len(m.CodeBytes) > 0 { - i -= len(m.CodeBytes) - copy(dAtA[i:], m.CodeBytes) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.CodeBytes))) - i-- - dAtA[i] = 0x1a - } - { - size, err := m.CodeInfo.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if m.CodeID != 0 { - i = encodeVarintGenesis(dAtA, i, uint64(m.CodeID)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *Contract) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Contract) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Contract) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.ContractCodeHistory) > 0 { - for iNdEx := len(m.ContractCodeHistory) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.ContractCodeHistory[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - if len(m.ContractState) > 0 { - for iNdEx := len(m.ContractState) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.ContractState[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - { - size, err := m.ContractInfo.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.ContractAddress) > 0 { - i -= len(m.ContractAddress) - copy(dAtA[i:], m.ContractAddress) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.ContractAddress))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *Sequence) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Sequence) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Sequence) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Value != 0 { - i = encodeVarintGenesis(dAtA, i, uint64(m.Value)) - i-- - dAtA[i] = 0x10 - } - if len(m.IDKey) > 0 { - i -= len(m.IDKey) - copy(dAtA[i:], m.IDKey) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.IDKey))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { - offset -= sovGenesis(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} - -func (m *GenesisState) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Params.Size() - n += 1 + l + sovGenesis(uint64(l)) - if len(m.Codes) > 0 { - for _, e := range m.Codes { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.Contracts) > 0 { - for _, e := range m.Contracts { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.Sequences) > 0 { - for _, e := range m.Sequences { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - return n -} - -func (m *Code) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.CodeID != 0 { - n += 1 + sovGenesis(uint64(m.CodeID)) - } - l = m.CodeInfo.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = len(m.CodeBytes) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - if m.Pinned { - n += 2 - } - return n -} - -func (m *Contract) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.ContractAddress) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - l = m.ContractInfo.Size() - n += 1 + l + sovGenesis(uint64(l)) - if len(m.ContractState) > 0 { - for _, e := range m.ContractState { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.ContractCodeHistory) > 0 { - for _, e := range m.ContractCodeHistory { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - return n -} - -func (m *Sequence) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.IDKey) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - if m.Value != 0 { - n += 1 + sovGenesis(uint64(m.Value)) - } - return n -} - -func sovGenesis(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} - -func sozGenesis(x uint64) (n int) { - return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} - -func (m *GenesisState) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: GenesisState: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Codes", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Codes = append(m.Codes, Code{}) - if err := m.Codes[len(m.Codes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Contracts", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Contracts = append(m.Contracts, Contract{}) - if err := m.Contracts[len(m.Contracts)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sequences", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sequences = append(m.Sequences, Sequence{}) - if err := m.Sequences[len(m.Sequences)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *Code) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Code: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Code: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) - } - m.CodeID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CodeID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeInfo", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.CodeInfo.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeBytes", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CodeBytes = append(m.CodeBytes[:0], dAtA[iNdEx:postIndex]...) - if m.CodeBytes == nil { - m.CodeBytes = []byte{} - } - iNdEx = postIndex - case 4: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Pinned", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Pinned = bool(v != 0) - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *Contract) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Contract: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Contract: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ContractAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ContractAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ContractInfo", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ContractInfo.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ContractState", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ContractState = append(m.ContractState, Model{}) - if err := m.ContractState[len(m.ContractState)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ContractCodeHistory", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ContractCodeHistory = append(m.ContractCodeHistory, ContractCodeHistoryEntry{}) - if err := m.ContractCodeHistory[len(m.ContractCodeHistory)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *Sequence) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Sequence: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Sequence: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IDKey", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.IDKey = append(m.IDKey[:0], dAtA[iNdEx:postIndex]...) - if m.IDKey == nil { - m.IDKey = []byte{} - } - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - m.Value = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Value |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func skipGenesis(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthGenesis - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupGenesis - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthGenesis - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/wasm/types/genesis_test.go b/x/wasm/types/genesis_test.go deleted file mode 100644 index 258528c..0000000 --- a/x/wasm/types/genesis_test.go +++ /dev/null @@ -1,212 +0,0 @@ -package types - -import ( - "bytes" - "testing" - "time" - - "github.com/cometbft/cometbft/libs/rand" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -const invalidAddress = "invalid address" - -func TestValidateGenesisState(t *testing.T) { - specs := map[string]struct { - srcMutator func(*GenesisState) - expError bool - }{ - "all good": { - srcMutator: func(s *GenesisState) {}, - }, - "params invalid": { - srcMutator: func(s *GenesisState) { - s.Params = Params{} - }, - expError: true, - }, - "codeinfo invalid": { - srcMutator: func(s *GenesisState) { - s.Codes[0].CodeInfo.CodeHash = nil - }, - expError: true, - }, - "contract invalid": { - srcMutator: func(s *GenesisState) { - s.Contracts[0].ContractAddress = invalidAddress - }, - expError: true, - }, - "sequence invalid": { - srcMutator: func(s *GenesisState) { - s.Sequences[0].IDKey = nil - }, - expError: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - state := GenesisFixture(spec.srcMutator) - got := state.ValidateBasic() - if spec.expError { - require.Error(t, got) - return - } - require.NoError(t, got) - }) - } -} - -func TestCodeValidateBasic(t *testing.T) { - specs := map[string]struct { - srcMutator func(*Code) - expError bool - }{ - "all good": {srcMutator: func(_ *Code) {}}, - "code id invalid": { - srcMutator: func(c *Code) { - c.CodeID = 0 - }, - expError: true, - }, - "codeinfo invalid": { - srcMutator: func(c *Code) { - c.CodeInfo.CodeHash = nil - }, - expError: true, - }, - "codeBytes empty": { - srcMutator: func(c *Code) { - c.CodeBytes = []byte{} - }, - expError: true, - }, - "codeBytes nil": { - srcMutator: func(c *Code) { - c.CodeBytes = nil - }, - expError: true, - }, - "codeBytes greater limit": { - srcMutator: func(c *Code) { - c.CodeBytes = bytes.Repeat([]byte{0x1}, MaxProposalWasmSize+1) - }, - expError: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - state := CodeFixture(spec.srcMutator) - got := state.ValidateBasic() - if spec.expError { - require.Error(t, got) - return - } - require.NoError(t, got) - }) - } -} - -func TestContractValidateBasic(t *testing.T) { - specs := map[string]struct { - srcMutator func(*Contract) - expError bool - }{ - "all good": {srcMutator: func(_ *Contract) {}}, - "contract address invalid": { - srcMutator: func(c *Contract) { - c.ContractAddress = invalidAddress - }, - expError: true, - }, - "contract info invalid": { - srcMutator: func(c *Contract) { - c.ContractInfo.Creator = invalidAddress - }, - expError: true, - }, - "contract with created set": { - srcMutator: func(c *Contract) { - c.ContractInfo.Created = &AbsoluteTxPosition{} - }, - expError: false, - }, - "contract state invalid": { - srcMutator: func(c *Contract) { - c.ContractState = append(c.ContractState, Model{}) - }, - expError: true, - }, - "contract history invalid": { - srcMutator: func(c *Contract) { - c.ContractCodeHistory = []ContractCodeHistoryEntry{{}} - }, - expError: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - state := ContractFixture(spec.srcMutator) - got := state.ValidateBasic() - if spec.expError { - require.Error(t, got) - return - } - require.NoError(t, got) - }) - } -} - -func TestGenesisContractInfoMarshalUnmarshal(t *testing.T) { - var myAddr sdk.AccAddress = rand.Bytes(ContractAddrLen) - var myOtherAddr sdk.AccAddress = rand.Bytes(ContractAddrLen) - anyPos := AbsoluteTxPosition{BlockHeight: 1, TxIndex: 2} - - anyTime := time.Now().UTC() - // using gov proposal here as a random protobuf types as it contains an Any type inside for nested unpacking - myExtension, err := v1beta1.NewProposal(&v1beta1.TextProposal{Title: "bar"}, 1, anyTime, anyTime) - require.NoError(t, err) - myExtension.TotalDeposit = nil - - src := NewContractInfo(1, myAddr, myOtherAddr, "bar", &anyPos) - err = src.SetExtension(&myExtension) - require.NoError(t, err) - - interfaceRegistry := types.NewInterfaceRegistry() - marshaler := codec.NewProtoCodec(interfaceRegistry) - RegisterInterfaces(interfaceRegistry) - // register proposal as extension type - interfaceRegistry.RegisterImplementations( - (*ContractInfoExtension)(nil), - &v1beta1.Proposal{}, - ) - // register gov types for nested Anys - v1beta1.RegisterInterfaces(interfaceRegistry) - - // when encode - gs := GenesisState{ - Contracts: []Contract{{ - ContractInfo: src, - }}, - } - - bz, err := marshaler.Marshal(&gs) - require.NoError(t, err) - // and decode - var destGs GenesisState - err = marshaler.Unmarshal(bz, &destGs) - require.NoError(t, err) - // then - require.Len(t, destGs.Contracts, 1) - dest := destGs.Contracts[0].ContractInfo - assert.Equal(t, src, dest) - // and sanity check nested any - var destExt v1beta1.Proposal - require.NoError(t, dest.ReadExtension(&destExt)) - assert.Equal(t, destExt.GetTitle(), "bar") -} diff --git a/x/wasm/types/iavl_range_test.go b/x/wasm/types/iavl_range_test.go deleted file mode 100644 index fd3297b..0000000 --- a/x/wasm/types/iavl_range_test.go +++ /dev/null @@ -1,83 +0,0 @@ -package types - -import ( - "testing" - - dbm "github.com/cometbft/cometbft-db" - "github.com/cosmos/cosmos-sdk/store" - "github.com/cosmos/cosmos-sdk/store/iavl" - iavl2 "github.com/cosmos/iavl" - "github.com/stretchr/testify/require" -) - -// This is modeled close to -// https://github.com/CosmWasm/cosmwasm-plus/blob/f97a7de44b6a930fd1d5179ee6f95b786a532f32/packages/storage-plus/src/prefix.rs#L183 -// and designed to ensure the IAVL store handles bounds the same way as the mock storage we use in Rust contract tests -func TestIavlRangeBounds(t *testing.T) { - memdb := dbm.NewMemDB() - tree, err := iavl2.NewMutableTree(memdb, 50, false) - require.NoError(t, err) - kvstore := iavl.UnsafeNewStore(tree) - - // values to compare with - expected := []KV{ - {[]byte("bar"), []byte("1")}, - {[]byte("ra"), []byte("2")}, - {[]byte("zi"), []byte("3")}, - } - reversed := []KV{ - {[]byte("zi"), []byte("3")}, - {[]byte("ra"), []byte("2")}, - {[]byte("bar"), []byte("1")}, - } - - // set up test cases, like `ensure_proper_range_bounds` in `cw-storage-plus` - for _, kv := range expected { - kvstore.Set(kv.Key, kv.Value) - } - - cases := map[string]struct { - start []byte - end []byte - reverse bool - expected []KV - }{ - "all ascending": {nil, nil, false, expected}, - "ascending start inclusive": {[]byte("ra"), nil, false, expected[1:]}, - "ascending end exclusive": {nil, []byte("ra"), false, expected[:1]}, - "ascending both points": {[]byte("bar"), []byte("zi"), false, expected[:2]}, - - "all descending": {nil, nil, true, reversed}, - "descending start inclusive": {[]byte("ra"), nil, true, reversed[:2]}, // "zi", "ra" - "descending end inclusive": {nil, []byte("ra"), true, reversed[2:]}, // "bar" - "descending both points": {[]byte("bar"), []byte("zi"), true, reversed[1:]}, // "ra", "bar" - } - - for name, tc := range cases { - t.Run(name, func(t *testing.T) { - var iter store.Iterator - if tc.reverse { - iter = kvstore.ReverseIterator(tc.start, tc.end) - } else { - iter = kvstore.Iterator(tc.start, tc.end) - } - items := consume(iter) - require.Equal(t, tc.expected, items) - iter.Close() - }) - } -} - -type KV struct { - Key []byte - Value []byte -} - -func consume(itr store.Iterator) []KV { - var res []KV - for ; itr.Valid(); itr.Next() { - k, v := itr.Key(), itr.Value() - res = append(res, KV{k, v}) - } - return res -} diff --git a/x/wasm/types/ibc.pb.go b/x/wasm/types/ibc.pb.go deleted file mode 100644 index cf1b535..0000000 --- a/x/wasm/types/ibc.pb.go +++ /dev/null @@ -1,766 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmwasm/wasm/v1/ibc.proto - -package types - -import ( - fmt "fmt" - io "io" - math "math" - math_bits "math/bits" - - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = proto.Marshal - _ = fmt.Errorf - _ = math.Inf -) - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// MsgIBCSend -type MsgIBCSend struct { - // the channel by which the packet will be sent - Channel string `protobuf:"bytes,2,opt,name=channel,proto3" json:"channel,omitempty" yaml:"source_channel"` - // Timeout height relative to the current block height. - // The timeout is disabled when set to 0. - TimeoutHeight uint64 `protobuf:"varint,4,opt,name=timeout_height,json=timeoutHeight,proto3" json:"timeout_height,omitempty" yaml:"timeout_height"` - // Timeout timestamp (in nanoseconds) relative to the current block timestamp. - // The timeout is disabled when set to 0. - TimeoutTimestamp uint64 `protobuf:"varint,5,opt,name=timeout_timestamp,json=timeoutTimestamp,proto3" json:"timeout_timestamp,omitempty" yaml:"timeout_timestamp"` - // Data is the payload to transfer. We must not make assumption what format or - // content is in here. - Data []byte `protobuf:"bytes,6,opt,name=data,proto3" json:"data,omitempty"` -} - -func (m *MsgIBCSend) Reset() { *m = MsgIBCSend{} } -func (m *MsgIBCSend) String() string { return proto.CompactTextString(m) } -func (*MsgIBCSend) ProtoMessage() {} -func (*MsgIBCSend) Descriptor() ([]byte, []int) { - return fileDescriptor_af0d1c43ea53c4b9, []int{0} -} - -func (m *MsgIBCSend) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgIBCSend) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgIBCSend.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *MsgIBCSend) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgIBCSend.Merge(m, src) -} - -func (m *MsgIBCSend) XXX_Size() int { - return m.Size() -} - -func (m *MsgIBCSend) XXX_DiscardUnknown() { - xxx_messageInfo_MsgIBCSend.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgIBCSend proto.InternalMessageInfo - -// MsgIBCSendResponse -type MsgIBCSendResponse struct { - // Sequence number of the IBC packet sent - Sequence uint64 `protobuf:"varint,1,opt,name=sequence,proto3" json:"sequence,omitempty"` -} - -func (m *MsgIBCSendResponse) Reset() { *m = MsgIBCSendResponse{} } -func (m *MsgIBCSendResponse) String() string { return proto.CompactTextString(m) } -func (*MsgIBCSendResponse) ProtoMessage() {} -func (*MsgIBCSendResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_af0d1c43ea53c4b9, []int{1} -} - -func (m *MsgIBCSendResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgIBCSendResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgIBCSendResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *MsgIBCSendResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgIBCSendResponse.Merge(m, src) -} - -func (m *MsgIBCSendResponse) XXX_Size() int { - return m.Size() -} - -func (m *MsgIBCSendResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgIBCSendResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgIBCSendResponse proto.InternalMessageInfo - -// MsgIBCCloseChannel port and channel need to be owned by the contract -type MsgIBCCloseChannel struct { - Channel string `protobuf:"bytes,2,opt,name=channel,proto3" json:"channel,omitempty" yaml:"source_channel"` -} - -func (m *MsgIBCCloseChannel) Reset() { *m = MsgIBCCloseChannel{} } -func (m *MsgIBCCloseChannel) String() string { return proto.CompactTextString(m) } -func (*MsgIBCCloseChannel) ProtoMessage() {} -func (*MsgIBCCloseChannel) Descriptor() ([]byte, []int) { - return fileDescriptor_af0d1c43ea53c4b9, []int{2} -} - -func (m *MsgIBCCloseChannel) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgIBCCloseChannel) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgIBCCloseChannel.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *MsgIBCCloseChannel) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgIBCCloseChannel.Merge(m, src) -} - -func (m *MsgIBCCloseChannel) XXX_Size() int { - return m.Size() -} - -func (m *MsgIBCCloseChannel) XXX_DiscardUnknown() { - xxx_messageInfo_MsgIBCCloseChannel.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgIBCCloseChannel proto.InternalMessageInfo - -func init() { - proto.RegisterType((*MsgIBCSend)(nil), "cosmwasm.wasm.v1.MsgIBCSend") - proto.RegisterType((*MsgIBCSendResponse)(nil), "cosmwasm.wasm.v1.MsgIBCSendResponse") - proto.RegisterType((*MsgIBCCloseChannel)(nil), "cosmwasm.wasm.v1.MsgIBCCloseChannel") -} - -func init() { proto.RegisterFile("cosmwasm/wasm/v1/ibc.proto", fileDescriptor_af0d1c43ea53c4b9) } - -var fileDescriptor_af0d1c43ea53c4b9 = []byte{ - // 334 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x51, 0xc1, 0x4e, 0xf2, 0x40, - 0x10, 0xee, 0xfe, 0xe1, 0x47, 0xdd, 0xa8, 0xc1, 0x8d, 0x26, 0x95, 0x98, 0x85, 0xec, 0x89, 0x0b, - 0x54, 0xc2, 0xcd, 0x93, 0x81, 0x8b, 0xc4, 0x78, 0xa9, 0x9e, 0xbc, 0x90, 0xb2, 0x4c, 0xda, 0x46, - 0xba, 0x5b, 0xbb, 0x5b, 0x90, 0xb7, 0xf0, 0xb1, 0x38, 0x72, 0xf4, 0x44, 0xb4, 0xbc, 0x01, 0x4f, - 0x60, 0x58, 0x5a, 0x94, 0xab, 0x97, 0xd9, 0x6f, 0xbe, 0xef, 0x9b, 0xd9, 0xcc, 0x0c, 0xae, 0x72, - 0xa9, 0xa2, 0xa9, 0xa7, 0x22, 0xc7, 0x84, 0x49, 0xdb, 0x09, 0x87, 0xbc, 0x15, 0x27, 0x52, 0x4b, - 0x52, 0x29, 0xb4, 0x96, 0x09, 0x93, 0x76, 0xf5, 0xdc, 0x97, 0xbe, 0x34, 0xa2, 0xb3, 0x41, 0x5b, - 0x1f, 0xcb, 0x10, 0xc6, 0x0f, 0xca, 0xef, 0x77, 0x7b, 0x8f, 0x20, 0x46, 0xa4, 0x83, 0x0f, 0x78, - 0xe0, 0x09, 0x01, 0x63, 0xfb, 0x5f, 0x1d, 0x35, 0x8e, 0xba, 0x97, 0xeb, 0x65, 0xed, 0x62, 0xe6, - 0x45, 0xe3, 0x1b, 0xa6, 0x64, 0x9a, 0x70, 0x18, 0xe4, 0x3a, 0x73, 0x0b, 0x27, 0xb9, 0xc5, 0xa7, - 0x3a, 0x8c, 0x40, 0xa6, 0x7a, 0x10, 0x40, 0xe8, 0x07, 0xda, 0x2e, 0xd5, 0x51, 0xa3, 0xf4, 0xbb, - 0x76, 0x5f, 0x67, 0xee, 0x49, 0x4e, 0xdc, 0x99, 0x9c, 0xf4, 0xf1, 0x59, 0xe1, 0xd8, 0xbc, 0x4a, - 0x7b, 0x51, 0x6c, 0xff, 0x37, 0x4d, 0xae, 0xd6, 0xcb, 0x9a, 0xbd, 0xdf, 0x64, 0x67, 0x61, 0x6e, - 0x25, 0xe7, 0x9e, 0x0a, 0x8a, 0x10, 0x5c, 0x1a, 0x79, 0xda, 0xb3, 0xcb, 0x75, 0xd4, 0x38, 0x76, - 0x0d, 0x66, 0xd7, 0x98, 0xfc, 0xcc, 0xe8, 0x82, 0x8a, 0xa5, 0x50, 0x40, 0xaa, 0xf8, 0x50, 0xc1, - 0x6b, 0x0a, 0x82, 0x83, 0x8d, 0x36, 0x7f, 0xb9, 0xbb, 0x9c, 0xf5, 0x8b, 0x8a, 0xde, 0x58, 0x2a, - 0xe8, 0xe5, 0x83, 0xfe, 0x65, 0x3b, 0xdd, 0xfb, 0xf9, 0x17, 0xb5, 0xe6, 0x19, 0x45, 0x8b, 0x8c, - 0xa2, 0xcf, 0x8c, 0xa2, 0xf7, 0x15, 0xb5, 0x16, 0x2b, 0x6a, 0x7d, 0xac, 0xa8, 0xf5, 0xdc, 0xf4, - 0x43, 0x1d, 0xa4, 0xc3, 0x16, 0x97, 0x91, 0xa3, 0x21, 0x89, 0x05, 0xe8, 0xa9, 0x4c, 0x5e, 0x0c, - 0x6e, 0x72, 0x99, 0x80, 0xf3, 0xb6, 0xbd, 0xae, 0x9e, 0xc5, 0xa0, 0x86, 0x65, 0x73, 0xb5, 0xce, - 0x77, 0x00, 0x00, 0x00, 0xff, 0xff, 0xba, 0x9b, 0x72, 0x2c, 0xfb, 0x01, 0x00, 0x00, -} - -func (m *MsgIBCSend) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgIBCSend) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgIBCSend) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Data) > 0 { - i -= len(m.Data) - copy(dAtA[i:], m.Data) - i = encodeVarintIbc(dAtA, i, uint64(len(m.Data))) - i-- - dAtA[i] = 0x32 - } - if m.TimeoutTimestamp != 0 { - i = encodeVarintIbc(dAtA, i, uint64(m.TimeoutTimestamp)) - i-- - dAtA[i] = 0x28 - } - if m.TimeoutHeight != 0 { - i = encodeVarintIbc(dAtA, i, uint64(m.TimeoutHeight)) - i-- - dAtA[i] = 0x20 - } - if len(m.Channel) > 0 { - i -= len(m.Channel) - copy(dAtA[i:], m.Channel) - i = encodeVarintIbc(dAtA, i, uint64(len(m.Channel))) - i-- - dAtA[i] = 0x12 - } - return len(dAtA) - i, nil -} - -func (m *MsgIBCSendResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgIBCSendResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgIBCSendResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Sequence != 0 { - i = encodeVarintIbc(dAtA, i, uint64(m.Sequence)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *MsgIBCCloseChannel) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgIBCCloseChannel) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgIBCCloseChannel) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Channel) > 0 { - i -= len(m.Channel) - copy(dAtA[i:], m.Channel) - i = encodeVarintIbc(dAtA, i, uint64(len(m.Channel))) - i-- - dAtA[i] = 0x12 - } - return len(dAtA) - i, nil -} - -func encodeVarintIbc(dAtA []byte, offset int, v uint64) int { - offset -= sovIbc(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} - -func (m *MsgIBCSend) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Channel) - if l > 0 { - n += 1 + l + sovIbc(uint64(l)) - } - if m.TimeoutHeight != 0 { - n += 1 + sovIbc(uint64(m.TimeoutHeight)) - } - if m.TimeoutTimestamp != 0 { - n += 1 + sovIbc(uint64(m.TimeoutTimestamp)) - } - l = len(m.Data) - if l > 0 { - n += 1 + l + sovIbc(uint64(l)) - } - return n -} - -func (m *MsgIBCSendResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Sequence != 0 { - n += 1 + sovIbc(uint64(m.Sequence)) - } - return n -} - -func (m *MsgIBCCloseChannel) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Channel) - if l > 0 { - n += 1 + l + sovIbc(uint64(l)) - } - return n -} - -func sovIbc(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} - -func sozIbc(x uint64) (n int) { - return sovIbc(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} - -func (m *MsgIBCSend) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowIbc - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgIBCSend: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgIBCSend: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Channel", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowIbc - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthIbc - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthIbc - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Channel = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TimeoutHeight", wireType) - } - m.TimeoutHeight = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowIbc - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.TimeoutHeight |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TimeoutTimestamp", wireType) - } - m.TimeoutTimestamp = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowIbc - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.TimeoutTimestamp |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowIbc - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthIbc - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthIbc - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) - if m.Data == nil { - m.Data = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipIbc(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthIbc - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgIBCSendResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowIbc - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgIBCSendResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgIBCSendResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Sequence", wireType) - } - m.Sequence = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowIbc - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Sequence |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipIbc(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthIbc - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgIBCCloseChannel) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowIbc - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgIBCCloseChannel: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgIBCCloseChannel: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Channel", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowIbc - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthIbc - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthIbc - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Channel = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipIbc(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthIbc - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func skipIbc(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowIbc - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowIbc - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowIbc - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthIbc - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupIbc - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthIbc - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthIbc = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowIbc = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupIbc = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/wasm/types/json_matching.go b/x/wasm/types/json_matching.go deleted file mode 100644 index 34ff76d..0000000 --- a/x/wasm/types/json_matching.go +++ /dev/null @@ -1,34 +0,0 @@ -package types - -import ( - "encoding/json" -) - -// isJSONObjectWithTopLevelKey returns true if the given bytes are a valid JSON object -// with exactly one top-level key that is contained in the list of allowed keys. -func isJSONObjectWithTopLevelKey(jsonBytes RawContractMessage, allowedKeys []string) (bool, error) { - if err := jsonBytes.ValidateBasic(); err != nil { - return false, err - } - - document := map[string]interface{}{} - if err := json.Unmarshal(jsonBytes, &document); err != nil { - return false, nil // not a map - } - - if len(document) != 1 { - return false, nil // unsupported type - } - - // Loop is executed exactly once - for topLevelKey := range document { - for _, allowedKey := range allowedKeys { - if allowedKey == topLevelKey { - return true, nil - } - } - return false, nil - } - - panic("Reached unreachable code. This is a bug.") -} diff --git a/x/wasm/types/json_matching_test.go b/x/wasm/types/json_matching_test.go deleted file mode 100644 index 286fde3..0000000 --- a/x/wasm/types/json_matching_test.go +++ /dev/null @@ -1,134 +0,0 @@ -package types - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/assert" - - // sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/stretchr/testify/require" -) - -func TestIsJSONObjectWithTopLevelKey(t *testing.T) { - specs := map[string]struct { - src []byte - allowedKeys []string - expResult bool - expErr error - }{ - "happy": { - src: []byte(`{"msg": {"foo":"bar"}}`), - allowedKeys: []string{"msg"}, - expResult: true, - }, - "happy with many allowed keys 1": { - src: []byte(`{"claim": {"foo":"bar"}}`), - allowedKeys: []string{"claim", "swap", "burn", "mint"}, - expResult: true, - }, - "happy with many allowed keys 2": { - src: []byte(`{"burn": {"foo":"bar"}}`), - allowedKeys: []string{"claim", "swap", "burn", "mint"}, - expResult: true, - }, - "happy with many allowed keys 3": { - src: []byte(`{"mint": {"foo":"bar"}}`), - allowedKeys: []string{"claim", "swap", "burn", "mint"}, - expResult: true, - }, - "happy with number": { - src: []byte(`{"msg": 123}`), - allowedKeys: []string{"msg"}, - expResult: true, - }, - "happy with array": { - src: []byte(`{"msg": [1, 2, 3, 4]}`), - allowedKeys: []string{"msg"}, - expResult: true, - }, - "happy with null": { - src: []byte(`{"msg": null}`), - allowedKeys: []string{"msg"}, - expResult: true, - }, - "happy with whitespace": { - src: []byte(`{ - "msg": null }`), - allowedKeys: []string{"msg"}, - expResult: true, - }, - "happy with escaped key": { - src: []byte(`{"event\u2468thing": {"foo":"bar"}}`), - allowedKeys: []string{"event⑨thing"}, - expResult: true, - }, - - // Invalid JSON object - "errors for bytes that are no JSON": { - src: []byte(`nope`), - allowedKeys: []string{"claim"}, - expErr: ErrInvalid, - }, - "false for valid JSON (string)": { - src: []byte(`"nope"`), - allowedKeys: []string{"claim"}, - expResult: false, - }, - "false for valid JSON (array)": { - src: []byte(`[1, 2, 3]`), - allowedKeys: []string{"claim"}, - expResult: false, - }, - // not supported: https://github.com/golang/go/issues/24415 - // "errors for duplicate key": { - // src: []byte(`{"claim": "foo", "claim":"bar"}`), - // allowedKeys: []string{"claim"}, - // expErr: ErrNotAJSONObject, - // }, - - // Not one top-level key - "false for no top-level key": { - src: []byte(`{}`), - allowedKeys: []string{"claim"}, - expResult: false, - }, - "false for multiple top-level keys": { - src: []byte(`{"claim": {}, "and_swap": {}}`), - allowedKeys: []string{"claim"}, - expResult: false, - }, - - // Wrong top-level key - "wrong top-level key 1": { - src: []byte(`{"claim": {}}`), - allowedKeys: []string{""}, - expResult: false, - }, - "wrong top-level key 2": { - src: []byte(`{"claim": {}}`), - allowedKeys: []string{"swap", "burn", "mint"}, - expResult: false, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - exists, gotErr := isJSONObjectWithTopLevelKey(spec.src, spec.allowedKeys) - if spec.expErr != nil { - assert.ErrorIs(t, gotErr, spec.expErr) - return - } - require.NoError(t, gotErr) - assert.Equal(t, spec.expResult, exists) - }) - } -} - -func TestDuplicateKeyGivesSameResult(t *testing.T) { - jsonBytes := []byte(`{"event⑨thing": "foo", "event⑨thing":"bar"}`) - for i := 0; i < 10000; i++ { - document := map[string]interface{}{} - require.NoError(t, json.Unmarshal(jsonBytes, &document)) - assert.Equal(t, "bar", document["event⑨thing"]) - } -} diff --git a/x/wasm/types/keys.go b/x/wasm/types/keys.go deleted file mode 100644 index 4f60587..0000000 --- a/x/wasm/types/keys.go +++ /dev/null @@ -1,131 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" -) - -const ( - // ModuleName is the name of the contract module - ModuleName = "wasm" - - // StoreKey is the string store representation - StoreKey = ModuleName - - // TStoreKey is the string transient store representation - TStoreKey = "transient_" + ModuleName - - // QuerierRoute is the querier route for the wasm module - QuerierRoute = ModuleName - - // RouterKey is the msg router key for the wasm module - RouterKey = ModuleName -) - -var ( - CodeKeyPrefix = []byte{0x01} - ContractKeyPrefix = []byte{0x02} - ContractStorePrefix = []byte{0x03} - SequenceKeyPrefix = []byte{0x04} - ContractCodeHistoryElementPrefix = []byte{0x05} - ContractByCodeIDAndCreatedSecondaryIndexPrefix = []byte{0x06} - PinnedCodeIndexPrefix = []byte{0x07} - TXCounterPrefix = []byte{0x08} - ContractsByCreatorPrefix = []byte{0x09} - ParamsKey = []byte{0x10} - - KeyLastCodeID = append(SequenceKeyPrefix, []byte("lastCodeId")...) - KeyLastInstanceID = append(SequenceKeyPrefix, []byte("lastContractId")...) -) - -// GetCodeKey constructs the key for retreiving the ID for the WASM code -func GetCodeKey(codeID uint64) []byte { - contractIDBz := sdk.Uint64ToBigEndian(codeID) - return append(CodeKeyPrefix, contractIDBz...) -} - -// GetContractAddressKey returns the key for the WASM contract instance -func GetContractAddressKey(addr sdk.AccAddress) []byte { - return append(ContractKeyPrefix, addr...) -} - -// GetContractsByCreatorPrefix returns the contracts by creator prefix for the WASM contract instance -func GetContractsByCreatorPrefix(addr sdk.AccAddress) []byte { - bz := address.MustLengthPrefix(addr) - return append(ContractsByCreatorPrefix, bz...) -} - -// GetContractStorePrefix returns the store prefix for the WASM contract instance -func GetContractStorePrefix(addr sdk.AccAddress) []byte { - return append(ContractStorePrefix, addr...) -} - -// GetContractByCreatedSecondaryIndexKey returns the key for the secondary index: -// `` -func GetContractByCreatedSecondaryIndexKey(contractAddr sdk.AccAddress, c ContractCodeHistoryEntry) []byte { - prefix := GetContractByCodeIDSecondaryIndexPrefix(c.CodeID) - prefixLen := len(prefix) - contractAddrLen := len(contractAddr) - r := make([]byte, prefixLen+AbsoluteTxPositionLen+contractAddrLen) - copy(r[0:], prefix) - copy(r[prefixLen:], c.Updated.Bytes()) - copy(r[prefixLen+AbsoluteTxPositionLen:], contractAddr) - return r -} - -// GetContractByCodeIDSecondaryIndexPrefix returns the prefix for the second index: `` -func GetContractByCodeIDSecondaryIndexPrefix(codeID uint64) []byte { - prefixLen := len(ContractByCodeIDAndCreatedSecondaryIndexPrefix) - const codeIDLen = 8 - r := make([]byte, prefixLen+codeIDLen) - copy(r[0:], ContractByCodeIDAndCreatedSecondaryIndexPrefix) - copy(r[prefixLen:], sdk.Uint64ToBigEndian(codeID)) - return r -} - -// GetContractByCreatorSecondaryIndexKey returns the key for the second index: `` -func GetContractByCreatorSecondaryIndexKey(bz []byte, position []byte, contractAddr sdk.AccAddress) []byte { - prefixBytes := GetContractsByCreatorPrefix(bz) - lenPrefixBytes := len(prefixBytes) - r := make([]byte, lenPrefixBytes+AbsoluteTxPositionLen+len(contractAddr)) - - copy(r[:lenPrefixBytes], prefixBytes) - copy(r[lenPrefixBytes:lenPrefixBytes+AbsoluteTxPositionLen], position) - copy(r[lenPrefixBytes+AbsoluteTxPositionLen:], contractAddr) - - return r -} - -// GetContractCodeHistoryElementKey returns the key a contract code history entry: `` -func GetContractCodeHistoryElementKey(contractAddr sdk.AccAddress, pos uint64) []byte { - prefix := GetContractCodeHistoryElementPrefix(contractAddr) - prefixLen := len(prefix) - r := make([]byte, prefixLen+8) - copy(r[0:], prefix) - copy(r[prefixLen:], sdk.Uint64ToBigEndian(pos)) - return r -} - -// GetContractCodeHistoryElementPrefix returns the key prefix for a contract code history entry: `` -func GetContractCodeHistoryElementPrefix(contractAddr sdk.AccAddress) []byte { - prefixLen := len(ContractCodeHistoryElementPrefix) - contractAddrLen := len(contractAddr) - r := make([]byte, prefixLen+contractAddrLen) - copy(r[0:], ContractCodeHistoryElementPrefix) - copy(r[prefixLen:], contractAddr) - return r -} - -// GetPinnedCodeIndexPrefix returns the key prefix for a code id pinned into the wasmvm cache -func GetPinnedCodeIndexPrefix(codeID uint64) []byte { - prefixLen := len(PinnedCodeIndexPrefix) - r := make([]byte, prefixLen+8) - copy(r[0:], PinnedCodeIndexPrefix) - copy(r[prefixLen:], sdk.Uint64ToBigEndian(codeID)) - return r -} - -// ParsePinnedCodeIndex converts the serialized code ID back. -func ParsePinnedCodeIndex(s []byte) uint64 { - return sdk.BigEndianToUint64(s) -} diff --git a/x/wasm/types/keys_test.go b/x/wasm/types/keys_test.go deleted file mode 100644 index a5cbce7..0000000 --- a/x/wasm/types/keys_test.go +++ /dev/null @@ -1,148 +0,0 @@ -package types - -import ( - "bytes" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestGetContractByCodeIDSecondaryIndexPrefix(t *testing.T) { - specs := map[string]struct { - src uint64 - exp []byte - }{ - "small number": { - src: 1, - exp: []byte{6, 0, 0, 0, 0, 0, 0, 0, 1}, - }, - "big number": { - src: 1 << (8 * 7), - exp: []byte{6, 1, 0, 0, 0, 0, 0, 0, 0}, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - got := GetContractByCodeIDSecondaryIndexPrefix(spec.src) - assert.Equal(t, spec.exp, got) - }) - } -} - -func TestGetContractCodeHistoryElementPrefix(t *testing.T) { - // test that contract addresses of 20 length are still supported - addr := bytes.Repeat([]byte{4}, 20) - got := GetContractCodeHistoryElementPrefix(addr) - exp := []byte{ - 5, // prefix - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, // address 20 bytes - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - } - assert.Equal(t, exp, got) - - addr = bytes.Repeat([]byte{4}, ContractAddrLen) - got = GetContractCodeHistoryElementPrefix(addr) - exp = []byte{ - 5, // prefix - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, // address 32 bytes - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, - } - assert.Equal(t, exp, got) -} - -func TestGetContractByCreatedSecondaryIndexKey(t *testing.T) { - e := ContractCodeHistoryEntry{ - CodeID: 1, - Updated: &AbsoluteTxPosition{2 + 1<<(8*7), 3 + 1<<(8*7)}, - } - - // test that contract addresses of 20 length are still supported - addr := bytes.Repeat([]byte{4}, 20) - got := GetContractByCreatedSecondaryIndexKey(addr, e) - exp := []byte{ - 6, // prefix - 0, 0, 0, 0, 0, 0, 0, 1, // codeID - 1, 0, 0, 0, 0, 0, 0, 2, // height - 1, 0, 0, 0, 0, 0, 0, 3, // index - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, // address 32 bytes - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - } - assert.Equal(t, exp, got) - - addr = bytes.Repeat([]byte{4}, ContractAddrLen) - got = GetContractByCreatedSecondaryIndexKey(addr, e) - exp = []byte{ - 6, // prefix - 0, 0, 0, 0, 0, 0, 0, 1, // codeID - 1, 0, 0, 0, 0, 0, 0, 2, // height - 1, 0, 0, 0, 0, 0, 0, 3, // index - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, // address 32 bytes - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, - } - assert.Equal(t, exp, got) -} - -func TestGetContractByCreatorSecondaryIndexKey(t *testing.T) { - creatorAddr := bytes.Repeat([]byte{4}, 20) - e := ContractCodeHistoryEntry{ - CodeID: 1, - Updated: &AbsoluteTxPosition{2 + 1<<(8*7), 3 + 1<<(8*7)}, - } - - // test that contract addresses of 20 length are still supported - contractAddr := bytes.Repeat([]byte{4}, 20) - got := GetContractByCreatorSecondaryIndexKey(creatorAddr, e.Updated.Bytes(), contractAddr) - exp := []byte{ - 9, // prefix - 20, // creator address length - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, // creator address with fixed length prefix - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 1, 0, 0, 0, 0, 0, 0, 2, // height - 1, 0, 0, 0, 0, 0, 0, 3, // index - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, // address 20 bytes - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - } - assert.Equal(t, exp, got) - - // test that contract addresses of 32 length are still supported - contractAddr = bytes.Repeat([]byte{4}, 32) - got = GetContractByCreatorSecondaryIndexKey(creatorAddr, e.Updated.Bytes(), contractAddr) - exp = []byte{ - 9, // prefix - 20, // creator address length - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, // creator address with fixed length prefix - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 1, 0, 0, 0, 0, 0, 0, 2, // height - 1, 0, 0, 0, 0, 0, 0, 3, // index - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, // address 32 bytes - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, - } - assert.Equal(t, exp, got) - - // test that creator is contract addresses of 32 length - contractAddr = bytes.Repeat([]byte{4}, 32) - creatorAddr = bytes.Repeat([]byte{8}, 32) - got = GetContractByCreatorSecondaryIndexKey(creatorAddr, e.Updated.Bytes(), contractAddr) - exp = []byte{ - 9, // prefix - 32, // creator address length - 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, // creator address is a contract address - 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, - 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, - 8, 8, - 1, 0, 0, 0, 0, 0, 0, 2, // height - 1, 0, 0, 0, 0, 0, 0, 3, // index - - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, // address 32 bytes - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, - } - assert.Equal(t, exp, got) -} diff --git a/x/wasm/types/params.go b/x/wasm/types/params.go deleted file mode 100644 index d06ba7e..0000000 --- a/x/wasm/types/params.go +++ /dev/null @@ -1,208 +0,0 @@ -package types - -import ( - "encoding/json" - "fmt" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/gogoproto/jsonpb" - "github.com/pkg/errors" - "gopkg.in/yaml.v2" -) - -var AllAccessTypes = []AccessType{ - AccessTypeNobody, - AccessTypeOnlyAddress, - AccessTypeAnyOfAddresses, - AccessTypeEverybody, -} - -func (a AccessType) With(addrs ...sdk.AccAddress) AccessConfig { - switch a { - case AccessTypeNobody: - return AllowNobody - case AccessTypeOnlyAddress: - if n := len(addrs); n != 1 { - panic(fmt.Sprintf("expected exactly 1 address but got %d", n)) - } - if err := sdk.VerifyAddressFormat(addrs[0]); err != nil { - panic(err) - } - return AccessConfig{Permission: AccessTypeOnlyAddress, Address: addrs[0].String()} - case AccessTypeEverybody: - return AllowEverybody - case AccessTypeAnyOfAddresses: - bech32Addrs := make([]string, len(addrs)) - for i, v := range addrs { - bech32Addrs[i] = v.String() - } - if err := assertValidAddresses(bech32Addrs); err != nil { - panic(errorsmod.Wrap(err, "addresses")) - } - return AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: bech32Addrs} - } - panic("unsupported access type") -} - -func (a AccessType) String() string { - switch a { - case AccessTypeNobody: - return "Nobody" - case AccessTypeOnlyAddress: - return "OnlyAddress" - case AccessTypeEverybody: - return "Everybody" - case AccessTypeAnyOfAddresses: - return "AnyOfAddresses" - } - return "Unspecified" -} - -func (a *AccessType) UnmarshalText(text []byte) error { - for _, v := range AllAccessTypes { - if v.String() == string(text) { - *a = v - return nil - } - } - *a = AccessTypeUnspecified - return nil -} - -func (a AccessType) MarshalText() ([]byte, error) { - return []byte(a.String()), nil -} - -func (a *AccessType) MarshalJSONPB(_ *jsonpb.Marshaler) ([]byte, error) { - return json.Marshal(a) -} - -func (a *AccessType) UnmarshalJSONPB(_ *jsonpb.Unmarshaler, data []byte) error { - return json.Unmarshal(data, a) -} - -func (a AccessConfig) Equals(o AccessConfig) bool { - return a.Permission == o.Permission && a.Address == o.Address -} - -var ( - DefaultUploadAccess = AllowEverybody - AllowEverybody = AccessConfig{Permission: AccessTypeEverybody} - AllowNobody = AccessConfig{Permission: AccessTypeNobody} -) - -// DefaultParams returns default wasm parameters -func DefaultParams() Params { - return Params{ - CodeUploadAccess: AllowEverybody, - InstantiateDefaultPermission: AccessTypeEverybody, - } -} - -func (p Params) String() string { - out, err := yaml.Marshal(p) - if err != nil { - panic(err) - } - return string(out) -} - -// ValidateBasic performs basic validation on wasm parameters -func (p Params) ValidateBasic() error { - if err := validateAccessType(p.InstantiateDefaultPermission); err != nil { - return errors.Wrap(err, "instantiate default permission") - } - if err := validateAccessConfig(p.CodeUploadAccess); err != nil { - return errors.Wrap(err, "upload access") - } - return nil -} - -func validateAccessConfig(i interface{}) error { - v, ok := i.(AccessConfig) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - return v.ValidateBasic() -} - -func validateAccessType(i interface{}) error { - a, ok := i.(AccessType) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - if a == AccessTypeUnspecified { - return errorsmod.Wrap(ErrEmpty, "type") - } - for _, v := range AllAccessTypes { - if v == a { - return nil - } - } - return errorsmod.Wrapf(ErrInvalid, "unknown type: %q", a) -} - -// ValidateBasic performs basic validation -func (a AccessConfig) ValidateBasic() error { - switch a.Permission { - case AccessTypeUnspecified: - return errorsmod.Wrap(ErrEmpty, "type") - case AccessTypeNobody, AccessTypeEverybody: - if len(a.Address) != 0 { - return errorsmod.Wrap(ErrInvalid, "address not allowed for this type") - } - return nil - case AccessTypeOnlyAddress: - if len(a.Addresses) != 0 { - return ErrInvalid.Wrap("addresses field set") - } - _, err := sdk.AccAddressFromBech32(a.Address) - return err - case AccessTypeAnyOfAddresses: - if a.Address != "" { - return ErrInvalid.Wrap("address field set") - } - return errorsmod.Wrap(assertValidAddresses(a.Addresses), "addresses") - } - return errorsmod.Wrapf(ErrInvalid, "unknown type: %q", a.Permission) -} - -func assertValidAddresses(addrs []string) error { - if len(addrs) == 0 { - return ErrEmpty - } - idx := make(map[string]struct{}, len(addrs)) - for _, a := range addrs { - if _, err := sdk.AccAddressFromBech32(a); err != nil { - return errorsmod.Wrapf(err, "address: %s", a) - } - if _, exists := idx[a]; exists { - return ErrDuplicate.Wrapf("address: %s", a) - } - idx[a] = struct{}{} - } - return nil -} - -// Allowed returns if permission includes the actor. -// Actor address must be valid and not nil -func (a AccessConfig) Allowed(actor sdk.AccAddress) bool { - switch a.Permission { - case AccessTypeNobody: - return false - case AccessTypeEverybody: - return true - case AccessTypeOnlyAddress: - return a.Address == actor.String() - case AccessTypeAnyOfAddresses: - for _, v := range a.Addresses { - if v == actor.String() { - return true - } - } - return false - default: - panic("unknown type") - } -} diff --git a/x/wasm/types/params_legacy.go b/x/wasm/types/params_legacy.go deleted file mode 100644 index db38cb8..0000000 --- a/x/wasm/types/params_legacy.go +++ /dev/null @@ -1,26 +0,0 @@ -/* -NOTE: Usage of x/params to manage parameters is deprecated in favor of x/gov -controlled execution of MsgUpdateParams messages. These types remains solely -for migration purposes and will be removed in a future release. -*/ -package types - -import paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - -var ( - ParamStoreKeyUploadAccess = []byte("uploadAccess") - ParamStoreKeyInstantiateAccess = []byte("instantiateAccess") -) - -// Deprecated: Type declaration for parameters -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) -} - -// ParamSetPairs returns the parameter set pairs. -func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{ - paramtypes.NewParamSetPair(ParamStoreKeyUploadAccess, &p.CodeUploadAccess, validateAccessConfig), - paramtypes.NewParamSetPair(ParamStoreKeyInstantiateAccess, &p.InstantiateDefaultPermission, validateAccessType), - } -} diff --git a/x/wasm/types/params_test.go b/x/wasm/types/params_test.go deleted file mode 100644 index 77ac8b7..0000000 --- a/x/wasm/types/params_test.go +++ /dev/null @@ -1,306 +0,0 @@ -package types - -import ( - "bytes" - "encoding/json" - "testing" - - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestValidateParams(t *testing.T) { - var ( - anyAddress sdk.AccAddress = make([]byte, ContractAddrLen) - otherAddress sdk.AccAddress = bytes.Repeat([]byte{1}, ContractAddrLen) - invalidAddress = "invalid address" - ) - - specs := map[string]struct { - src Params - expErr bool - }{ - "all good with defaults": { - src: DefaultParams(), - }, - "all good with nobody": { - src: Params{ - CodeUploadAccess: AllowNobody, - InstantiateDefaultPermission: AccessTypeNobody, - }, - }, - "all good with everybody": { - src: Params{ - CodeUploadAccess: AllowEverybody, - InstantiateDefaultPermission: AccessTypeEverybody, - }, - }, - "all good with only address": { - src: Params{ - CodeUploadAccess: AccessTypeOnlyAddress.With(anyAddress), - InstantiateDefaultPermission: AccessTypeOnlyAddress, - }, - }, - "all good with anyOf address": { - src: Params{ - CodeUploadAccess: AccessTypeAnyOfAddresses.With(anyAddress), - InstantiateDefaultPermission: AccessTypeAnyOfAddresses, - }, - }, - "all good with anyOf addresses": { - src: Params{ - CodeUploadAccess: AccessTypeAnyOfAddresses.With(anyAddress, otherAddress), - InstantiateDefaultPermission: AccessTypeAnyOfAddresses, - }, - }, - "reject empty type in instantiate permission": { - src: Params{ - CodeUploadAccess: AllowNobody, - }, - expErr: true, - }, - "reject unknown type in instantiate": { - src: Params{ - CodeUploadAccess: AllowNobody, - InstantiateDefaultPermission: 1111, - }, - expErr: true, - }, - "reject invalid address in only address": { - src: Params{ - CodeUploadAccess: AccessConfig{Permission: AccessTypeOnlyAddress, Address: invalidAddress}, - InstantiateDefaultPermission: AccessTypeOnlyAddress, - }, - expErr: true, - }, - "reject wrong field addresses in only address": { - src: Params{ - CodeUploadAccess: AccessConfig{Permission: AccessTypeOnlyAddress, Address: anyAddress.String(), Addresses: []string{anyAddress.String()}}, - InstantiateDefaultPermission: AccessTypeOnlyAddress, - }, - expErr: true, - }, - "reject CodeUploadAccess Everybody with obsolete address": { - src: Params{ - CodeUploadAccess: AccessConfig{Permission: AccessTypeEverybody, Address: anyAddress.String()}, - InstantiateDefaultPermission: AccessTypeOnlyAddress, - }, - expErr: true, - }, - "reject CodeUploadAccess Nobody with obsolete address": { - src: Params{ - CodeUploadAccess: AccessConfig{Permission: AccessTypeNobody, Address: anyAddress.String()}, - InstantiateDefaultPermission: AccessTypeOnlyAddress, - }, - expErr: true, - }, - "reject empty CodeUploadAccess": { - src: Params{ - InstantiateDefaultPermission: AccessTypeOnlyAddress, - }, - expErr: true, - }, - "reject undefined permission in CodeUploadAccess": { - src: Params{ - CodeUploadAccess: AccessConfig{Permission: AccessTypeUnspecified}, - InstantiateDefaultPermission: AccessTypeOnlyAddress, - }, - expErr: true, - }, - "reject empty addresses in any of addresses": { - src: Params{ - CodeUploadAccess: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{}}, - InstantiateDefaultPermission: AccessTypeAnyOfAddresses, - }, - expErr: true, - }, - "reject addresses not set in any of addresses": { - src: Params{ - CodeUploadAccess: AccessConfig{Permission: AccessTypeAnyOfAddresses}, - InstantiateDefaultPermission: AccessTypeAnyOfAddresses, - }, - expErr: true, - }, - "reject invalid address in any of addresses": { - src: Params{ - CodeUploadAccess: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{invalidAddress}}, - InstantiateDefaultPermission: AccessTypeAnyOfAddresses, - }, - expErr: true, - }, - "reject duplicate address in any of addresses": { - src: Params{ - CodeUploadAccess: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{anyAddress.String(), anyAddress.String()}}, - InstantiateDefaultPermission: AccessTypeAnyOfAddresses, - }, - expErr: true, - }, - "reject wrong field address in any of addresses": { - src: Params{ - CodeUploadAccess: AccessConfig{Permission: AccessTypeAnyOfAddresses, Address: anyAddress.String(), Addresses: []string{anyAddress.String()}}, - InstantiateDefaultPermission: AccessTypeAnyOfAddresses, - }, - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestAccessTypeMarshalJson(t *testing.T) { - specs := map[string]struct { - src AccessType - exp string - }{ - "Unspecified": {src: AccessTypeUnspecified, exp: `"Unspecified"`}, - "Nobody": {src: AccessTypeNobody, exp: `"Nobody"`}, - "OnlyAddress": {src: AccessTypeOnlyAddress, exp: `"OnlyAddress"`}, - "AccessTypeAnyOfAddresses": {src: AccessTypeAnyOfAddresses, exp: `"AnyOfAddresses"`}, - "Everybody": {src: AccessTypeEverybody, exp: `"Everybody"`}, - "unknown": {src: 999, exp: `"Unspecified"`}, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - got, err := json.Marshal(spec.src) - require.NoError(t, err) - assert.Equal(t, []byte(spec.exp), got) - }) - } -} - -func TestAccessTypeUnmarshalJson(t *testing.T) { - specs := map[string]struct { - src string - exp AccessType - }{ - "Unspecified": {src: `"Unspecified"`, exp: AccessTypeUnspecified}, - "Nobody": {src: `"Nobody"`, exp: AccessTypeNobody}, - "OnlyAddress": {src: `"OnlyAddress"`, exp: AccessTypeOnlyAddress}, - "AnyOfAddresses": {src: `"AnyOfAddresses"`, exp: AccessTypeAnyOfAddresses}, - "Everybody": {src: `"Everybody"`, exp: AccessTypeEverybody}, - "unknown": {src: `""`, exp: AccessTypeUnspecified}, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - var got AccessType - err := json.Unmarshal([]byte(spec.src), &got) - require.NoError(t, err) - assert.Equal(t, spec.exp, got) - }) - } -} - -func TestParamsUnmarshalJson(t *testing.T) { - specs := map[string]struct { - src string - exp Params - }{ - "defaults": { - src: `{"code_upload_access": {"permission": "Everybody"}, - "instantiate_default_permission": "Everybody"}`, - exp: DefaultParams(), - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - var val Params - interfaceRegistry := codectypes.NewInterfaceRegistry() - marshaler := codec.NewProtoCodec(interfaceRegistry) - - err := marshaler.UnmarshalJSON([]byte(spec.src), &val) - require.NoError(t, err) - assert.Equal(t, spec.exp, val) - }) - } -} - -func TestAccessTypeWith(t *testing.T) { - myAddress := sdk.AccAddress(randBytes(SDKAddrLen)) - myOtherAddress := sdk.AccAddress(randBytes(SDKAddrLen)) - specs := map[string]struct { - src AccessType - addrs []sdk.AccAddress - exp AccessConfig - expPanic bool - }{ - "nobody": { - src: AccessTypeNobody, - exp: AccessConfig{Permission: AccessTypeNobody}, - }, - "nobody with address": { - src: AccessTypeNobody, - addrs: []sdk.AccAddress{myAddress}, - exp: AccessConfig{Permission: AccessTypeNobody}, - }, - "everybody": { - src: AccessTypeEverybody, - exp: AccessConfig{Permission: AccessTypeEverybody}, - }, - "everybody with address": { - src: AccessTypeEverybody, - addrs: []sdk.AccAddress{myAddress}, - exp: AccessConfig{Permission: AccessTypeEverybody}, - }, - "only address without address": { - src: AccessTypeOnlyAddress, - expPanic: true, - }, - "only address with address": { - src: AccessTypeOnlyAddress, - addrs: []sdk.AccAddress{myAddress}, - exp: AccessConfig{Permission: AccessTypeOnlyAddress, Address: myAddress.String()}, - }, - "only address with invalid address": { - src: AccessTypeOnlyAddress, - addrs: []sdk.AccAddress{nil}, - expPanic: true, - }, - "any of address without address": { - src: AccessTypeAnyOfAddresses, - expPanic: true, - }, - "any of address with single address": { - src: AccessTypeAnyOfAddresses, - addrs: []sdk.AccAddress{myAddress}, - exp: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{myAddress.String()}}, - }, - "any of address with multiple addresses": { - src: AccessTypeAnyOfAddresses, - addrs: []sdk.AccAddress{myAddress, myOtherAddress}, - exp: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{myAddress.String(), myOtherAddress.String()}}, - }, - "any of address with duplicate addresses": { - src: AccessTypeAnyOfAddresses, - addrs: []sdk.AccAddress{myAddress, myAddress}, - expPanic: true, - }, - "any of address with invalid address": { - src: AccessTypeAnyOfAddresses, - addrs: []sdk.AccAddress{nil}, - expPanic: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - if !spec.expPanic { - got := spec.src.With(spec.addrs...) - assert.Equal(t, spec.exp, got) - return - } - assert.Panics(t, func() { - spec.src.With(spec.addrs...) - }) - }) - } -} diff --git a/x/wasm/types/proposal.go b/x/wasm/types/proposal.go deleted file mode 100644 index 468f45b..0000000 --- a/x/wasm/types/proposal.go +++ /dev/null @@ -1,986 +0,0 @@ -package types - -import ( - "encoding/base64" - "encoding/hex" - "fmt" - "strings" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" -) - -type ProposalType string - -const ( - ProposalTypeStoreCode ProposalType = "StoreCode" - ProposalTypeInstantiateContract ProposalType = "InstantiateContract" - ProposalTypeInstantiateContract2 ProposalType = "InstantiateContract2" - ProposalTypeMigrateContract ProposalType = "MigrateContract" - ProposalTypeSudoContract ProposalType = "SudoContract" - ProposalTypeExecuteContract ProposalType = "ExecuteContract" - ProposalTypeUpdateAdmin ProposalType = "UpdateAdmin" - ProposalTypeClearAdmin ProposalType = "ClearAdmin" - ProposalTypePinCodes ProposalType = "PinCodes" - ProposalTypeUnpinCodes ProposalType = "UnpinCodes" - ProposalTypeUpdateInstantiateConfig ProposalType = "UpdateInstantiateConfig" - ProposalTypeStoreAndInstantiateContractProposal ProposalType = "StoreAndInstantiateContract" -) - -// DisableAllProposals contains no wasm gov types. -var DisableAllProposals []ProposalType - -// EnableAllProposals contains all wasm gov types as keys. -var EnableAllProposals = []ProposalType{ - ProposalTypeStoreCode, - ProposalTypeInstantiateContract, - ProposalTypeInstantiateContract2, - ProposalTypeMigrateContract, - ProposalTypeSudoContract, - ProposalTypeExecuteContract, - ProposalTypeUpdateAdmin, - ProposalTypeClearAdmin, - ProposalTypePinCodes, - ProposalTypeUnpinCodes, - ProposalTypeUpdateInstantiateConfig, - ProposalTypeStoreAndInstantiateContractProposal, -} - -// ConvertToProposals maps each key to a ProposalType and returns a typed list. -// If any string is not a valid type (in this file), then return an error -func ConvertToProposals(keys []string) ([]ProposalType, error) { - valid := make(map[string]bool, len(EnableAllProposals)) - for _, key := range EnableAllProposals { - valid[string(key)] = true - } - - proposals := make([]ProposalType, len(keys)) - for i, key := range keys { - if _, ok := valid[key]; !ok { - return nil, errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "'%s' is not a valid ProposalType", key) - } - proposals[i] = ProposalType(key) - } - return proposals, nil -} - -func init() { // register new content types with the sdk - v1beta1.RegisterProposalType(string(ProposalTypeStoreCode)) - v1beta1.RegisterProposalType(string(ProposalTypeInstantiateContract)) - v1beta1.RegisterProposalType(string(ProposalTypeInstantiateContract2)) - v1beta1.RegisterProposalType(string(ProposalTypeMigrateContract)) - v1beta1.RegisterProposalType(string(ProposalTypeSudoContract)) - v1beta1.RegisterProposalType(string(ProposalTypeExecuteContract)) - v1beta1.RegisterProposalType(string(ProposalTypeUpdateAdmin)) - v1beta1.RegisterProposalType(string(ProposalTypeClearAdmin)) - v1beta1.RegisterProposalType(string(ProposalTypePinCodes)) - v1beta1.RegisterProposalType(string(ProposalTypeUnpinCodes)) - v1beta1.RegisterProposalType(string(ProposalTypeUpdateInstantiateConfig)) - v1beta1.RegisterProposalType(string(ProposalTypeStoreAndInstantiateContractProposal)) -} - -func NewStoreCodeProposal( - title string, - description string, - runAs string, - wasmBz []byte, - permission *AccessConfig, - unpinCode bool, - source string, - builder string, - codeHash []byte, -) *StoreCodeProposal { - return &StoreCodeProposal{title, description, runAs, wasmBz, permission, unpinCode, source, builder, codeHash} -} - -// ProposalRoute returns the routing key of a parameter change proposal. -func (p StoreCodeProposal) ProposalRoute() string { return RouterKey } - -// GetTitle returns the title of the proposal -func (p *StoreCodeProposal) GetTitle() string { return p.Title } - -// GetDescription returns the human readable description of the proposal -func (p StoreCodeProposal) GetDescription() string { return p.Description } - -// ProposalType returns the type -func (p StoreCodeProposal) ProposalType() string { return string(ProposalTypeStoreCode) } - -// ValidateBasic validates the proposal -func (p StoreCodeProposal) ValidateBasic() error { - if err := validateProposalCommons(p.Title, p.Description); err != nil { - return err - } - if _, err := sdk.AccAddressFromBech32(p.RunAs); err != nil { - return errorsmod.Wrap(err, "run as") - } - - if err := validateWasmCode(p.WASMByteCode, MaxProposalWasmSize); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "code bytes %s", err.Error()) - } - - if p.InstantiatePermission != nil { - if err := p.InstantiatePermission.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "instantiate permission") - } - } - - if err := ValidateVerificationInfo(p.Source, p.Builder, p.CodeHash); err != nil { - return errorsmod.Wrapf(err, "code verification info") - } - return nil -} - -// String implements the Stringer interface. -func (p StoreCodeProposal) String() string { - return fmt.Sprintf(`Store Code Proposal: - Title: %s - Description: %s - Run as: %s - WasmCode: %X - Source: %s - Builder: %s - Code Hash: %X -`, p.Title, p.Description, p.RunAs, p.WASMByteCode, p.Source, p.Builder, p.CodeHash) -} - -// MarshalYAML pretty prints the wasm byte code -func (p StoreCodeProposal) MarshalYAML() (interface{}, error) { - return struct { - Title string `yaml:"title"` - Description string `yaml:"description"` - RunAs string `yaml:"run_as"` - WASMByteCode string `yaml:"wasm_byte_code"` - InstantiatePermission *AccessConfig `yaml:"instantiate_permission"` - Source string `yaml:"source"` - Builder string `yaml:"builder"` - CodeHash string `yaml:"code_hash"` - }{ - Title: p.Title, - Description: p.Description, - RunAs: p.RunAs, - WASMByteCode: base64.StdEncoding.EncodeToString(p.WASMByteCode), - InstantiatePermission: p.InstantiatePermission, - Source: p.Source, - Builder: p.Builder, - CodeHash: hex.EncodeToString(p.CodeHash), - }, nil -} - -func NewInstantiateContractProposal( - title string, - description string, - runAs string, - admin string, - codeID uint64, - label string, - msg RawContractMessage, - funds sdk.Coins, -) *InstantiateContractProposal { - return &InstantiateContractProposal{title, description, runAs, admin, codeID, label, msg, funds} -} - -// ProposalRoute returns the routing key of a parameter change proposal. -func (p InstantiateContractProposal) ProposalRoute() string { return RouterKey } - -// GetTitle returns the title of the proposal -func (p *InstantiateContractProposal) GetTitle() string { return p.Title } - -// GetDescription returns the human readable description of the proposal -func (p InstantiateContractProposal) GetDescription() string { return p.Description } - -// ProposalType returns the type -func (p InstantiateContractProposal) ProposalType() string { - return string(ProposalTypeInstantiateContract) -} - -// ValidateBasic validates the proposal -func (p InstantiateContractProposal) ValidateBasic() error { - if err := validateProposalCommons(p.Title, p.Description); err != nil { - return err - } - if _, err := sdk.AccAddressFromBech32(p.RunAs); err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "run as") - } - - if p.CodeID == 0 { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "code id is required") - } - - if err := ValidateLabel(p.Label); err != nil { - return err - } - - if !p.Funds.IsValid() { - return sdkerrors.ErrInvalidCoins - } - - if len(p.Admin) != 0 { - if _, err := sdk.AccAddressFromBech32(p.Admin); err != nil { - return err - } - } - if err := p.Msg.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "payload msg") - } - return nil -} - -// String implements the Stringer interface. -func (p InstantiateContractProposal) String() string { - return fmt.Sprintf(`Instantiate Code Proposal: - Title: %s - Description: %s - Run as: %s - Admin: %s - Code id: %d - Label: %s - Msg: %q - Funds: %s -`, p.Title, p.Description, p.RunAs, p.Admin, p.CodeID, p.Label, p.Msg, p.Funds) -} - -// MarshalYAML pretty prints the init message -func (p InstantiateContractProposal) MarshalYAML() (interface{}, error) { - return struct { - Title string `yaml:"title"` - Description string `yaml:"description"` - RunAs string `yaml:"run_as"` - Admin string `yaml:"admin"` - CodeID uint64 `yaml:"code_id"` - Label string `yaml:"label"` - Msg string `yaml:"msg"` - Funds sdk.Coins `yaml:"funds"` - }{ - Title: p.Title, - Description: p.Description, - RunAs: p.RunAs, - Admin: p.Admin, - CodeID: p.CodeID, - Label: p.Label, - Msg: string(p.Msg), - Funds: p.Funds, - }, nil -} - -func NewInstantiateContract2Proposal( - title string, - description string, - runAs string, - admin string, - codeID uint64, - label string, - msg RawContractMessage, - funds sdk.Coins, - salt []byte, - fixMsg bool, -) *InstantiateContract2Proposal { - return &InstantiateContract2Proposal{title, description, runAs, admin, codeID, label, msg, funds, salt, fixMsg} -} - -// ProposalRoute returns the routing key of a parameter change proposal. -func (p InstantiateContract2Proposal) ProposalRoute() string { return RouterKey } - -// GetTitle returns the title of the proposal -func (p *InstantiateContract2Proposal) GetTitle() string { return p.Title } - -// GetDescription returns the human readable description of the proposal -func (p InstantiateContract2Proposal) GetDescription() string { return p.Description } - -// ProposalType returns the type -func (p InstantiateContract2Proposal) ProposalType() string { - return string(ProposalTypeInstantiateContract2) -} - -// ValidateBasic validates the proposal -func (p InstantiateContract2Proposal) ValidateBasic() error { - // Validate title and description - if err := validateProposalCommons(p.Title, p.Description); err != nil { - return err - } - // Validate run as - if _, err := sdk.AccAddressFromBech32(p.RunAs); err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "run as") - } - // Validate admin - if len(p.Admin) != 0 { - if _, err := sdk.AccAddressFromBech32(p.Admin); err != nil { - return err - } - } - // Validate codeid - if p.CodeID == 0 { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "code id is required") - } - // Validate label - if err := ValidateLabel(p.Label); err != nil { - return err - } - // Validate msg - if err := p.Msg.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "payload msg") - } - // Validate funds - if !p.Funds.IsValid() { - return sdkerrors.ErrInvalidCoins - } - // Validate salt - if len(p.Salt) == 0 { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "salt is required") - } - return nil -} - -// String implements the Stringer interface. -func (p InstantiateContract2Proposal) String() string { - return fmt.Sprintf(`Instantiate Code Proposal: - Title: %s - Description: %s - Run as: %s - Admin: %s - Code id: %d - Label: %s - Msg: %q - Funds: %s - Salt: %X -`, p.Title, p.Description, p.RunAs, p.Admin, p.CodeID, p.Label, p.Msg, p.Funds, p.Salt) -} - -// MarshalYAML pretty prints the init message -func (p InstantiateContract2Proposal) MarshalYAML() (interface{}, error) { - return struct { - Title string `yaml:"title"` - Description string `yaml:"description"` - RunAs string `yaml:"run_as"` - Admin string `yaml:"admin"` - CodeID uint64 `yaml:"code_id"` - Label string `yaml:"label"` - Msg string `yaml:"msg"` - Funds sdk.Coins `yaml:"funds"` - Salt string `yaml:"salt"` - }{ - Title: p.Title, - Description: p.Description, - RunAs: p.RunAs, - Admin: p.Admin, - CodeID: p.CodeID, - Label: p.Label, - Msg: string(p.Msg), - Funds: p.Funds, - Salt: base64.StdEncoding.EncodeToString(p.Salt), - }, nil -} - -func NewStoreAndInstantiateContractProposal( - title string, - description string, - runAs string, - wasmBz []byte, - source string, - builder string, - codeHash []byte, - permission *AccessConfig, - unpinCode bool, - admin string, - label string, - msg RawContractMessage, - funds sdk.Coins, -) *StoreAndInstantiateContractProposal { - return &StoreAndInstantiateContractProposal{ - Title: title, - Description: description, - RunAs: runAs, - WASMByteCode: wasmBz, - Source: source, - Builder: builder, - CodeHash: codeHash, - InstantiatePermission: permission, - UnpinCode: unpinCode, - Admin: admin, - Label: label, - Msg: msg, - Funds: funds, - } -} - -// ProposalRoute returns the routing key of a parameter change proposal. -func (p StoreAndInstantiateContractProposal) ProposalRoute() string { return RouterKey } - -// GetTitle returns the title of the proposal -func (p *StoreAndInstantiateContractProposal) GetTitle() string { return p.Title } - -// GetDescription returns the human readable description of the proposal -func (p StoreAndInstantiateContractProposal) GetDescription() string { return p.Description } - -// ProposalType returns the type -func (p StoreAndInstantiateContractProposal) ProposalType() string { - return string(ProposalTypeStoreAndInstantiateContractProposal) -} - -// ValidateBasic validates the proposal -func (p StoreAndInstantiateContractProposal) ValidateBasic() error { - if err := validateProposalCommons(p.Title, p.Description); err != nil { - return err - } - if _, err := sdk.AccAddressFromBech32(p.RunAs); err != nil { - return errorsmod.Wrap(err, "run as") - } - - if err := validateWasmCode(p.WASMByteCode, MaxProposalWasmSize); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "code bytes %s", err.Error()) - } - - if err := ValidateVerificationInfo(p.Source, p.Builder, p.CodeHash); err != nil { - return errorsmod.Wrap(err, "code info") - } - - if p.InstantiatePermission != nil { - if err := p.InstantiatePermission.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "instantiate permission") - } - } - - if err := ValidateLabel(p.Label); err != nil { - return err - } - - if !p.Funds.IsValid() { - return sdkerrors.ErrInvalidCoins - } - - if len(p.Admin) != 0 { - if _, err := sdk.AccAddressFromBech32(p.Admin); err != nil { - return err - } - } - if err := p.Msg.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "payload msg") - } - return nil -} - -// String implements the Stringer interface. -func (p StoreAndInstantiateContractProposal) String() string { - return fmt.Sprintf(`Store And Instantiate Coontract Proposal: - Title: %s - Description: %s - Run as: %s - WasmCode: %X - Source: %s - Builder: %s - Code Hash: %X - Instantiate permission: %s - Unpin code: %t - Admin: %s - Label: %s - Msg: %q - Funds: %s -`, p.Title, p.Description, p.RunAs, p.WASMByteCode, p.Source, p.Builder, p.CodeHash, p.InstantiatePermission, p.UnpinCode, p.Admin, p.Label, p.Msg, p.Funds) -} - -// MarshalYAML pretty prints the wasm byte code and the init message -func (p StoreAndInstantiateContractProposal) MarshalYAML() (interface{}, error) { - return struct { - Title string `yaml:"title"` - Description string `yaml:"description"` - RunAs string `yaml:"run_as"` - WASMByteCode string `yaml:"wasm_byte_code"` - Source string `yaml:"source"` - Builder string `yaml:"builder"` - CodeHash string `yaml:"code_hash"` - InstantiatePermission *AccessConfig `yaml:"instantiate_permission"` - UnpinCode bool `yaml:"unpin_code"` - Admin string `yaml:"admin"` - Label string `yaml:"label"` - Msg string `yaml:"msg"` - Funds sdk.Coins `yaml:"funds"` - }{ - Title: p.Title, - Description: p.Description, - RunAs: p.RunAs, - WASMByteCode: base64.StdEncoding.EncodeToString(p.WASMByteCode), - InstantiatePermission: p.InstantiatePermission, - UnpinCode: p.UnpinCode, - Admin: p.Admin, - Label: p.Label, - Source: p.Source, - Builder: p.Builder, - CodeHash: hex.EncodeToString(p.CodeHash), - Msg: string(p.Msg), - Funds: p.Funds, - }, nil -} - -func NewMigrateContractProposal( - title string, - description string, - contract string, - codeID uint64, - msg RawContractMessage, -) *MigrateContractProposal { - return &MigrateContractProposal{ - Title: title, - Description: description, - Contract: contract, - CodeID: codeID, - Msg: msg, - } -} - -// ProposalRoute returns the routing key of a parameter change proposal. -func (p MigrateContractProposal) ProposalRoute() string { return RouterKey } - -// GetTitle returns the title of the proposal -func (p *MigrateContractProposal) GetTitle() string { return p.Title } - -// GetDescription returns the human readable description of the proposal -func (p MigrateContractProposal) GetDescription() string { return p.Description } - -// ProposalType returns the type -func (p MigrateContractProposal) ProposalType() string { return string(ProposalTypeMigrateContract) } - -// ValidateBasic validates the proposal -func (p MigrateContractProposal) ValidateBasic() error { - if err := validateProposalCommons(p.Title, p.Description); err != nil { - return err - } - if p.CodeID == 0 { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "code_id is required") - } - if _, err := sdk.AccAddressFromBech32(p.Contract); err != nil { - return errorsmod.Wrap(err, "contract") - } - if err := p.Msg.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "payload msg") - } - return nil -} - -// String implements the Stringer interface. -func (p MigrateContractProposal) String() string { - return fmt.Sprintf(`Migrate Contract Proposal: - Title: %s - Description: %s - Contract: %s - Code id: %d - Msg: %q -`, p.Title, p.Description, p.Contract, p.CodeID, p.Msg) -} - -// MarshalYAML pretty prints the migrate message -func (p MigrateContractProposal) MarshalYAML() (interface{}, error) { - return struct { - Title string `yaml:"title"` - Description string `yaml:"description"` - Contract string `yaml:"contract"` - CodeID uint64 `yaml:"code_id"` - Msg string `yaml:"msg"` - }{ - Title: p.Title, - Description: p.Description, - Contract: p.Contract, - CodeID: p.CodeID, - Msg: string(p.Msg), - }, nil -} - -func NewSudoContractProposal( - title string, - description string, - contract string, - msg RawContractMessage, -) *SudoContractProposal { - return &SudoContractProposal{ - Title: title, - Description: description, - Contract: contract, - Msg: msg, - } -} - -// ProposalRoute returns the routing key of a parameter change proposal. -func (p SudoContractProposal) ProposalRoute() string { return RouterKey } - -// GetTitle returns the title of the proposal -func (p *SudoContractProposal) GetTitle() string { return p.Title } - -// GetDescription returns the human readable description of the proposal -func (p SudoContractProposal) GetDescription() string { return p.Description } - -// ProposalType returns the type -func (p SudoContractProposal) ProposalType() string { return string(ProposalTypeSudoContract) } - -// ValidateBasic validates the proposal -func (p SudoContractProposal) ValidateBasic() error { - if err := validateProposalCommons(p.Title, p.Description); err != nil { - return err - } - if _, err := sdk.AccAddressFromBech32(p.Contract); err != nil { - return errorsmod.Wrap(err, "contract") - } - if err := p.Msg.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "payload msg") - } - return nil -} - -// String implements the Stringer interface. -func (p SudoContractProposal) String() string { - return fmt.Sprintf(`Migrate Contract Proposal: - Title: %s - Description: %s - Contract: %s - Msg: %q -`, p.Title, p.Description, p.Contract, p.Msg) -} - -// MarshalYAML pretty prints the migrate message -func (p SudoContractProposal) MarshalYAML() (interface{}, error) { - return struct { - Title string `yaml:"title"` - Description string `yaml:"description"` - Contract string `yaml:"contract"` - Msg string `yaml:"msg"` - }{ - Title: p.Title, - Description: p.Description, - Contract: p.Contract, - Msg: string(p.Msg), - }, nil -} - -func NewExecuteContractProposal( - title string, - description string, - runAs string, - contract string, - msg RawContractMessage, - funds sdk.Coins, -) *ExecuteContractProposal { - return &ExecuteContractProposal{title, description, runAs, contract, msg, funds} -} - -// ProposalRoute returns the routing key of a parameter change proposal. -func (p ExecuteContractProposal) ProposalRoute() string { return RouterKey } - -// GetTitle returns the title of the proposal -func (p *ExecuteContractProposal) GetTitle() string { return p.Title } - -// GetDescription returns the human readable description of the proposal -func (p ExecuteContractProposal) GetDescription() string { return p.Description } - -// ProposalType returns the type -func (p ExecuteContractProposal) ProposalType() string { return string(ProposalTypeExecuteContract) } - -// ValidateBasic validates the proposal -func (p ExecuteContractProposal) ValidateBasic() error { - if err := validateProposalCommons(p.Title, p.Description); err != nil { - return err - } - if _, err := sdk.AccAddressFromBech32(p.Contract); err != nil { - return errorsmod.Wrap(err, "contract") - } - if _, err := sdk.AccAddressFromBech32(p.RunAs); err != nil { - return errorsmod.Wrap(err, "run as") - } - if !p.Funds.IsValid() { - return sdkerrors.ErrInvalidCoins - } - if err := p.Msg.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "payload msg") - } - return nil -} - -// String implements the Stringer interface. -func (p ExecuteContractProposal) String() string { - return fmt.Sprintf(`Migrate Contract Proposal: - Title: %s - Description: %s - Contract: %s - Run as: %s - Msg: %q - Funds: %s -`, p.Title, p.Description, p.Contract, p.RunAs, p.Msg, p.Funds) -} - -// MarshalYAML pretty prints the migrate message -func (p ExecuteContractProposal) MarshalYAML() (interface{}, error) { - return struct { - Title string `yaml:"title"` - Description string `yaml:"description"` - Contract string `yaml:"contract"` - Msg string `yaml:"msg"` - RunAs string `yaml:"run_as"` - Funds sdk.Coins `yaml:"funds"` - }{ - Title: p.Title, - Description: p.Description, - Contract: p.Contract, - Msg: string(p.Msg), - RunAs: p.RunAs, - Funds: p.Funds, - }, nil -} - -func NewUpdateAdminProposal( - title string, - description string, - newAdmin string, - contract string, -) *UpdateAdminProposal { - return &UpdateAdminProposal{title, description, newAdmin, contract} -} - -// ProposalRoute returns the routing key of a parameter change proposal. -func (p UpdateAdminProposal) ProposalRoute() string { return RouterKey } - -// GetTitle returns the title of the proposal -func (p *UpdateAdminProposal) GetTitle() string { return p.Title } - -// GetDescription returns the human readable description of the proposal -func (p UpdateAdminProposal) GetDescription() string { return p.Description } - -// ProposalType returns the type -func (p UpdateAdminProposal) ProposalType() string { return string(ProposalTypeUpdateAdmin) } - -// ValidateBasic validates the proposal -func (p UpdateAdminProposal) ValidateBasic() error { - if err := validateProposalCommons(p.Title, p.Description); err != nil { - return err - } - if _, err := sdk.AccAddressFromBech32(p.Contract); err != nil { - return errorsmod.Wrap(err, "contract") - } - if _, err := sdk.AccAddressFromBech32(p.NewAdmin); err != nil { - return errorsmod.Wrap(err, "new admin") - } - return nil -} - -// String implements the Stringer interface. -func (p UpdateAdminProposal) String() string { - return fmt.Sprintf(`Update Contract Admin Proposal: - Title: %s - Description: %s - Contract: %s - New Admin: %s -`, p.Title, p.Description, p.Contract, p.NewAdmin) -} - -func NewClearAdminProposal( - title string, - description string, - contract string, -) *ClearAdminProposal { - return &ClearAdminProposal{title, description, contract} -} - -// ProposalRoute returns the routing key of a parameter change proposal. -func (p ClearAdminProposal) ProposalRoute() string { return RouterKey } - -// GetTitle returns the title of the proposal -func (p *ClearAdminProposal) GetTitle() string { return p.Title } - -// GetDescription returns the human readable description of the proposal -func (p ClearAdminProposal) GetDescription() string { return p.Description } - -// ProposalType returns the type -func (p ClearAdminProposal) ProposalType() string { return string(ProposalTypeClearAdmin) } - -// ValidateBasic validates the proposal -func (p ClearAdminProposal) ValidateBasic() error { - if err := validateProposalCommons(p.Title, p.Description); err != nil { - return err - } - if _, err := sdk.AccAddressFromBech32(p.Contract); err != nil { - return errorsmod.Wrap(err, "contract") - } - return nil -} - -// String implements the Stringer interface. -func (p ClearAdminProposal) String() string { - return fmt.Sprintf(`Clear Contract Admin Proposal: - Title: %s - Description: %s - Contract: %s -`, p.Title, p.Description, p.Contract) -} - -func NewPinCodesProposal( - title string, - description string, - codeIDs []uint64, -) *PinCodesProposal { - return &PinCodesProposal{ - Title: title, - Description: description, - CodeIDs: codeIDs, - } -} - -// ProposalRoute returns the routing key of a parameter change proposal. -func (p PinCodesProposal) ProposalRoute() string { return RouterKey } - -// GetTitle returns the title of the proposal -func (p *PinCodesProposal) GetTitle() string { return p.Title } - -// GetDescription returns the human readable description of the proposal -func (p PinCodesProposal) GetDescription() string { return p.Description } - -// ProposalType returns the type -func (p PinCodesProposal) ProposalType() string { return string(ProposalTypePinCodes) } - -// ValidateBasic validates the proposal -func (p PinCodesProposal) ValidateBasic() error { - if err := validateProposalCommons(p.Title, p.Description); err != nil { - return err - } - if len(p.CodeIDs) == 0 { - return errorsmod.Wrap(ErrEmpty, "code ids") - } - return nil -} - -// String implements the Stringer interface. -func (p PinCodesProposal) String() string { - return fmt.Sprintf(`Pin Wasm Codes Proposal: - Title: %s - Description: %s - Codes: %v -`, p.Title, p.Description, p.CodeIDs) -} - -func NewUnpinCodesProposal( - title string, - description string, - codeIDs []uint64, -) *UnpinCodesProposal { - return &UnpinCodesProposal{ - Title: title, - Description: description, - CodeIDs: codeIDs, - } -} - -// ProposalRoute returns the routing key of a parameter change proposal. -func (p UnpinCodesProposal) ProposalRoute() string { return RouterKey } - -// GetTitle returns the title of the proposal -func (p *UnpinCodesProposal) GetTitle() string { return p.Title } - -// GetDescription returns the human readable description of the proposal -func (p UnpinCodesProposal) GetDescription() string { return p.Description } - -// ProposalType returns the type -func (p UnpinCodesProposal) ProposalType() string { return string(ProposalTypeUnpinCodes) } - -// ValidateBasic validates the proposal -func (p UnpinCodesProposal) ValidateBasic() error { - if err := validateProposalCommons(p.Title, p.Description); err != nil { - return err - } - if len(p.CodeIDs) == 0 { - return errorsmod.Wrap(ErrEmpty, "code ids") - } - return nil -} - -// String implements the Stringer interface. -func (p UnpinCodesProposal) String() string { - return fmt.Sprintf(`Unpin Wasm Codes Proposal: - Title: %s - Description: %s - Codes: %v -`, p.Title, p.Description, p.CodeIDs) -} - -func validateProposalCommons(title, description string) error { - if strings.TrimSpace(title) != title { - return errorsmod.Wrap(govtypes.ErrInvalidProposalContent, "proposal title must not start/end with white spaces") - } - if len(title) == 0 { - return errorsmod.Wrap(govtypes.ErrInvalidProposalContent, "proposal title cannot be blank") - } - if len(title) > v1beta1.MaxTitleLength { - return errorsmod.Wrapf(govtypes.ErrInvalidProposalContent, "proposal title is longer than max length of %d", v1beta1.MaxTitleLength) - } - if strings.TrimSpace(description) != description { - return errorsmod.Wrap(govtypes.ErrInvalidProposalContent, "proposal description must not start/end with white spaces") - } - if len(description) == 0 { - return errorsmod.Wrap(govtypes.ErrInvalidProposalContent, "proposal description cannot be blank") - } - if len(description) > v1beta1.MaxDescriptionLength { - return errorsmod.Wrapf(govtypes.ErrInvalidProposalContent, "proposal description is longer than max length of %d", v1beta1.MaxDescriptionLength) - } - return nil -} - -func NewUpdateInstantiateConfigProposal( - title string, - description string, - accessConfigUpdates ...AccessConfigUpdate, -) *UpdateInstantiateConfigProposal { - return &UpdateInstantiateConfigProposal{ - Title: title, - Description: description, - AccessConfigUpdates: accessConfigUpdates, - } -} - -// ProposalRoute returns the routing key of a parameter change proposal. -func (p UpdateInstantiateConfigProposal) ProposalRoute() string { return RouterKey } - -// GetTitle returns the title of the proposal -func (p *UpdateInstantiateConfigProposal) GetTitle() string { return p.Title } - -// GetDescription returns the human readable description of the proposal -func (p UpdateInstantiateConfigProposal) GetDescription() string { return p.Description } - -// ProposalType returns the type -func (p UpdateInstantiateConfigProposal) ProposalType() string { - return string(ProposalTypeUpdateInstantiateConfig) -} - -// ValidateBasic validates the proposal -func (p UpdateInstantiateConfigProposal) ValidateBasic() error { - if err := validateProposalCommons(p.Title, p.Description); err != nil { - return err - } - if len(p.AccessConfigUpdates) == 0 { - return errorsmod.Wrap(ErrEmpty, "code updates") - } - dedup := make(map[uint64]bool) - for _, codeUpdate := range p.AccessConfigUpdates { - _, found := dedup[codeUpdate.CodeID] - if found { - return errorsmod.Wrapf(ErrDuplicate, "duplicate code: %d", codeUpdate.CodeID) - } - if err := codeUpdate.InstantiatePermission.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "instantiate permission") - } - dedup[codeUpdate.CodeID] = true - } - return nil -} - -// String implements the Stringer interface. -func (p UpdateInstantiateConfigProposal) String() string { - return fmt.Sprintf(`Update Instantiate Config Proposal: - Title: %s - Description: %s - AccessConfigUpdates: %v -`, p.Title, p.Description, p.AccessConfigUpdates) -} - -// String implements the Stringer interface. -func (c AccessConfigUpdate) String() string { - return fmt.Sprintf(`AccessConfigUpdate: - CodeID: %d - AccessConfig: %v -`, c.CodeID, c.InstantiatePermission) -} diff --git a/x/wasm/types/proposal.pb.go b/x/wasm/types/proposal.pb.go deleted file mode 100644 index df66215..0000000 --- a/x/wasm/types/proposal.pb.go +++ /dev/null @@ -1,5856 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmwasm/wasm/v1/proposal.proto - -package types - -import ( - bytes "bytes" - fmt "fmt" - io "io" - math "math" - math_bits "math/bits" - - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/cosmos-sdk/types/tx/amino" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = proto.Marshal - _ = fmt.Errorf - _ = math.Inf -) - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit StoreCodeProposal. To submit WASM code to the system, -// a simple MsgStoreCode can be invoked from the x/gov module via -// a v1 governance proposal. -// -// Deprecated: Do not use. -type StoreCodeProposal struct { - // Title is a short summary - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - // Description is a human readable text - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - // RunAs is the address that is passed to the contract's environment as sender - RunAs string `protobuf:"bytes,3,opt,name=run_as,json=runAs,proto3" json:"run_as,omitempty"` - // WASMByteCode can be raw or gzip compressed - WASMByteCode []byte `protobuf:"bytes,4,opt,name=wasm_byte_code,json=wasmByteCode,proto3" json:"wasm_byte_code,omitempty"` - // InstantiatePermission to apply on contract creation, optional - InstantiatePermission *AccessConfig `protobuf:"bytes,7,opt,name=instantiate_permission,json=instantiatePermission,proto3" json:"instantiate_permission,omitempty"` - // UnpinCode code on upload, optional - UnpinCode bool `protobuf:"varint,8,opt,name=unpin_code,json=unpinCode,proto3" json:"unpin_code,omitempty"` - // Source is the URL where the code is hosted - Source string `protobuf:"bytes,9,opt,name=source,proto3" json:"source,omitempty"` - // Builder is the docker image used to build the code deterministically, used - // for smart contract verification - Builder string `protobuf:"bytes,10,opt,name=builder,proto3" json:"builder,omitempty"` - // CodeHash is the SHA256 sum of the code outputted by builder, used for smart - // contract verification - CodeHash []byte `protobuf:"bytes,11,opt,name=code_hash,json=codeHash,proto3" json:"code_hash,omitempty"` -} - -func (m *StoreCodeProposal) Reset() { *m = StoreCodeProposal{} } -func (*StoreCodeProposal) ProtoMessage() {} -func (*StoreCodeProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_be6422d717c730cb, []int{0} -} - -func (m *StoreCodeProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *StoreCodeProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_StoreCodeProposal.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *StoreCodeProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_StoreCodeProposal.Merge(m, src) -} - -func (m *StoreCodeProposal) XXX_Size() int { - return m.Size() -} - -func (m *StoreCodeProposal) XXX_DiscardUnknown() { - xxx_messageInfo_StoreCodeProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_StoreCodeProposal proto.InternalMessageInfo - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit InstantiateContractProposal. To instantiate a contract, -// a simple MsgInstantiateContract can be invoked from the x/gov module via -// a v1 governance proposal. -// -// Deprecated: Do not use. -type InstantiateContractProposal struct { - // Title is a short summary - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - // Description is a human readable text - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - // RunAs is the address that is passed to the contract's environment as sender - RunAs string `protobuf:"bytes,3,opt,name=run_as,json=runAs,proto3" json:"run_as,omitempty"` - // Admin is an optional address that can execute migrations - Admin string `protobuf:"bytes,4,opt,name=admin,proto3" json:"admin,omitempty"` - // CodeID is the reference to the stored WASM code - CodeID uint64 `protobuf:"varint,5,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` - // Label is optional metadata to be stored with a constract instance. - Label string `protobuf:"bytes,6,opt,name=label,proto3" json:"label,omitempty"` - // Msg json encoded message to be passed to the contract on instantiation - Msg RawContractMessage `protobuf:"bytes,7,opt,name=msg,proto3,casttype=RawContractMessage" json:"msg,omitempty"` - // Funds coins that are transferred to the contract on instantiation - Funds github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,8,rep,name=funds,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"funds"` -} - -func (m *InstantiateContractProposal) Reset() { *m = InstantiateContractProposal{} } -func (*InstantiateContractProposal) ProtoMessage() {} -func (*InstantiateContractProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_be6422d717c730cb, []int{1} -} - -func (m *InstantiateContractProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *InstantiateContractProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_InstantiateContractProposal.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *InstantiateContractProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_InstantiateContractProposal.Merge(m, src) -} - -func (m *InstantiateContractProposal) XXX_Size() int { - return m.Size() -} - -func (m *InstantiateContractProposal) XXX_DiscardUnknown() { - xxx_messageInfo_InstantiateContractProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_InstantiateContractProposal proto.InternalMessageInfo - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit InstantiateContract2Proposal. To instantiate contract 2, -// a simple MsgInstantiateContract2 can be invoked from the x/gov module via -// a v1 governance proposal. -// -// Deprecated: Do not use. -type InstantiateContract2Proposal struct { - // Title is a short summary - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - // Description is a human readable text - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - // RunAs is the address that is passed to the contract's enviroment as sender - RunAs string `protobuf:"bytes,3,opt,name=run_as,json=runAs,proto3" json:"run_as,omitempty"` - // Admin is an optional address that can execute migrations - Admin string `protobuf:"bytes,4,opt,name=admin,proto3" json:"admin,omitempty"` - // CodeID is the reference to the stored WASM code - CodeID uint64 `protobuf:"varint,5,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` - // Label is optional metadata to be stored with a constract instance. - Label string `protobuf:"bytes,6,opt,name=label,proto3" json:"label,omitempty"` - // Msg json encode message to be passed to the contract on instantiation - Msg RawContractMessage `protobuf:"bytes,7,opt,name=msg,proto3,casttype=RawContractMessage" json:"msg,omitempty"` - // Funds coins that are transferred to the contract on instantiation - Funds github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,8,rep,name=funds,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"funds"` - // Salt is an arbitrary value provided by the sender. Size can be 1 to 64. - Salt []byte `protobuf:"bytes,9,opt,name=salt,proto3" json:"salt,omitempty"` - // FixMsg include the msg value into the hash for the predictable address. - // Default is false - FixMsg bool `protobuf:"varint,10,opt,name=fix_msg,json=fixMsg,proto3" json:"fix_msg,omitempty"` -} - -func (m *InstantiateContract2Proposal) Reset() { *m = InstantiateContract2Proposal{} } -func (*InstantiateContract2Proposal) ProtoMessage() {} -func (*InstantiateContract2Proposal) Descriptor() ([]byte, []int) { - return fileDescriptor_be6422d717c730cb, []int{2} -} - -func (m *InstantiateContract2Proposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *InstantiateContract2Proposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_InstantiateContract2Proposal.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *InstantiateContract2Proposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_InstantiateContract2Proposal.Merge(m, src) -} - -func (m *InstantiateContract2Proposal) XXX_Size() int { - return m.Size() -} - -func (m *InstantiateContract2Proposal) XXX_DiscardUnknown() { - xxx_messageInfo_InstantiateContract2Proposal.DiscardUnknown(m) -} - -var xxx_messageInfo_InstantiateContract2Proposal proto.InternalMessageInfo - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit MigrateContractProposal. To migrate a contract, -// a simple MsgMigrateContract can be invoked from the x/gov module via -// a v1 governance proposal. -// -// Deprecated: Do not use. -type MigrateContractProposal struct { - // Title is a short summary - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - // Description is a human readable text - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - // Contract is the address of the smart contract - Contract string `protobuf:"bytes,4,opt,name=contract,proto3" json:"contract,omitempty"` - // CodeID references the new WASM code - CodeID uint64 `protobuf:"varint,5,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` - // Msg json encoded message to be passed to the contract on migration - Msg RawContractMessage `protobuf:"bytes,6,opt,name=msg,proto3,casttype=RawContractMessage" json:"msg,omitempty"` -} - -func (m *MigrateContractProposal) Reset() { *m = MigrateContractProposal{} } -func (*MigrateContractProposal) ProtoMessage() {} -func (*MigrateContractProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_be6422d717c730cb, []int{3} -} - -func (m *MigrateContractProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MigrateContractProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MigrateContractProposal.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *MigrateContractProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_MigrateContractProposal.Merge(m, src) -} - -func (m *MigrateContractProposal) XXX_Size() int { - return m.Size() -} - -func (m *MigrateContractProposal) XXX_DiscardUnknown() { - xxx_messageInfo_MigrateContractProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_MigrateContractProposal proto.InternalMessageInfo - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit SudoContractProposal. To call sudo on a contract, -// a simple MsgSudoContract can be invoked from the x/gov module via -// a v1 governance proposal. -// -// Deprecated: Do not use. -type SudoContractProposal struct { - // Title is a short summary - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - // Description is a human readable text - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - // Contract is the address of the smart contract - Contract string `protobuf:"bytes,3,opt,name=contract,proto3" json:"contract,omitempty"` - // Msg json encoded message to be passed to the contract as sudo - Msg RawContractMessage `protobuf:"bytes,4,opt,name=msg,proto3,casttype=RawContractMessage" json:"msg,omitempty"` -} - -func (m *SudoContractProposal) Reset() { *m = SudoContractProposal{} } -func (*SudoContractProposal) ProtoMessage() {} -func (*SudoContractProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_be6422d717c730cb, []int{4} -} - -func (m *SudoContractProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *SudoContractProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_SudoContractProposal.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *SudoContractProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_SudoContractProposal.Merge(m, src) -} - -func (m *SudoContractProposal) XXX_Size() int { - return m.Size() -} - -func (m *SudoContractProposal) XXX_DiscardUnknown() { - xxx_messageInfo_SudoContractProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_SudoContractProposal proto.InternalMessageInfo - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit ExecuteContractProposal. To call execute on a contract, -// a simple MsgExecuteContract can be invoked from the x/gov module via -// a v1 governance proposal. -// -// Deprecated: Do not use. -type ExecuteContractProposal struct { - // Title is a short summary - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - // Description is a human readable text - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - // RunAs is the address that is passed to the contract's environment as sender - RunAs string `protobuf:"bytes,3,opt,name=run_as,json=runAs,proto3" json:"run_as,omitempty"` - // Contract is the address of the smart contract - Contract string `protobuf:"bytes,4,opt,name=contract,proto3" json:"contract,omitempty"` - // Msg json encoded message to be passed to the contract as execute - Msg RawContractMessage `protobuf:"bytes,5,opt,name=msg,proto3,casttype=RawContractMessage" json:"msg,omitempty"` - // Funds coins that are transferred to the contract on instantiation - Funds github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,6,rep,name=funds,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"funds"` -} - -func (m *ExecuteContractProposal) Reset() { *m = ExecuteContractProposal{} } -func (*ExecuteContractProposal) ProtoMessage() {} -func (*ExecuteContractProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_be6422d717c730cb, []int{5} -} - -func (m *ExecuteContractProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *ExecuteContractProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ExecuteContractProposal.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *ExecuteContractProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_ExecuteContractProposal.Merge(m, src) -} - -func (m *ExecuteContractProposal) XXX_Size() int { - return m.Size() -} - -func (m *ExecuteContractProposal) XXX_DiscardUnknown() { - xxx_messageInfo_ExecuteContractProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_ExecuteContractProposal proto.InternalMessageInfo - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit UpdateAdminProposal. To set an admin for a contract, -// a simple MsgUpdateAdmin can be invoked from the x/gov module via -// a v1 governance proposal. -// -// Deprecated: Do not use. -type UpdateAdminProposal struct { - // Title is a short summary - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - // Description is a human readable text - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - // NewAdmin address to be set - NewAdmin string `protobuf:"bytes,3,opt,name=new_admin,json=newAdmin,proto3" json:"new_admin,omitempty" yaml:"new_admin"` - // Contract is the address of the smart contract - Contract string `protobuf:"bytes,4,opt,name=contract,proto3" json:"contract,omitempty"` -} - -func (m *UpdateAdminProposal) Reset() { *m = UpdateAdminProposal{} } -func (*UpdateAdminProposal) ProtoMessage() {} -func (*UpdateAdminProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_be6422d717c730cb, []int{6} -} - -func (m *UpdateAdminProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *UpdateAdminProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_UpdateAdminProposal.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *UpdateAdminProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_UpdateAdminProposal.Merge(m, src) -} - -func (m *UpdateAdminProposal) XXX_Size() int { - return m.Size() -} - -func (m *UpdateAdminProposal) XXX_DiscardUnknown() { - xxx_messageInfo_UpdateAdminProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_UpdateAdminProposal proto.InternalMessageInfo - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit ClearAdminProposal. To clear the admin of a contract, -// a simple MsgClearAdmin can be invoked from the x/gov module via -// a v1 governance proposal. -// -// Deprecated: Do not use. -type ClearAdminProposal struct { - // Title is a short summary - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - // Description is a human readable text - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - // Contract is the address of the smart contract - Contract string `protobuf:"bytes,3,opt,name=contract,proto3" json:"contract,omitempty"` -} - -func (m *ClearAdminProposal) Reset() { *m = ClearAdminProposal{} } -func (*ClearAdminProposal) ProtoMessage() {} -func (*ClearAdminProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_be6422d717c730cb, []int{7} -} - -func (m *ClearAdminProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *ClearAdminProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ClearAdminProposal.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *ClearAdminProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_ClearAdminProposal.Merge(m, src) -} - -func (m *ClearAdminProposal) XXX_Size() int { - return m.Size() -} - -func (m *ClearAdminProposal) XXX_DiscardUnknown() { - xxx_messageInfo_ClearAdminProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_ClearAdminProposal proto.InternalMessageInfo - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit PinCodesProposal. To pin a set of code ids in the wasmvm -// cache, a simple MsgPinCodes can be invoked from the x/gov module via -// a v1 governance proposal. -// -// Deprecated: Do not use. -type PinCodesProposal struct { - // Title is a short summary - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty" yaml:"title"` - // Description is a human readable text - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty" yaml:"description"` - // CodeIDs references the new WASM codes - CodeIDs []uint64 `protobuf:"varint,3,rep,packed,name=code_ids,json=codeIds,proto3" json:"code_ids,omitempty" yaml:"code_ids"` -} - -func (m *PinCodesProposal) Reset() { *m = PinCodesProposal{} } -func (*PinCodesProposal) ProtoMessage() {} -func (*PinCodesProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_be6422d717c730cb, []int{8} -} - -func (m *PinCodesProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *PinCodesProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_PinCodesProposal.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *PinCodesProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_PinCodesProposal.Merge(m, src) -} - -func (m *PinCodesProposal) XXX_Size() int { - return m.Size() -} - -func (m *PinCodesProposal) XXX_DiscardUnknown() { - xxx_messageInfo_PinCodesProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_PinCodesProposal proto.InternalMessageInfo - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit UnpinCodesProposal. To unpin a set of code ids in the wasmvm -// cache, a simple MsgUnpinCodes can be invoked from the x/gov module via -// a v1 governance proposal. -// -// Deprecated: Do not use. -type UnpinCodesProposal struct { - // Title is a short summary - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty" yaml:"title"` - // Description is a human readable text - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty" yaml:"description"` - // CodeIDs references the WASM codes - CodeIDs []uint64 `protobuf:"varint,3,rep,packed,name=code_ids,json=codeIds,proto3" json:"code_ids,omitempty" yaml:"code_ids"` -} - -func (m *UnpinCodesProposal) Reset() { *m = UnpinCodesProposal{} } -func (*UnpinCodesProposal) ProtoMessage() {} -func (*UnpinCodesProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_be6422d717c730cb, []int{9} -} - -func (m *UnpinCodesProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *UnpinCodesProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_UnpinCodesProposal.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *UnpinCodesProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_UnpinCodesProposal.Merge(m, src) -} - -func (m *UnpinCodesProposal) XXX_Size() int { - return m.Size() -} - -func (m *UnpinCodesProposal) XXX_DiscardUnknown() { - xxx_messageInfo_UnpinCodesProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_UnpinCodesProposal proto.InternalMessageInfo - -// AccessConfigUpdate contains the code id and the access config to be -// applied. -type AccessConfigUpdate struct { - // CodeID is the reference to the stored WASM code to be updated - CodeID uint64 `protobuf:"varint,1,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` - // InstantiatePermission to apply to the set of code ids - InstantiatePermission AccessConfig `protobuf:"bytes,2,opt,name=instantiate_permission,json=instantiatePermission,proto3" json:"instantiate_permission"` -} - -func (m *AccessConfigUpdate) Reset() { *m = AccessConfigUpdate{} } -func (*AccessConfigUpdate) ProtoMessage() {} -func (*AccessConfigUpdate) Descriptor() ([]byte, []int) { - return fileDescriptor_be6422d717c730cb, []int{10} -} - -func (m *AccessConfigUpdate) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *AccessConfigUpdate) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AccessConfigUpdate.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *AccessConfigUpdate) XXX_Merge(src proto.Message) { - xxx_messageInfo_AccessConfigUpdate.Merge(m, src) -} - -func (m *AccessConfigUpdate) XXX_Size() int { - return m.Size() -} - -func (m *AccessConfigUpdate) XXX_DiscardUnknown() { - xxx_messageInfo_AccessConfigUpdate.DiscardUnknown(m) -} - -var xxx_messageInfo_AccessConfigUpdate proto.InternalMessageInfo - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit UpdateInstantiateConfigProposal. To update instantiate config -// to a set of code ids, a simple MsgUpdateInstantiateConfig can be invoked from -// the x/gov module via a v1 governance proposal. -// -// Deprecated: Do not use. -type UpdateInstantiateConfigProposal struct { - // Title is a short summary - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty" yaml:"title"` - // Description is a human readable text - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty" yaml:"description"` - // AccessConfigUpdate contains the list of code ids and the access config - // to be applied. - AccessConfigUpdates []AccessConfigUpdate `protobuf:"bytes,3,rep,name=access_config_updates,json=accessConfigUpdates,proto3" json:"access_config_updates"` -} - -func (m *UpdateInstantiateConfigProposal) Reset() { *m = UpdateInstantiateConfigProposal{} } -func (*UpdateInstantiateConfigProposal) ProtoMessage() {} -func (*UpdateInstantiateConfigProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_be6422d717c730cb, []int{11} -} - -func (m *UpdateInstantiateConfigProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *UpdateInstantiateConfigProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_UpdateInstantiateConfigProposal.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *UpdateInstantiateConfigProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_UpdateInstantiateConfigProposal.Merge(m, src) -} - -func (m *UpdateInstantiateConfigProposal) XXX_Size() int { - return m.Size() -} - -func (m *UpdateInstantiateConfigProposal) XXX_DiscardUnknown() { - xxx_messageInfo_UpdateInstantiateConfigProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_UpdateInstantiateConfigProposal proto.InternalMessageInfo - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit StoreAndInstantiateContractProposal. To store and instantiate -// the contract, a simple MsgStoreAndInstantiateContract can be invoked from -// the x/gov module via a v1 governance proposal. -// -// Deprecated: Do not use. -type StoreAndInstantiateContractProposal struct { - // Title is a short summary - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - // Description is a human readable text - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - // RunAs is the address that is passed to the contract's environment as sender - RunAs string `protobuf:"bytes,3,opt,name=run_as,json=runAs,proto3" json:"run_as,omitempty"` - // WASMByteCode can be raw or gzip compressed - WASMByteCode []byte `protobuf:"bytes,4,opt,name=wasm_byte_code,json=wasmByteCode,proto3" json:"wasm_byte_code,omitempty"` - // InstantiatePermission to apply on contract creation, optional - InstantiatePermission *AccessConfig `protobuf:"bytes,5,opt,name=instantiate_permission,json=instantiatePermission,proto3" json:"instantiate_permission,omitempty"` - // UnpinCode code on upload, optional - UnpinCode bool `protobuf:"varint,6,opt,name=unpin_code,json=unpinCode,proto3" json:"unpin_code,omitempty"` - // Admin is an optional address that can execute migrations - Admin string `protobuf:"bytes,7,opt,name=admin,proto3" json:"admin,omitempty"` - // Label is optional metadata to be stored with a constract instance. - Label string `protobuf:"bytes,8,opt,name=label,proto3" json:"label,omitempty"` - // Msg json encoded message to be passed to the contract on instantiation - Msg RawContractMessage `protobuf:"bytes,9,opt,name=msg,proto3,casttype=RawContractMessage" json:"msg,omitempty"` - // Funds coins that are transferred to the contract on instantiation - Funds github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,10,rep,name=funds,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"funds"` - // Source is the URL where the code is hosted - Source string `protobuf:"bytes,11,opt,name=source,proto3" json:"source,omitempty"` - // Builder is the docker image used to build the code deterministically, used - // for smart contract verification - Builder string `protobuf:"bytes,12,opt,name=builder,proto3" json:"builder,omitempty"` - // CodeHash is the SHA256 sum of the code outputted by builder, used for smart - // contract verification - CodeHash []byte `protobuf:"bytes,13,opt,name=code_hash,json=codeHash,proto3" json:"code_hash,omitempty"` -} - -func (m *StoreAndInstantiateContractProposal) Reset() { *m = StoreAndInstantiateContractProposal{} } -func (*StoreAndInstantiateContractProposal) ProtoMessage() {} -func (*StoreAndInstantiateContractProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_be6422d717c730cb, []int{12} -} - -func (m *StoreAndInstantiateContractProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *StoreAndInstantiateContractProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_StoreAndInstantiateContractProposal.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *StoreAndInstantiateContractProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_StoreAndInstantiateContractProposal.Merge(m, src) -} - -func (m *StoreAndInstantiateContractProposal) XXX_Size() int { - return m.Size() -} - -func (m *StoreAndInstantiateContractProposal) XXX_DiscardUnknown() { - xxx_messageInfo_StoreAndInstantiateContractProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_StoreAndInstantiateContractProposal proto.InternalMessageInfo - -func init() { - proto.RegisterType((*StoreCodeProposal)(nil), "cosmwasm.wasm.v1.StoreCodeProposal") - proto.RegisterType((*InstantiateContractProposal)(nil), "cosmwasm.wasm.v1.InstantiateContractProposal") - proto.RegisterType((*InstantiateContract2Proposal)(nil), "cosmwasm.wasm.v1.InstantiateContract2Proposal") - proto.RegisterType((*MigrateContractProposal)(nil), "cosmwasm.wasm.v1.MigrateContractProposal") - proto.RegisterType((*SudoContractProposal)(nil), "cosmwasm.wasm.v1.SudoContractProposal") - proto.RegisterType((*ExecuteContractProposal)(nil), "cosmwasm.wasm.v1.ExecuteContractProposal") - proto.RegisterType((*UpdateAdminProposal)(nil), "cosmwasm.wasm.v1.UpdateAdminProposal") - proto.RegisterType((*ClearAdminProposal)(nil), "cosmwasm.wasm.v1.ClearAdminProposal") - proto.RegisterType((*PinCodesProposal)(nil), "cosmwasm.wasm.v1.PinCodesProposal") - proto.RegisterType((*UnpinCodesProposal)(nil), "cosmwasm.wasm.v1.UnpinCodesProposal") - proto.RegisterType((*AccessConfigUpdate)(nil), "cosmwasm.wasm.v1.AccessConfigUpdate") - proto.RegisterType((*UpdateInstantiateConfigProposal)(nil), "cosmwasm.wasm.v1.UpdateInstantiateConfigProposal") - proto.RegisterType((*StoreAndInstantiateContractProposal)(nil), "cosmwasm.wasm.v1.StoreAndInstantiateContractProposal") -} - -func init() { proto.RegisterFile("cosmwasm/wasm/v1/proposal.proto", fileDescriptor_be6422d717c730cb) } - -var fileDescriptor_be6422d717c730cb = []byte{ - // 1175 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xec, 0x58, 0xcd, 0x6f, 0xe3, 0x44, - 0x14, 0xcf, 0x34, 0x89, 0x93, 0x4c, 0x02, 0x64, 0xbd, 0xfd, 0x98, 0xed, 0x16, 0x3b, 0x78, 0x57, - 0x28, 0x5a, 0xa9, 0x09, 0x2d, 0x02, 0x41, 0xf8, 0x90, 0xe2, 0xb2, 0x88, 0xae, 0x54, 0xa9, 0x72, - 0x55, 0x21, 0x71, 0x09, 0x13, 0x7b, 0x92, 0x5a, 0x9b, 0x78, 0x22, 0x8f, 0xd3, 0x8f, 0x7f, 0x81, - 0x13, 0x27, 0x2e, 0xdc, 0x51, 0xc5, 0x69, 0x25, 0xf8, 0x17, 0x90, 0x2a, 0x4e, 0x7b, 0xe0, 0xb0, - 0x12, 0x52, 0x60, 0xd3, 0xc3, 0x1e, 0x38, 0x20, 0xf5, 0xc8, 0x01, 0x90, 0x67, 0xec, 0xd4, 0x6d, - 0x93, 0xb8, 0x0b, 0xed, 0x4a, 0x48, 0x5c, 0x1c, 0xbf, 0x79, 0x33, 0xf6, 0xef, 0xf7, 0x7e, 0xf3, - 0x9e, 0xdf, 0x04, 0xaa, 0x26, 0x65, 0xdd, 0x3d, 0xcc, 0xba, 0x55, 0x7e, 0xd9, 0x5d, 0xa9, 0xf6, - 0x5c, 0xda, 0xa3, 0x0c, 0x77, 0x2a, 0x3d, 0x97, 0x7a, 0x54, 0x2e, 0x86, 0x13, 0x2a, 0xfc, 0xb2, - 0xbb, 0xb2, 0x38, 0xdb, 0xa6, 0x6d, 0xca, 0x9d, 0x55, 0xff, 0x4e, 0xcc, 0x5b, 0xbc, 0xe5, 0xcf, - 0xa3, 0xac, 0x21, 0x1c, 0xc2, 0x08, 0x5c, 0x8a, 0xb0, 0xaa, 0x4d, 0xcc, 0x48, 0x75, 0x77, 0xa5, - 0x49, 0x3c, 0xbc, 0x52, 0x35, 0xa9, 0xed, 0x04, 0xfe, 0xa5, 0x0b, 0x18, 0xbc, 0x83, 0x1e, 0x09, - 0x57, 0xdf, 0xc0, 0x5d, 0xdb, 0xa1, 0x55, 0x7e, 0x15, 0x43, 0xda, 0x61, 0x12, 0xde, 0xd8, 0xf2, - 0xa8, 0x4b, 0xd6, 0xa8, 0x45, 0x36, 0x03, 0xbc, 0xf2, 0x2c, 0x4c, 0x7b, 0xb6, 0xd7, 0x21, 0x08, - 0x94, 0x40, 0x39, 0x67, 0x08, 0x43, 0x2e, 0xc1, 0xbc, 0x45, 0x98, 0xe9, 0xda, 0x3d, 0xcf, 0xa6, - 0x0e, 0x9a, 0xe1, 0xbe, 0xe8, 0x90, 0x3c, 0x07, 0x25, 0xb7, 0xef, 0x34, 0x30, 0x43, 0x49, 0xb1, - 0xd0, 0xed, 0x3b, 0x75, 0x26, 0xbf, 0x0d, 0x5f, 0xf6, 0xe1, 0x34, 0x9a, 0x07, 0x1e, 0x69, 0x98, - 0xd4, 0x22, 0x28, 0x55, 0x02, 0xe5, 0x82, 0x5e, 0x1c, 0x0e, 0xd4, 0xc2, 0xa7, 0xf5, 0xad, 0x0d, - 0xfd, 0xc0, 0xe3, 0x00, 0x8c, 0x82, 0x3f, 0x2f, 0xb4, 0xe4, 0x6d, 0x38, 0x6f, 0x3b, 0xcc, 0xc3, - 0x8e, 0x67, 0x63, 0x8f, 0x34, 0x7a, 0xc4, 0xed, 0xda, 0x8c, 0xf9, 0xef, 0xce, 0x94, 0x40, 0x39, - 0xbf, 0xaa, 0x54, 0xce, 0x47, 0xb4, 0x52, 0x37, 0x4d, 0xc2, 0xd8, 0x1a, 0x75, 0x5a, 0x76, 0xdb, - 0x98, 0x8b, 0xac, 0xde, 0x1c, 0x2d, 0x96, 0x5f, 0x85, 0xb0, 0xef, 0xf4, 0x6c, 0x47, 0x40, 0xc9, - 0x96, 0x40, 0x39, 0x6b, 0xe4, 0xf8, 0x08, 0x7f, 0xeb, 0x3c, 0x94, 0x18, 0xed, 0xbb, 0x26, 0x41, - 0x39, 0x4e, 0x22, 0xb0, 0x64, 0x04, 0x33, 0xcd, 0xbe, 0xdd, 0xb1, 0x88, 0x8b, 0x20, 0x77, 0x84, - 0xa6, 0x7c, 0x1b, 0xe6, 0xfc, 0x47, 0x35, 0x76, 0x30, 0xdb, 0x41, 0x79, 0x9f, 0x9a, 0x91, 0xf5, - 0x07, 0x3e, 0xc1, 0x6c, 0xa7, 0xf6, 0xde, 0x8f, 0xdf, 0x2f, 0x2f, 0x06, 0x22, 0xb6, 0xe9, 0x6e, - 0x25, 0x50, 0xad, 0xb2, 0x46, 0x1d, 0x8f, 0x38, 0xde, 0x17, 0xcf, 0x1e, 0xdd, 0x9b, 0xe7, 0x62, - 0x5d, 0x90, 0x01, 0x81, 0x07, 0xa9, 0x6c, 0xba, 0x28, 0x3d, 0x48, 0x65, 0xa5, 0x62, 0x46, 0xfb, - 0x2a, 0x09, 0x6f, 0xaf, 0x9f, 0x12, 0xf2, 0xd7, 0xbb, 0xd8, 0xf4, 0xae, 0x4b, 0xb4, 0x59, 0x98, - 0xc6, 0x56, 0xd7, 0x76, 0xb8, 0x56, 0x39, 0x43, 0x18, 0xf2, 0x1d, 0x98, 0xe1, 0x54, 0x6d, 0x0b, - 0xa5, 0x4b, 0xa0, 0x9c, 0xd2, 0xe1, 0x70, 0xa0, 0x4a, 0x3e, 0xea, 0xf5, 0x8f, 0x0c, 0xc9, 0x77, - 0xad, 0x5b, 0xfe, 0xd2, 0x0e, 0x6e, 0x92, 0x0e, 0x92, 0xc4, 0x52, 0x6e, 0xc8, 0x65, 0x98, 0xec, - 0xb2, 0x36, 0x97, 0xae, 0xa0, 0xcf, 0xff, 0x31, 0x50, 0x65, 0x03, 0xef, 0x85, 0x2c, 0x36, 0x08, - 0x63, 0xb8, 0x4d, 0x0c, 0x7f, 0x8a, 0xdc, 0x82, 0xe9, 0x56, 0xdf, 0xb1, 0x18, 0xca, 0x96, 0x92, - 0xe5, 0xfc, 0xea, 0xad, 0x4a, 0x10, 0x3e, 0x7f, 0xd7, 0x47, 0xe2, 0x67, 0x3b, 0xfa, 0x5b, 0x47, - 0x03, 0x35, 0xf1, 0xed, 0x2f, 0x6a, 0xb9, 0x6d, 0x7b, 0x3b, 0xfd, 0x66, 0xc5, 0xa4, 0xdd, 0x20, - 0x61, 0x82, 0x9f, 0x65, 0x66, 0x3d, 0x0c, 0x72, 0xc0, 0x5f, 0xc0, 0x0e, 0x9f, 0x3d, 0xba, 0x07, - 0x0c, 0xf1, 0xf8, 0xda, 0xfd, 0x78, 0x69, 0x4a, 0x5c, 0x9a, 0x29, 0x61, 0x47, 0x40, 0xfb, 0x21, - 0x09, 0x97, 0xc6, 0xcc, 0x58, 0xfd, 0x5f, 0x99, 0x7f, 0xaa, 0x8c, 0x2c, 0xc3, 0x14, 0xc3, 0x1d, - 0x8f, 0x67, 0x60, 0xc1, 0xe0, 0xf7, 0xf2, 0x02, 0xcc, 0xb4, 0xec, 0xfd, 0x86, 0x8f, 0x14, 0xf2, - 0x9c, 0x95, 0x5a, 0xf6, 0xfe, 0x06, 0x6b, 0xd7, 0x3e, 0x8e, 0x97, 0xf1, 0xb5, 0x49, 0x32, 0xae, - 0x46, 0x74, 0xfc, 0x0b, 0xc0, 0x85, 0x0d, 0xbb, 0xed, 0x5e, 0x65, 0x72, 0x2d, 0xc2, 0xac, 0x19, - 0x3c, 0x2b, 0x90, 0x6b, 0x64, 0x5f, 0x4e, 0xb1, 0x40, 0x1b, 0x29, 0x56, 0x9b, 0x5a, 0x3d, 0x3e, - 0x0c, 0x4b, 0x3c, 0x0c, 0x13, 0x38, 0x22, 0xa0, 0xfd, 0x04, 0xe0, 0xec, 0x56, 0xdf, 0xa2, 0xd7, - 0x42, 0x3f, 0x79, 0x8e, 0x7e, 0xc0, 0x2c, 0x15, 0xcf, 0xec, 0xc3, 0x78, 0x66, 0xb7, 0x44, 0x09, - 0x1d, 0x83, 0xdd, 0xa7, 0x35, 0x03, 0x17, 0xee, 0xef, 0x13, 0xb3, 0x7f, 0xfd, 0x55, 0x73, 0x9a, - 0xde, 0x01, 0xe1, 0x74, 0x7c, 0x9a, 0xe1, 0x30, 0xcd, 0xa4, 0xb8, 0x34, 0x7b, 0xe3, 0x79, 0xd3, - 0x2c, 0xac, 0x7d, 0x97, 0xde, 0x2d, 0x13, 0x02, 0x87, 0x80, 0xf6, 0x33, 0x80, 0x37, 0xb7, 0x7b, - 0x16, 0xf6, 0x48, 0xdd, 0xaf, 0x40, 0xff, 0x3a, 0xa4, 0x2b, 0x30, 0xe7, 0x90, 0xbd, 0x86, 0xa8, - 0x6d, 0x3c, 0xaa, 0xfa, 0xec, 0xc9, 0x40, 0x2d, 0x1e, 0xe0, 0x6e, 0xa7, 0xa6, 0x8d, 0x5c, 0x9a, - 0x91, 0x75, 0xc8, 0x1e, 0x7f, 0xe5, 0xb4, 0x70, 0xd7, 0x3e, 0x88, 0x67, 0x88, 0x38, 0xc3, 0x31, - 0x1c, 0x10, 0xd0, 0xbe, 0x01, 0x50, 0x5e, 0xeb, 0x10, 0xec, 0x5e, 0x0d, 0xb9, 0x29, 0x99, 0x50, - 0x7b, 0x3f, 0x1e, 0xe9, 0x02, 0x47, 0x7a, 0x11, 0x0f, 0x02, 0xda, 0x6f, 0x00, 0x16, 0x37, 0x45, - 0xef, 0xc2, 0x46, 0x30, 0x5f, 0x3f, 0x03, 0x53, 0x2f, 0x9e, 0x0c, 0xd4, 0x82, 0x88, 0x23, 0x1f, - 0xd6, 0x42, 0xe0, 0xef, 0x8c, 0x01, 0xae, 0xcf, 0x9f, 0x0c, 0x54, 0x59, 0xcc, 0x8e, 0x38, 0xb5, - 0xb3, 0x84, 0xde, 0x85, 0xd9, 0xa0, 0x7a, 0xf9, 0x29, 0x90, 0x2c, 0xa7, 0x74, 0x65, 0x38, 0x50, - 0x33, 0xa2, 0x7c, 0xb1, 0x93, 0x81, 0xfa, 0x8a, 0x78, 0x42, 0x38, 0x49, 0x33, 0x32, 0xa2, 0xa4, - 0xb1, 0x5a, 0x2d, 0x9e, 0xef, 0x1c, 0xe7, 0x7b, 0x9e, 0x16, 0x02, 0xda, 0xef, 0x00, 0xca, 0xdb, - 0x61, 0xaf, 0xf6, 0x1f, 0xe1, 0x7b, 0x69, 0x7d, 0x2f, 0x12, 0x43, 0x40, 0xfb, 0x1a, 0x40, 0x39, - 0xda, 0xd6, 0x8a, 0xed, 0x1a, 0xfd, 0x7a, 0x80, 0x89, 0x5f, 0x8f, 0xcf, 0x27, 0x76, 0xd0, 0x33, - 0x97, 0xe9, 0xa0, 0xf5, 0x9c, 0x5f, 0x5e, 0xc4, 0x97, 0x79, 0x7c, 0x33, 0xad, 0x7d, 0x37, 0x03, - 0x55, 0x81, 0xe8, 0xec, 0xd7, 0xb5, 0x65, 0xb7, 0x5f, 0xa0, 0x38, 0x26, 0x9c, 0xc3, 0x1c, 0x77, - 0xc3, 0xe4, 0xaf, 0x6e, 0xf4, 0x39, 0x24, 0xa1, 0x54, 0x7e, 0xf5, 0xee, 0x74, 0x9a, 0x02, 0x7f, - 0x94, 0xec, 0x4d, 0x7c, 0xc1, 0xcd, 0x6a, 0xeb, 0xf1, 0x32, 0xde, 0x8d, 0x14, 0x94, 0x89, 0xf1, - 0x40, 0x40, 0xfb, 0x33, 0x05, 0xef, 0xf0, 0x7e, 0xbf, 0xee, 0x58, 0x2f, 0xb0, 0xa7, 0xbf, 0xfa, - 0x83, 0x58, 0xfa, 0xea, 0x0e, 0x62, 0xd2, 0xf9, 0x83, 0xd8, 0xa8, 0xcf, 0xcd, 0x44, 0xfb, 0xdc, - 0x51, 0x0b, 0x9b, 0x1d, 0xd3, 0xc2, 0xe6, 0x9e, 0xa3, 0x85, 0x85, 0xd7, 0xdb, 0xc2, 0x9e, 0x1e, - 0x23, 0xf3, 0x93, 0x8e, 0x91, 0x85, 0x29, 0xc7, 0xc8, 0x97, 0xce, 0x1d, 0x23, 0x37, 0xe2, 0x37, - 0x5f, 0xf9, 0xf4, 0x18, 0x39, 0x7d, 0x5b, 0x21, 0xa0, 0x6f, 0x1d, 0x3d, 0x55, 0x12, 0x4f, 0x9e, - 0x2a, 0x89, 0xc3, 0xa1, 0x02, 0x8e, 0x86, 0x0a, 0x78, 0x3c, 0x54, 0xc0, 0xaf, 0x43, 0x05, 0x7c, - 0x79, 0xac, 0x24, 0x1e, 0x1f, 0x2b, 0x89, 0x27, 0xc7, 0x4a, 0xe2, 0xb3, 0xe5, 0x08, 0x73, 0x8f, - 0xb8, 0x3d, 0x87, 0x78, 0x7b, 0xd4, 0x7d, 0xc8, 0xef, 0x97, 0x4d, 0xea, 0x92, 0xea, 0xbe, 0xf8, - 0xa3, 0x81, 0x07, 0xa1, 0x29, 0xf1, 0xff, 0x14, 0xde, 0xfc, 0x3b, 0x00, 0x00, 0xff, 0xff, 0x41, - 0x3d, 0x83, 0x5f, 0x0a, 0x11, 0x00, 0x00, -} - -func (this *StoreCodeProposal) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*StoreCodeProposal) - if !ok { - that2, ok := that.(StoreCodeProposal) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Title != that1.Title { - return false - } - if this.Description != that1.Description { - return false - } - if this.RunAs != that1.RunAs { - return false - } - if !bytes.Equal(this.WASMByteCode, that1.WASMByteCode) { - return false - } - if !this.InstantiatePermission.Equal(that1.InstantiatePermission) { - return false - } - if this.UnpinCode != that1.UnpinCode { - return false - } - if this.Source != that1.Source { - return false - } - if this.Builder != that1.Builder { - return false - } - if !bytes.Equal(this.CodeHash, that1.CodeHash) { - return false - } - return true -} - -func (this *InstantiateContractProposal) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*InstantiateContractProposal) - if !ok { - that2, ok := that.(InstantiateContractProposal) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Title != that1.Title { - return false - } - if this.Description != that1.Description { - return false - } - if this.RunAs != that1.RunAs { - return false - } - if this.Admin != that1.Admin { - return false - } - if this.CodeID != that1.CodeID { - return false - } - if this.Label != that1.Label { - return false - } - if !bytes.Equal(this.Msg, that1.Msg) { - return false - } - if len(this.Funds) != len(that1.Funds) { - return false - } - for i := range this.Funds { - if !this.Funds[i].Equal(&that1.Funds[i]) { - return false - } - } - return true -} - -func (this *InstantiateContract2Proposal) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*InstantiateContract2Proposal) - if !ok { - that2, ok := that.(InstantiateContract2Proposal) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Title != that1.Title { - return false - } - if this.Description != that1.Description { - return false - } - if this.RunAs != that1.RunAs { - return false - } - if this.Admin != that1.Admin { - return false - } - if this.CodeID != that1.CodeID { - return false - } - if this.Label != that1.Label { - return false - } - if !bytes.Equal(this.Msg, that1.Msg) { - return false - } - if len(this.Funds) != len(that1.Funds) { - return false - } - for i := range this.Funds { - if !this.Funds[i].Equal(&that1.Funds[i]) { - return false - } - } - if !bytes.Equal(this.Salt, that1.Salt) { - return false - } - if this.FixMsg != that1.FixMsg { - return false - } - return true -} - -func (this *MigrateContractProposal) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*MigrateContractProposal) - if !ok { - that2, ok := that.(MigrateContractProposal) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Title != that1.Title { - return false - } - if this.Description != that1.Description { - return false - } - if this.Contract != that1.Contract { - return false - } - if this.CodeID != that1.CodeID { - return false - } - if !bytes.Equal(this.Msg, that1.Msg) { - return false - } - return true -} - -func (this *SudoContractProposal) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*SudoContractProposal) - if !ok { - that2, ok := that.(SudoContractProposal) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Title != that1.Title { - return false - } - if this.Description != that1.Description { - return false - } - if this.Contract != that1.Contract { - return false - } - if !bytes.Equal(this.Msg, that1.Msg) { - return false - } - return true -} - -func (this *ExecuteContractProposal) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*ExecuteContractProposal) - if !ok { - that2, ok := that.(ExecuteContractProposal) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Title != that1.Title { - return false - } - if this.Description != that1.Description { - return false - } - if this.RunAs != that1.RunAs { - return false - } - if this.Contract != that1.Contract { - return false - } - if !bytes.Equal(this.Msg, that1.Msg) { - return false - } - if len(this.Funds) != len(that1.Funds) { - return false - } - for i := range this.Funds { - if !this.Funds[i].Equal(&that1.Funds[i]) { - return false - } - } - return true -} - -func (this *UpdateAdminProposal) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*UpdateAdminProposal) - if !ok { - that2, ok := that.(UpdateAdminProposal) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Title != that1.Title { - return false - } - if this.Description != that1.Description { - return false - } - if this.NewAdmin != that1.NewAdmin { - return false - } - if this.Contract != that1.Contract { - return false - } - return true -} - -func (this *ClearAdminProposal) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*ClearAdminProposal) - if !ok { - that2, ok := that.(ClearAdminProposal) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Title != that1.Title { - return false - } - if this.Description != that1.Description { - return false - } - if this.Contract != that1.Contract { - return false - } - return true -} - -func (this *PinCodesProposal) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*PinCodesProposal) - if !ok { - that2, ok := that.(PinCodesProposal) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Title != that1.Title { - return false - } - if this.Description != that1.Description { - return false - } - if len(this.CodeIDs) != len(that1.CodeIDs) { - return false - } - for i := range this.CodeIDs { - if this.CodeIDs[i] != that1.CodeIDs[i] { - return false - } - } - return true -} - -func (this *UnpinCodesProposal) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*UnpinCodesProposal) - if !ok { - that2, ok := that.(UnpinCodesProposal) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Title != that1.Title { - return false - } - if this.Description != that1.Description { - return false - } - if len(this.CodeIDs) != len(that1.CodeIDs) { - return false - } - for i := range this.CodeIDs { - if this.CodeIDs[i] != that1.CodeIDs[i] { - return false - } - } - return true -} - -func (this *AccessConfigUpdate) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*AccessConfigUpdate) - if !ok { - that2, ok := that.(AccessConfigUpdate) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.CodeID != that1.CodeID { - return false - } - if !this.InstantiatePermission.Equal(&that1.InstantiatePermission) { - return false - } - return true -} - -func (this *UpdateInstantiateConfigProposal) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*UpdateInstantiateConfigProposal) - if !ok { - that2, ok := that.(UpdateInstantiateConfigProposal) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Title != that1.Title { - return false - } - if this.Description != that1.Description { - return false - } - if len(this.AccessConfigUpdates) != len(that1.AccessConfigUpdates) { - return false - } - for i := range this.AccessConfigUpdates { - if !this.AccessConfigUpdates[i].Equal(&that1.AccessConfigUpdates[i]) { - return false - } - } - return true -} - -func (this *StoreAndInstantiateContractProposal) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*StoreAndInstantiateContractProposal) - if !ok { - that2, ok := that.(StoreAndInstantiateContractProposal) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Title != that1.Title { - return false - } - if this.Description != that1.Description { - return false - } - if this.RunAs != that1.RunAs { - return false - } - if !bytes.Equal(this.WASMByteCode, that1.WASMByteCode) { - return false - } - if !this.InstantiatePermission.Equal(that1.InstantiatePermission) { - return false - } - if this.UnpinCode != that1.UnpinCode { - return false - } - if this.Admin != that1.Admin { - return false - } - if this.Label != that1.Label { - return false - } - if !bytes.Equal(this.Msg, that1.Msg) { - return false - } - if len(this.Funds) != len(that1.Funds) { - return false - } - for i := range this.Funds { - if !this.Funds[i].Equal(&that1.Funds[i]) { - return false - } - } - if this.Source != that1.Source { - return false - } - if this.Builder != that1.Builder { - return false - } - if !bytes.Equal(this.CodeHash, that1.CodeHash) { - return false - } - return true -} - -func (m *StoreCodeProposal) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *StoreCodeProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *StoreCodeProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.CodeHash) > 0 { - i -= len(m.CodeHash) - copy(dAtA[i:], m.CodeHash) - i = encodeVarintProposal(dAtA, i, uint64(len(m.CodeHash))) - i-- - dAtA[i] = 0x5a - } - if len(m.Builder) > 0 { - i -= len(m.Builder) - copy(dAtA[i:], m.Builder) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Builder))) - i-- - dAtA[i] = 0x52 - } - if len(m.Source) > 0 { - i -= len(m.Source) - copy(dAtA[i:], m.Source) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Source))) - i-- - dAtA[i] = 0x4a - } - if m.UnpinCode { - i-- - if m.UnpinCode { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x40 - } - if m.InstantiatePermission != nil { - { - size, err := m.InstantiatePermission.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - } - if len(m.WASMByteCode) > 0 { - i -= len(m.WASMByteCode) - copy(dAtA[i:], m.WASMByteCode) - i = encodeVarintProposal(dAtA, i, uint64(len(m.WASMByteCode))) - i-- - dAtA[i] = 0x22 - } - if len(m.RunAs) > 0 { - i -= len(m.RunAs) - copy(dAtA[i:], m.RunAs) - i = encodeVarintProposal(dAtA, i, uint64(len(m.RunAs))) - i-- - dAtA[i] = 0x1a - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *InstantiateContractProposal) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *InstantiateContractProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *InstantiateContractProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Funds) > 0 { - for iNdEx := len(m.Funds) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Funds[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x42 - } - } - if len(m.Msg) > 0 { - i -= len(m.Msg) - copy(dAtA[i:], m.Msg) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Msg))) - i-- - dAtA[i] = 0x3a - } - if len(m.Label) > 0 { - i -= len(m.Label) - copy(dAtA[i:], m.Label) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Label))) - i-- - dAtA[i] = 0x32 - } - if m.CodeID != 0 { - i = encodeVarintProposal(dAtA, i, uint64(m.CodeID)) - i-- - dAtA[i] = 0x28 - } - if len(m.Admin) > 0 { - i -= len(m.Admin) - copy(dAtA[i:], m.Admin) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Admin))) - i-- - dAtA[i] = 0x22 - } - if len(m.RunAs) > 0 { - i -= len(m.RunAs) - copy(dAtA[i:], m.RunAs) - i = encodeVarintProposal(dAtA, i, uint64(len(m.RunAs))) - i-- - dAtA[i] = 0x1a - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *InstantiateContract2Proposal) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *InstantiateContract2Proposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *InstantiateContract2Proposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.FixMsg { - i-- - if m.FixMsg { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x50 - } - if len(m.Salt) > 0 { - i -= len(m.Salt) - copy(dAtA[i:], m.Salt) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Salt))) - i-- - dAtA[i] = 0x4a - } - if len(m.Funds) > 0 { - for iNdEx := len(m.Funds) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Funds[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x42 - } - } - if len(m.Msg) > 0 { - i -= len(m.Msg) - copy(dAtA[i:], m.Msg) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Msg))) - i-- - dAtA[i] = 0x3a - } - if len(m.Label) > 0 { - i -= len(m.Label) - copy(dAtA[i:], m.Label) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Label))) - i-- - dAtA[i] = 0x32 - } - if m.CodeID != 0 { - i = encodeVarintProposal(dAtA, i, uint64(m.CodeID)) - i-- - dAtA[i] = 0x28 - } - if len(m.Admin) > 0 { - i -= len(m.Admin) - copy(dAtA[i:], m.Admin) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Admin))) - i-- - dAtA[i] = 0x22 - } - if len(m.RunAs) > 0 { - i -= len(m.RunAs) - copy(dAtA[i:], m.RunAs) - i = encodeVarintProposal(dAtA, i, uint64(len(m.RunAs))) - i-- - dAtA[i] = 0x1a - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MigrateContractProposal) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MigrateContractProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MigrateContractProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Msg) > 0 { - i -= len(m.Msg) - copy(dAtA[i:], m.Msg) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Msg))) - i-- - dAtA[i] = 0x32 - } - if m.CodeID != 0 { - i = encodeVarintProposal(dAtA, i, uint64(m.CodeID)) - i-- - dAtA[i] = 0x28 - } - if len(m.Contract) > 0 { - i -= len(m.Contract) - copy(dAtA[i:], m.Contract) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Contract))) - i-- - dAtA[i] = 0x22 - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *SudoContractProposal) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *SudoContractProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *SudoContractProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Msg) > 0 { - i -= len(m.Msg) - copy(dAtA[i:], m.Msg) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Msg))) - i-- - dAtA[i] = 0x22 - } - if len(m.Contract) > 0 { - i -= len(m.Contract) - copy(dAtA[i:], m.Contract) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Contract))) - i-- - dAtA[i] = 0x1a - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *ExecuteContractProposal) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *ExecuteContractProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ExecuteContractProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Funds) > 0 { - for iNdEx := len(m.Funds) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Funds[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - } - } - if len(m.Msg) > 0 { - i -= len(m.Msg) - copy(dAtA[i:], m.Msg) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Msg))) - i-- - dAtA[i] = 0x2a - } - if len(m.Contract) > 0 { - i -= len(m.Contract) - copy(dAtA[i:], m.Contract) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Contract))) - i-- - dAtA[i] = 0x22 - } - if len(m.RunAs) > 0 { - i -= len(m.RunAs) - copy(dAtA[i:], m.RunAs) - i = encodeVarintProposal(dAtA, i, uint64(len(m.RunAs))) - i-- - dAtA[i] = 0x1a - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *UpdateAdminProposal) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *UpdateAdminProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *UpdateAdminProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Contract) > 0 { - i -= len(m.Contract) - copy(dAtA[i:], m.Contract) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Contract))) - i-- - dAtA[i] = 0x22 - } - if len(m.NewAdmin) > 0 { - i -= len(m.NewAdmin) - copy(dAtA[i:], m.NewAdmin) - i = encodeVarintProposal(dAtA, i, uint64(len(m.NewAdmin))) - i-- - dAtA[i] = 0x1a - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *ClearAdminProposal) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *ClearAdminProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ClearAdminProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Contract) > 0 { - i -= len(m.Contract) - copy(dAtA[i:], m.Contract) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Contract))) - i-- - dAtA[i] = 0x1a - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *PinCodesProposal) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *PinCodesProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *PinCodesProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.CodeIDs) > 0 { - dAtA3 := make([]byte, len(m.CodeIDs)*10) - var j2 int - for _, num := range m.CodeIDs { - for num >= 1<<7 { - dAtA3[j2] = uint8(uint64(num)&0x7f | 0x80) - num >>= 7 - j2++ - } - dAtA3[j2] = uint8(num) - j2++ - } - i -= j2 - copy(dAtA[i:], dAtA3[:j2]) - i = encodeVarintProposal(dAtA, i, uint64(j2)) - i-- - dAtA[i] = 0x1a - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *UnpinCodesProposal) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *UnpinCodesProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *UnpinCodesProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.CodeIDs) > 0 { - dAtA5 := make([]byte, len(m.CodeIDs)*10) - var j4 int - for _, num := range m.CodeIDs { - for num >= 1<<7 { - dAtA5[j4] = uint8(uint64(num)&0x7f | 0x80) - num >>= 7 - j4++ - } - dAtA5[j4] = uint8(num) - j4++ - } - i -= j4 - copy(dAtA[i:], dAtA5[:j4]) - i = encodeVarintProposal(dAtA, i, uint64(j4)) - i-- - dAtA[i] = 0x1a - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *AccessConfigUpdate) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *AccessConfigUpdate) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AccessConfigUpdate) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.InstantiatePermission.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if m.CodeID != 0 { - i = encodeVarintProposal(dAtA, i, uint64(m.CodeID)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *UpdateInstantiateConfigProposal) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *UpdateInstantiateConfigProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *UpdateInstantiateConfigProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.AccessConfigUpdates) > 0 { - for iNdEx := len(m.AccessConfigUpdates) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.AccessConfigUpdates[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *StoreAndInstantiateContractProposal) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *StoreAndInstantiateContractProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *StoreAndInstantiateContractProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.CodeHash) > 0 { - i -= len(m.CodeHash) - copy(dAtA[i:], m.CodeHash) - i = encodeVarintProposal(dAtA, i, uint64(len(m.CodeHash))) - i-- - dAtA[i] = 0x6a - } - if len(m.Builder) > 0 { - i -= len(m.Builder) - copy(dAtA[i:], m.Builder) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Builder))) - i-- - dAtA[i] = 0x62 - } - if len(m.Source) > 0 { - i -= len(m.Source) - copy(dAtA[i:], m.Source) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Source))) - i-- - dAtA[i] = 0x5a - } - if len(m.Funds) > 0 { - for iNdEx := len(m.Funds) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Funds[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x52 - } - } - if len(m.Msg) > 0 { - i -= len(m.Msg) - copy(dAtA[i:], m.Msg) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Msg))) - i-- - dAtA[i] = 0x4a - } - if len(m.Label) > 0 { - i -= len(m.Label) - copy(dAtA[i:], m.Label) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Label))) - i-- - dAtA[i] = 0x42 - } - if len(m.Admin) > 0 { - i -= len(m.Admin) - copy(dAtA[i:], m.Admin) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Admin))) - i-- - dAtA[i] = 0x3a - } - if m.UnpinCode { - i-- - if m.UnpinCode { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x30 - } - if m.InstantiatePermission != nil { - { - size, err := m.InstantiatePermission.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - } - if len(m.WASMByteCode) > 0 { - i -= len(m.WASMByteCode) - copy(dAtA[i:], m.WASMByteCode) - i = encodeVarintProposal(dAtA, i, uint64(len(m.WASMByteCode))) - i-- - dAtA[i] = 0x22 - } - if len(m.RunAs) > 0 { - i -= len(m.RunAs) - copy(dAtA[i:], m.RunAs) - i = encodeVarintProposal(dAtA, i, uint64(len(m.RunAs))) - i-- - dAtA[i] = 0x1a - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintProposal(dAtA []byte, offset int, v uint64) int { - offset -= sovProposal(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} - -func (m *StoreCodeProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.RunAs) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.WASMByteCode) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if m.InstantiatePermission != nil { - l = m.InstantiatePermission.Size() - n += 1 + l + sovProposal(uint64(l)) - } - if m.UnpinCode { - n += 2 - } - l = len(m.Source) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Builder) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.CodeHash) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - return n -} - -func (m *InstantiateContractProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.RunAs) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Admin) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if m.CodeID != 0 { - n += 1 + sovProposal(uint64(m.CodeID)) - } - l = len(m.Label) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Msg) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if len(m.Funds) > 0 { - for _, e := range m.Funds { - l = e.Size() - n += 1 + l + sovProposal(uint64(l)) - } - } - return n -} - -func (m *InstantiateContract2Proposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.RunAs) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Admin) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if m.CodeID != 0 { - n += 1 + sovProposal(uint64(m.CodeID)) - } - l = len(m.Label) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Msg) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if len(m.Funds) > 0 { - for _, e := range m.Funds { - l = e.Size() - n += 1 + l + sovProposal(uint64(l)) - } - } - l = len(m.Salt) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if m.FixMsg { - n += 2 - } - return n -} - -func (m *MigrateContractProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Contract) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if m.CodeID != 0 { - n += 1 + sovProposal(uint64(m.CodeID)) - } - l = len(m.Msg) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - return n -} - -func (m *SudoContractProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Contract) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Msg) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - return n -} - -func (m *ExecuteContractProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.RunAs) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Contract) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Msg) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if len(m.Funds) > 0 { - for _, e := range m.Funds { - l = e.Size() - n += 1 + l + sovProposal(uint64(l)) - } - } - return n -} - -func (m *UpdateAdminProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.NewAdmin) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Contract) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - return n -} - -func (m *ClearAdminProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Contract) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - return n -} - -func (m *PinCodesProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if len(m.CodeIDs) > 0 { - l = 0 - for _, e := range m.CodeIDs { - l += sovProposal(uint64(e)) - } - n += 1 + sovProposal(uint64(l)) + l - } - return n -} - -func (m *UnpinCodesProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if len(m.CodeIDs) > 0 { - l = 0 - for _, e := range m.CodeIDs { - l += sovProposal(uint64(e)) - } - n += 1 + sovProposal(uint64(l)) + l - } - return n -} - -func (m *AccessConfigUpdate) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.CodeID != 0 { - n += 1 + sovProposal(uint64(m.CodeID)) - } - l = m.InstantiatePermission.Size() - n += 1 + l + sovProposal(uint64(l)) - return n -} - -func (m *UpdateInstantiateConfigProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if len(m.AccessConfigUpdates) > 0 { - for _, e := range m.AccessConfigUpdates { - l = e.Size() - n += 1 + l + sovProposal(uint64(l)) - } - } - return n -} - -func (m *StoreAndInstantiateContractProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.RunAs) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.WASMByteCode) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if m.InstantiatePermission != nil { - l = m.InstantiatePermission.Size() - n += 1 + l + sovProposal(uint64(l)) - } - if m.UnpinCode { - n += 2 - } - l = len(m.Admin) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Label) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Msg) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if len(m.Funds) > 0 { - for _, e := range m.Funds { - l = e.Size() - n += 1 + l + sovProposal(uint64(l)) - } - } - l = len(m.Source) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Builder) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.CodeHash) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - return n -} - -func sovProposal(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} - -func sozProposal(x uint64) (n int) { - return sovProposal(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} - -func (m *StoreCodeProposal) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: StoreCodeProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: StoreCodeProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RunAs", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RunAs = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field WASMByteCode", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.WASMByteCode = append(m.WASMByteCode[:0], dAtA[iNdEx:postIndex]...) - if m.WASMByteCode == nil { - m.WASMByteCode = []byte{} - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field InstantiatePermission", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.InstantiatePermission == nil { - m.InstantiatePermission = &AccessConfig{} - } - if err := m.InstantiatePermission.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field UnpinCode", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.UnpinCode = bool(v != 0) - case 9: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Source", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Source = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 10: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Builder", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Builder = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 11: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeHash", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CodeHash = append(m.CodeHash[:0], dAtA[iNdEx:postIndex]...) - if m.CodeHash == nil { - m.CodeHash = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *InstantiateContractProposal) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: InstantiateContractProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: InstantiateContractProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RunAs", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RunAs = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Admin", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Admin = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) - } - m.CodeID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CodeID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Label", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Label = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Msg = append(m.Msg[:0], dAtA[iNdEx:postIndex]...) - if m.Msg == nil { - m.Msg = []byte{} - } - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Funds", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Funds = append(m.Funds, types.Coin{}) - if err := m.Funds[len(m.Funds)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *InstantiateContract2Proposal) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: InstantiateContract2Proposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: InstantiateContract2Proposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RunAs", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RunAs = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Admin", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Admin = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) - } - m.CodeID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CodeID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Label", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Label = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Msg = append(m.Msg[:0], dAtA[iNdEx:postIndex]...) - if m.Msg == nil { - m.Msg = []byte{} - } - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Funds", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Funds = append(m.Funds, types.Coin{}) - if err := m.Funds[len(m.Funds)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 9: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Salt", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Salt = append(m.Salt[:0], dAtA[iNdEx:postIndex]...) - if m.Salt == nil { - m.Salt = []byte{} - } - iNdEx = postIndex - case 10: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field FixMsg", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.FixMsg = bool(v != 0) - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MigrateContractProposal) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MigrateContractProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MigrateContractProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Contract", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Contract = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) - } - m.CodeID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CodeID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Msg = append(m.Msg[:0], dAtA[iNdEx:postIndex]...) - if m.Msg == nil { - m.Msg = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *SudoContractProposal) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: SudoContractProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: SudoContractProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Contract", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Contract = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Msg = append(m.Msg[:0], dAtA[iNdEx:postIndex]...) - if m.Msg == nil { - m.Msg = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *ExecuteContractProposal) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: ExecuteContractProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ExecuteContractProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RunAs", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RunAs = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Contract", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Contract = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Msg = append(m.Msg[:0], dAtA[iNdEx:postIndex]...) - if m.Msg == nil { - m.Msg = []byte{} - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Funds", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Funds = append(m.Funds, types.Coin{}) - if err := m.Funds[len(m.Funds)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *UpdateAdminProposal) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: UpdateAdminProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: UpdateAdminProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NewAdmin", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.NewAdmin = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Contract", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Contract = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *ClearAdminProposal) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: ClearAdminProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ClearAdminProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Contract", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Contract = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *PinCodesProposal) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: PinCodesProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: PinCodesProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType == 0 { - var v uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.CodeIDs = append(m.CodeIDs, v) - } else if wireType == 2 { - var packedLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - packedLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if packedLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + packedLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - var elementCount int - var count int - for _, integer := range dAtA[iNdEx:postIndex] { - if integer < 128 { - count++ - } - } - elementCount = count - if elementCount != 0 && len(m.CodeIDs) == 0 { - m.CodeIDs = make([]uint64, 0, elementCount) - } - for iNdEx < postIndex { - var v uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.CodeIDs = append(m.CodeIDs, v) - } - } else { - return fmt.Errorf("proto: wrong wireType = %d for field CodeIDs", wireType) - } - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *UnpinCodesProposal) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: UnpinCodesProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: UnpinCodesProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType == 0 { - var v uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.CodeIDs = append(m.CodeIDs, v) - } else if wireType == 2 { - var packedLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - packedLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if packedLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + packedLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - var elementCount int - var count int - for _, integer := range dAtA[iNdEx:postIndex] { - if integer < 128 { - count++ - } - } - elementCount = count - if elementCount != 0 && len(m.CodeIDs) == 0 { - m.CodeIDs = make([]uint64, 0, elementCount) - } - for iNdEx < postIndex { - var v uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.CodeIDs = append(m.CodeIDs, v) - } - } else { - return fmt.Errorf("proto: wrong wireType = %d for field CodeIDs", wireType) - } - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *AccessConfigUpdate) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: AccessConfigUpdate: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AccessConfigUpdate: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) - } - m.CodeID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CodeID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field InstantiatePermission", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.InstantiatePermission.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *UpdateInstantiateConfigProposal) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: UpdateInstantiateConfigProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: UpdateInstantiateConfigProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AccessConfigUpdates", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.AccessConfigUpdates = append(m.AccessConfigUpdates, AccessConfigUpdate{}) - if err := m.AccessConfigUpdates[len(m.AccessConfigUpdates)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *StoreAndInstantiateContractProposal) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: StoreAndInstantiateContractProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: StoreAndInstantiateContractProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RunAs", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RunAs = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field WASMByteCode", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.WASMByteCode = append(m.WASMByteCode[:0], dAtA[iNdEx:postIndex]...) - if m.WASMByteCode == nil { - m.WASMByteCode = []byte{} - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field InstantiatePermission", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.InstantiatePermission == nil { - m.InstantiatePermission = &AccessConfig{} - } - if err := m.InstantiatePermission.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field UnpinCode", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.UnpinCode = bool(v != 0) - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Admin", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Admin = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Label", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Label = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 9: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Msg = append(m.Msg[:0], dAtA[iNdEx:postIndex]...) - if m.Msg == nil { - m.Msg = []byte{} - } - iNdEx = postIndex - case 10: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Funds", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Funds = append(m.Funds, types.Coin{}) - if err := m.Funds[len(m.Funds)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 11: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Source", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Source = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 12: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Builder", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Builder = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 13: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeHash", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CodeHash = append(m.CodeHash[:0], dAtA[iNdEx:postIndex]...) - if m.CodeHash == nil { - m.CodeHash = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func skipProposal(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowProposal - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowProposal - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowProposal - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthProposal - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupProposal - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthProposal - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthProposal = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowProposal = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupProposal = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/wasm/types/proposal_test.go b/x/wasm/types/proposal_test.go deleted file mode 100644 index 8952f8c..0000000 --- a/x/wasm/types/proposal_test.go +++ /dev/null @@ -1,1123 +0,0 @@ -package types - -import ( - "bytes" - "encoding/json" - "strings" - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "gopkg.in/yaml.v2" -) - -func TestValidateProposalCommons(t *testing.T) { - type commonProposal struct { - Title, Description string - } - - specs := map[string]struct { - src commonProposal - expErr bool - }{ - "all good": {src: commonProposal{ - Title: "Foo", - Description: "Bar", - }}, - "prevent empty title": { - src: commonProposal{ - Description: "Bar", - }, - expErr: true, - }, - "prevent white space only title": { - src: commonProposal{ - Title: " ", - Description: "Bar", - }, - expErr: true, - }, - "prevent leading white spaces in title": { - src: commonProposal{ - Title: " Foo", - Description: "Bar", - }, - expErr: true, - }, - "prevent title exceeds max length ": { - src: commonProposal{ - Title: strings.Repeat("a", v1beta1.MaxTitleLength+1), - Description: "Bar", - }, - expErr: true, - }, - "prevent empty description": { - src: commonProposal{ - Title: "Foo", - }, - expErr: true, - }, - "prevent leading white spaces in description": { - src: commonProposal{ - Title: "Foo", - Description: " Bar", - }, - expErr: true, - }, - "prevent white space only description": { - src: commonProposal{ - Title: "Foo", - Description: " ", - }, - expErr: true, - }, - "prevent descr exceeds max length ": { - src: commonProposal{ - Title: "Foo", - Description: strings.Repeat("a", v1beta1.MaxDescriptionLength+1), - }, - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := validateProposalCommons(spec.src.Title, spec.src.Description) - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestValidateStoreCodeProposal(t *testing.T) { - var anyAddress sdk.AccAddress = bytes.Repeat([]byte{0x0}, ContractAddrLen) - - specs := map[string]struct { - src *StoreCodeProposal - expErr bool - }{ - "all good": { - src: StoreCodeProposalFixture(), - }, - "all good no code verification info": { - src: StoreCodeProposalFixture(func(p *StoreCodeProposal) { - p.Source = "" - p.Builder = "" - p.CodeHash = nil - }), - }, - "source missing": { - src: StoreCodeProposalFixture(func(p *StoreCodeProposal) { - p.Source = "" - }), - expErr: true, - }, - "builder missing": { - src: StoreCodeProposalFixture(func(p *StoreCodeProposal) { - p.Builder = "" - }), - expErr: true, - }, - "code hash missing": { - src: StoreCodeProposalFixture(func(p *StoreCodeProposal) { - p.CodeHash = nil - }), - expErr: true, - }, - "with instantiate permission": { - src: StoreCodeProposalFixture(func(p *StoreCodeProposal) { - accessConfig := AccessTypeOnlyAddress.With(anyAddress) - p.InstantiatePermission = &accessConfig - }), - }, - "base data missing": { - src: StoreCodeProposalFixture(func(p *StoreCodeProposal) { - p.Title = "" - }), - expErr: true, - }, - "run_as missing": { - src: StoreCodeProposalFixture(func(p *StoreCodeProposal) { - p.RunAs = "" - }), - expErr: true, - }, - "run_as invalid": { - src: StoreCodeProposalFixture(func(p *StoreCodeProposal) { - p.RunAs = invalidAddress - }), - expErr: true, - }, - "wasm code missing": { - src: StoreCodeProposalFixture(func(p *StoreCodeProposal) { - p.WASMByteCode = nil - }), - expErr: true, - }, - "wasm code invalid": { - src: StoreCodeProposalFixture(func(p *StoreCodeProposal) { - p.WASMByteCode = bytes.Repeat([]byte{0x0}, MaxProposalWasmSize+1) - }), - expErr: true, - }, - "with invalid instantiate permission": { - src: StoreCodeProposalFixture(func(p *StoreCodeProposal) { - p.InstantiatePermission = &AccessConfig{} - }), - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestValidateInstantiateContractProposal(t *testing.T) { - specs := map[string]struct { - src *InstantiateContractProposal - expErr bool - }{ - "all good": { - src: InstantiateContractProposalFixture(), - }, - "without admin": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { - p.Admin = "" - }), - }, - "without init msg": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { - p.Msg = nil - }), - expErr: true, - }, - "with invalid init msg": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { - p.Msg = []byte("not a json string") - }), - expErr: true, - }, - "without init funds": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { - p.Funds = nil - }), - }, - "base data missing": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { - p.Title = "" - }), - expErr: true, - }, - "run_as missing": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { - p.RunAs = "" - }), - expErr: true, - }, - "run_as invalid": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { - p.RunAs = invalidAddress - }), - expErr: true, - }, - "admin invalid": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { - p.Admin = invalidAddress - }), - expErr: true, - }, - "code id empty": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { - p.CodeID = 0 - }), - expErr: true, - }, - "label empty": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { - p.Label = "" - }), - expErr: true, - }, - "init funds negative": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { - p.Funds = sdk.Coins{{Denom: "foo", Amount: sdk.NewInt(-1)}} - }), - expErr: true, - }, - "init funds with duplicates": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { - p.Funds = sdk.Coins{{Denom: "foo", Amount: sdk.NewInt(1)}, {Denom: "foo", Amount: sdk.NewInt(2)}} - }), - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestValidateInstantiateContract2Proposal(t *testing.T) { - specs := map[string]struct { - src *InstantiateContract2Proposal - expErr bool - }{ - "all good": { - src: InstantiateContract2ProposalFixture(), - }, - "without admin": { - src: InstantiateContract2ProposalFixture(func(p *InstantiateContract2Proposal) { - p.Admin = "" - }), - }, - "without init msg": { - src: InstantiateContract2ProposalFixture(func(p *InstantiateContract2Proposal) { - p.Msg = nil - }), - expErr: true, - }, - "with invalid init msg": { - src: InstantiateContract2ProposalFixture(func(p *InstantiateContract2Proposal) { - p.Msg = []byte("not a json string") - }), - expErr: true, - }, - "without init funds": { - src: InstantiateContract2ProposalFixture(func(p *InstantiateContract2Proposal) { - p.Funds = nil - }), - }, - "base data missing": { - src: InstantiateContract2ProposalFixture(func(p *InstantiateContract2Proposal) { - p.Title = "" - }), - expErr: true, - }, - "run_as missing": { - src: InstantiateContract2ProposalFixture(func(p *InstantiateContract2Proposal) { - p.RunAs = "" - }), - expErr: true, - }, - "run_as invalid": { - src: InstantiateContract2ProposalFixture(func(p *InstantiateContract2Proposal) { - p.RunAs = invalidAddress - }), - expErr: true, - }, - "admin invalid": { - src: InstantiateContract2ProposalFixture(func(p *InstantiateContract2Proposal) { - p.Admin = invalidAddress - }), - expErr: true, - }, - "code id empty": { - src: InstantiateContract2ProposalFixture(func(p *InstantiateContract2Proposal) { - p.CodeID = 0 - }), - expErr: true, - }, - "label empty": { - src: InstantiateContract2ProposalFixture(func(p *InstantiateContract2Proposal) { - p.Label = "" - }), - expErr: true, - }, - "init funds negative": { - src: InstantiateContract2ProposalFixture(func(p *InstantiateContract2Proposal) { - p.Funds = sdk.Coins{{Denom: "foo", Amount: sdk.NewInt(-1)}} - }), - expErr: true, - }, - "init funds with duplicates": { - src: InstantiateContract2ProposalFixture(func(p *InstantiateContract2Proposal) { - p.Funds = sdk.Coins{{Denom: "foo", Amount: sdk.NewInt(1)}, {Denom: "foo", Amount: sdk.NewInt(2)}} - }), - expErr: true, - }, - "init with empty salt": { - src: InstantiateContract2ProposalFixture(func(p *InstantiateContract2Proposal) { - p.Salt = nil - }), - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestValidateStoreAndInstantiateContractProposal(t *testing.T) { - var anyAddress sdk.AccAddress = bytes.Repeat([]byte{0x0}, ContractAddrLen) - - specs := map[string]struct { - src *StoreAndInstantiateContractProposal - expErr bool - }{ - "all good": { - src: StoreAndInstantiateContractProposalFixture(), - }, - "all good no code verification info": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.Source = "" - p.Builder = "" - p.CodeHash = nil - }), - }, - "source missing": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.Source = "" - }), - expErr: true, - }, - "builder missing": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.Builder = "" - }), - expErr: true, - }, - "code hash missing": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.CodeHash = nil - }), - expErr: true, - }, - "with instantiate permission": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - accessConfig := AccessTypeOnlyAddress.With(anyAddress) - p.InstantiatePermission = &accessConfig - }), - }, - "base data missing": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.Title = "" - }), - expErr: true, - }, - "run_as missing": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.RunAs = "" - }), - expErr: true, - }, - "run_as invalid": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.RunAs = invalidAddress - }), - expErr: true, - }, - "wasm code missing": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.WASMByteCode = nil - }), - expErr: true, - }, - "wasm code invalid": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.WASMByteCode = bytes.Repeat([]byte{0x0}, MaxProposalWasmSize+1) - }), - expErr: true, - }, - "with invalid instantiate permission": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.InstantiatePermission = &AccessConfig{} - }), - expErr: true, - }, - "without admin": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.Admin = "" - }), - }, - "without init msg": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.Msg = nil - }), - expErr: true, - }, - "with invalid init msg": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.Msg = []byte("not a json string") - }), - expErr: true, - }, - "without init funds": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.Funds = nil - }), - }, - "admin invalid": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.Admin = invalidAddress - }), - expErr: true, - }, - "label empty": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.Label = "" - }), - expErr: true, - }, - "init funds negative": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.Funds = sdk.Coins{{Denom: "foo", Amount: sdk.NewInt(-1)}} - }), - expErr: true, - }, - "init funds with duplicates": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.Funds = sdk.Coins{{Denom: "foo", Amount: sdk.NewInt(1)}, {Denom: "foo", Amount: sdk.NewInt(2)}} - }), - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestValidateMigrateContractProposal(t *testing.T) { - invalidAddress := "invalid address2" - - specs := map[string]struct { - src *MigrateContractProposal - expErr bool - }{ - "all good": { - src: MigrateContractProposalFixture(), - }, - "without migrate msg": { - src: MigrateContractProposalFixture(func(p *MigrateContractProposal) { - p.Msg = nil - }), - expErr: true, - }, - "migrate msg with invalid json": { - src: MigrateContractProposalFixture(func(p *MigrateContractProposal) { - p.Msg = []byte("not a json message") - }), - expErr: true, - }, - "base data missing": { - src: MigrateContractProposalFixture(func(p *MigrateContractProposal) { - p.Title = "" - }), - expErr: true, - }, - "contract missing": { - src: MigrateContractProposalFixture(func(p *MigrateContractProposal) { - p.Contract = "" - }), - expErr: true, - }, - "contract invalid": { - src: MigrateContractProposalFixture(func(p *MigrateContractProposal) { - p.Contract = invalidAddress - }), - expErr: true, - }, - "code id empty": { - src: MigrateContractProposalFixture(func(p *MigrateContractProposal) { - p.CodeID = 0 - }), - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestValidateSudoContractProposal(t *testing.T) { - specs := map[string]struct { - src *SudoContractProposal - expErr bool - }{ - "all good": { - src: SudoContractProposalFixture(), - }, - "msg is nil": { - src: SudoContractProposalFixture(func(p *SudoContractProposal) { - p.Msg = nil - }), - expErr: true, - }, - "msg with invalid json": { - src: SudoContractProposalFixture(func(p *SudoContractProposal) { - p.Msg = []byte("not a json message") - }), - expErr: true, - }, - "base data missing": { - src: SudoContractProposalFixture(func(p *SudoContractProposal) { - p.Title = "" - }), - expErr: true, - }, - "contract missing": { - src: SudoContractProposalFixture(func(p *SudoContractProposal) { - p.Contract = "" - }), - expErr: true, - }, - "contract invalid": { - src: SudoContractProposalFixture(func(p *SudoContractProposal) { - p.Contract = invalidAddress - }), - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestValidateExecuteContractProposal(t *testing.T) { - specs := map[string]struct { - src *ExecuteContractProposal - expErr bool - }{ - "all good": { - src: ExecuteContractProposalFixture(), - }, - "msg is nil": { - src: ExecuteContractProposalFixture(func(p *ExecuteContractProposal) { - p.Msg = nil - }), - expErr: true, - }, - "msg with invalid json": { - src: ExecuteContractProposalFixture(func(p *ExecuteContractProposal) { - p.Msg = []byte("not a valid json message") - }), - expErr: true, - }, - "base data missing": { - src: ExecuteContractProposalFixture(func(p *ExecuteContractProposal) { - p.Title = "" - }), - expErr: true, - }, - "contract missing": { - src: ExecuteContractProposalFixture(func(p *ExecuteContractProposal) { - p.Contract = "" - }), - expErr: true, - }, - "contract invalid": { - src: ExecuteContractProposalFixture(func(p *ExecuteContractProposal) { - p.Contract = invalidAddress - }), - expErr: true, - }, - "run as is invalid": { - src: ExecuteContractProposalFixture(func(p *ExecuteContractProposal) { - p.RunAs = invalidAddress - }), - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestValidateUpdateAdminProposal(t *testing.T) { - specs := map[string]struct { - src *UpdateAdminProposal - expErr bool - }{ - "all good": { - src: UpdateAdminProposalFixture(), - }, - "base data missing": { - src: UpdateAdminProposalFixture(func(p *UpdateAdminProposal) { - p.Title = "" - }), - expErr: true, - }, - "contract missing": { - src: UpdateAdminProposalFixture(func(p *UpdateAdminProposal) { - p.Contract = "" - }), - expErr: true, - }, - "contract invalid": { - src: UpdateAdminProposalFixture(func(p *UpdateAdminProposal) { - p.Contract = invalidAddress - }), - expErr: true, - }, - "admin missing": { - src: UpdateAdminProposalFixture(func(p *UpdateAdminProposal) { - p.NewAdmin = "" - }), - expErr: true, - }, - "admin invalid": { - src: UpdateAdminProposalFixture(func(p *UpdateAdminProposal) { - p.NewAdmin = invalidAddress - }), - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestValidateClearAdminProposal(t *testing.T) { - specs := map[string]struct { - src *ClearAdminProposal - expErr bool - }{ - "all good": { - src: ClearAdminProposalFixture(), - }, - "base data missing": { - src: ClearAdminProposalFixture(func(p *ClearAdminProposal) { - p.Title = "" - }), - expErr: true, - }, - "contract missing": { - src: ClearAdminProposalFixture(func(p *ClearAdminProposal) { - p.Contract = "" - }), - expErr: true, - }, - "contract invalid": { - src: ClearAdminProposalFixture(func(p *ClearAdminProposal) { - p.Contract = invalidAddress - }), - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestProposalStrings(t *testing.T) { - specs := map[string]struct { - src v1beta1.Content - exp string - }{ - "store code": { - src: StoreCodeProposalFixture(func(p *StoreCodeProposal) { - p.WASMByteCode = []byte{0o1, 0o2, 0o3, 0o4, 0o5, 0o6, 0o7, 0x08, 0x09, 0x0a} - }), - exp: `Store Code Proposal: - Title: Foo - Description: Bar - Run as: cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4 - WasmCode: 0102030405060708090A - Source: https://example.com/ - Builder: cosmwasm/workspace-optimizer:v0.12.8 - Code Hash: 6E340B9CFFB37A989CA544E6BB780A2C78901D3FB33738768511A30617AFA01D -`, - }, - "instantiate contract": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { - p.Funds = sdk.Coins{{Denom: "foo", Amount: sdk.NewInt(1)}, {Denom: "bar", Amount: sdk.NewInt(2)}} - }), - exp: `Instantiate Code Proposal: - Title: Foo - Description: Bar - Run as: cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4 - Admin: cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4 - Code id: 1 - Label: testing - Msg: "{\"verifier\":\"cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4\",\"beneficiary\":\"cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4\"}" - Funds: 1foo,2bar -`, - }, - "instantiate contract without funds": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { p.Funds = nil }), - exp: `Instantiate Code Proposal: - Title: Foo - Description: Bar - Run as: cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4 - Admin: cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4 - Code id: 1 - Label: testing - Msg: "{\"verifier\":\"cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4\",\"beneficiary\":\"cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4\"}" - Funds: -`, - }, - "instantiate contract without admin": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { p.Admin = "" }), - exp: `Instantiate Code Proposal: - Title: Foo - Description: Bar - Run as: cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4 - Admin: - Code id: 1 - Label: testing - Msg: "{\"verifier\":\"cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4\",\"beneficiary\":\"cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4\"}" - Funds: -`, - }, - "migrate contract": { - src: MigrateContractProposalFixture(), - exp: `Migrate Contract Proposal: - Title: Foo - Description: Bar - Contract: cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr - Code id: 1 - Msg: "{\"verifier\":\"cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4\"}" -`, - }, - "update admin": { - src: UpdateAdminProposalFixture(), - exp: `Update Contract Admin Proposal: - Title: Foo - Description: Bar - Contract: cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr - New Admin: cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4 -`, - }, - "clear admin": { - src: ClearAdminProposalFixture(), - exp: `Clear Contract Admin Proposal: - Title: Foo - Description: Bar - Contract: cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr -`, - }, - "pin codes": { - src: &PinCodesProposal{ - Title: "Foo", - Description: "Bar", - CodeIDs: []uint64{1, 2, 3}, - }, - exp: `Pin Wasm Codes Proposal: - Title: Foo - Description: Bar - Codes: [1 2 3] -`, - }, - "unpin codes": { - src: &UnpinCodesProposal{ - Title: "Foo", - Description: "Bar", - CodeIDs: []uint64{3, 2, 1}, - }, - exp: `Unpin Wasm Codes Proposal: - Title: Foo - Description: Bar - Codes: [3 2 1] -`, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - assert.Equal(t, spec.exp, spec.src.String()) - }) - } -} - -func TestProposalYaml(t *testing.T) { - specs := map[string]struct { - src v1beta1.Content - exp string - }{ - "store code": { - src: StoreCodeProposalFixture(func(p *StoreCodeProposal) { - p.WASMByteCode = []byte{0o1, 0o2, 0o3, 0o4, 0o5, 0o6, 0o7, 0x08, 0x09, 0x0a} - }), - exp: `title: Foo -description: Bar -run_as: cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4 -wasm_byte_code: AQIDBAUGBwgJCg== -instantiate_permission: null -source: https://example.com/ -builder: cosmwasm/workspace-optimizer:v0.12.8 -code_hash: 6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d -`, - }, - "instantiate contract": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { - p.Funds = sdk.Coins{{Denom: "foo", Amount: sdk.NewInt(1)}, {Denom: "bar", Amount: sdk.NewInt(2)}} - }), - exp: `title: Foo -description: Bar -run_as: cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4 -admin: cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4 -code_id: 1 -label: testing -msg: '{"verifier":"cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4","beneficiary":"cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4"}' -funds: -- denom: foo - amount: "1" -- denom: bar - amount: "2" -`, - }, - "instantiate contract without funds": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { p.Funds = nil }), - exp: `title: Foo -description: Bar -run_as: cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4 -admin: cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4 -code_id: 1 -label: testing -msg: '{"verifier":"cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4","beneficiary":"cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4"}' -funds: [] -`, - }, - "instantiate contract without admin": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { p.Admin = "" }), - exp: `title: Foo -description: Bar -run_as: cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4 -admin: "" -code_id: 1 -label: testing -msg: '{"verifier":"cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4","beneficiary":"cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4"}' -funds: [] -`, - }, - "migrate contract": { - src: MigrateContractProposalFixture(), - exp: `title: Foo -description: Bar -contract: cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr -code_id: 1 -msg: '{"verifier":"cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4"}' -`, - }, - "update admin": { - src: UpdateAdminProposalFixture(), - exp: `title: Foo -description: Bar -new_admin: cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4 -contract: cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr -`, - }, - "clear admin": { - src: ClearAdminProposalFixture(), - exp: `title: Foo -description: Bar -contract: cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr -`, - }, - "pin codes": { - src: &PinCodesProposal{ - Title: "Foo", - Description: "Bar", - CodeIDs: []uint64{1, 2, 3}, - }, - exp: `title: Foo -description: Bar -code_ids: -- 1 -- 2 -- 3 -`, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - v, err := yaml.Marshal(&spec.src) - require.NoError(t, err) - assert.Equal(t, spec.exp, string(v)) - }) - } -} - -func TestConvertToProposals(t *testing.T) { - cases := map[string]struct { - input string - isError bool - proposals []ProposalType - }{ - "one proper item": { - input: "UpdateAdmin", - proposals: []ProposalType{ProposalTypeUpdateAdmin}, - }, - "multiple proper items": { - input: "StoreCode,InstantiateContract,MigrateContract", - proposals: []ProposalType{ProposalTypeStoreCode, ProposalTypeInstantiateContract, ProposalTypeMigrateContract}, - }, - "empty trailing item": { - input: "StoreCode,", - isError: true, - }, - "invalid item": { - input: "StoreCode,InvalidProposalType", - isError: true, - }, - } - - for name, tc := range cases { - t.Run(name, func(t *testing.T) { - chunks := strings.Split(tc.input, ",") - proposals, err := ConvertToProposals(chunks) - if tc.isError { - require.Error(t, err) - } else { - require.NoError(t, err) - require.Equal(t, proposals, tc.proposals) - } - }) - } -} - -func TestUnmarshalContentFromJson(t *testing.T) { - specs := map[string]struct { - src string - got v1beta1.Content - exp v1beta1.Content - }{ - "instantiate ": { - src: ` -{ - "title": "foo", - "description": "bar", - "admin": "myAdminAddress", - "code_id": 1, - "funds": [{"denom": "ALX", "amount": "2"},{"denom": "BLX","amount": "3"}], - "msg": {}, - "label": "testing", - "run_as": "myRunAsAddress" -}`, - got: &InstantiateContractProposal{}, - exp: &InstantiateContractProposal{ - Title: "foo", - Description: "bar", - RunAs: "myRunAsAddress", - Admin: "myAdminAddress", - CodeID: 1, - Label: "testing", - Msg: []byte("{}"), - Funds: sdk.NewCoins(sdk.NewCoin("ALX", sdk.NewInt(2)), sdk.NewCoin("BLX", sdk.NewInt(3))), - }, - }, - "migrate ": { - src: ` -{ - "title": "foo", - "description": "bar", - "code_id": 1, - "contract": "myContractAddr", - "msg": {}, - "run_as": "myRunAsAddress" -}`, - got: &MigrateContractProposal{}, - exp: &MigrateContractProposal{ - Title: "foo", - Description: "bar", - Contract: "myContractAddr", - CodeID: 1, - Msg: []byte("{}"), - }, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - require.NoError(t, json.Unmarshal([]byte(spec.src), spec.got)) - assert.Equal(t, spec.exp, spec.got) - }) - } -} - -func TestProposalJsonSignBytes(t *testing.T) { - const myInnerMsg = `{"foo":"bar"}` - specs := map[string]struct { - src v1beta1.Content - exp string - }{ - "instantiate contract": { - src: &InstantiateContractProposal{Msg: RawContractMessage(myInnerMsg)}, - exp: ` -{ - "type":"cosmos-sdk/MsgSubmitProposal", - "value":{"content":{"type":"wasm/InstantiateContractProposal","value":{"funds":[],"msg":{"foo":"bar"}}},"initial_deposit":[]} -}`, - }, - "migrate contract": { - src: &MigrateContractProposal{Msg: RawContractMessage(myInnerMsg)}, - exp: ` -{ - "type":"cosmos-sdk/MsgSubmitProposal", - "value":{"content":{"type":"wasm/MigrateContractProposal","value":{"msg":{"foo":"bar"}}},"initial_deposit":[]} -}`, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - msg, err := v1beta1.NewMsgSubmitProposal(spec.src, sdk.NewCoins(), []byte{}) - require.NoError(t, err) - - bz := msg.GetSignBytes() - assert.JSONEq(t, spec.exp, string(bz), "exp %s\n got: %s\n", spec.exp, string(bz)) - }) - } -} diff --git a/x/wasm/types/query.pb.go b/x/wasm/types/query.pb.go deleted file mode 100644 index 0104998..0000000 --- a/x/wasm/types/query.pb.go +++ /dev/null @@ -1,5639 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmwasm/wasm/v1/query.proto - -package types - -import ( - bytes "bytes" - context "context" - fmt "fmt" - io "io" - math "math" - math_bits "math/bits" - - github_com_cometbft_cometbft_libs_bytes "github.com/cometbft/cometbft/libs/bytes" - query "github.com/cosmos/cosmos-sdk/types/query" - _ "github.com/cosmos/cosmos-sdk/types/tx/amino" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - _ "google.golang.org/genproto/googleapis/api/annotations" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = proto.Marshal - _ = fmt.Errorf - _ = math.Inf -) - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// QueryContractInfoRequest is the request type for the Query/ContractInfo RPC -// method -type QueryContractInfoRequest struct { - // address is the address of the contract to query - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` -} - -func (m *QueryContractInfoRequest) Reset() { *m = QueryContractInfoRequest{} } -func (m *QueryContractInfoRequest) String() string { return proto.CompactTextString(m) } -func (*QueryContractInfoRequest) ProtoMessage() {} -func (*QueryContractInfoRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{0} -} - -func (m *QueryContractInfoRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryContractInfoRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryContractInfoRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *QueryContractInfoRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryContractInfoRequest.Merge(m, src) -} - -func (m *QueryContractInfoRequest) XXX_Size() int { - return m.Size() -} - -func (m *QueryContractInfoRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryContractInfoRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryContractInfoRequest proto.InternalMessageInfo - -// QueryContractInfoResponse is the response type for the Query/ContractInfo RPC -// method -type QueryContractInfoResponse struct { - // address is the address of the contract - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - ContractInfo `protobuf:"bytes,2,opt,name=contract_info,json=contractInfo,proto3,embedded=contract_info" json:""` -} - -func (m *QueryContractInfoResponse) Reset() { *m = QueryContractInfoResponse{} } -func (m *QueryContractInfoResponse) String() string { return proto.CompactTextString(m) } -func (*QueryContractInfoResponse) ProtoMessage() {} -func (*QueryContractInfoResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{1} -} - -func (m *QueryContractInfoResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryContractInfoResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryContractInfoResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *QueryContractInfoResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryContractInfoResponse.Merge(m, src) -} - -func (m *QueryContractInfoResponse) XXX_Size() int { - return m.Size() -} - -func (m *QueryContractInfoResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryContractInfoResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryContractInfoResponse proto.InternalMessageInfo - -// QueryContractHistoryRequest is the request type for the Query/ContractHistory -// RPC method -type QueryContractHistoryRequest struct { - // address is the address of the contract to query - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - // pagination defines an optional pagination for the request. - Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryContractHistoryRequest) Reset() { *m = QueryContractHistoryRequest{} } -func (m *QueryContractHistoryRequest) String() string { return proto.CompactTextString(m) } -func (*QueryContractHistoryRequest) ProtoMessage() {} -func (*QueryContractHistoryRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{2} -} - -func (m *QueryContractHistoryRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryContractHistoryRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryContractHistoryRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *QueryContractHistoryRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryContractHistoryRequest.Merge(m, src) -} - -func (m *QueryContractHistoryRequest) XXX_Size() int { - return m.Size() -} - -func (m *QueryContractHistoryRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryContractHistoryRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryContractHistoryRequest proto.InternalMessageInfo - -// QueryContractHistoryResponse is the response type for the -// Query/ContractHistory RPC method -type QueryContractHistoryResponse struct { - Entries []ContractCodeHistoryEntry `protobuf:"bytes,1,rep,name=entries,proto3" json:"entries"` - // pagination defines the pagination in the response. - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryContractHistoryResponse) Reset() { *m = QueryContractHistoryResponse{} } -func (m *QueryContractHistoryResponse) String() string { return proto.CompactTextString(m) } -func (*QueryContractHistoryResponse) ProtoMessage() {} -func (*QueryContractHistoryResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{3} -} - -func (m *QueryContractHistoryResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryContractHistoryResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryContractHistoryResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *QueryContractHistoryResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryContractHistoryResponse.Merge(m, src) -} - -func (m *QueryContractHistoryResponse) XXX_Size() int { - return m.Size() -} - -func (m *QueryContractHistoryResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryContractHistoryResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryContractHistoryResponse proto.InternalMessageInfo - -// QueryContractsByCodeRequest is the request type for the Query/ContractsByCode -// RPC method -type QueryContractsByCodeRequest struct { - CodeId uint64 `protobuf:"varint,1,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` - // pagination defines an optional pagination for the request. - Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryContractsByCodeRequest) Reset() { *m = QueryContractsByCodeRequest{} } -func (m *QueryContractsByCodeRequest) String() string { return proto.CompactTextString(m) } -func (*QueryContractsByCodeRequest) ProtoMessage() {} -func (*QueryContractsByCodeRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{4} -} - -func (m *QueryContractsByCodeRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryContractsByCodeRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryContractsByCodeRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *QueryContractsByCodeRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryContractsByCodeRequest.Merge(m, src) -} - -func (m *QueryContractsByCodeRequest) XXX_Size() int { - return m.Size() -} - -func (m *QueryContractsByCodeRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryContractsByCodeRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryContractsByCodeRequest proto.InternalMessageInfo - -// QueryContractsByCodeResponse is the response type for the -// Query/ContractsByCode RPC method -type QueryContractsByCodeResponse struct { - // contracts are a set of contract addresses - Contracts []string `protobuf:"bytes,1,rep,name=contracts,proto3" json:"contracts,omitempty"` - // pagination defines the pagination in the response. - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryContractsByCodeResponse) Reset() { *m = QueryContractsByCodeResponse{} } -func (m *QueryContractsByCodeResponse) String() string { return proto.CompactTextString(m) } -func (*QueryContractsByCodeResponse) ProtoMessage() {} -func (*QueryContractsByCodeResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{5} -} - -func (m *QueryContractsByCodeResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryContractsByCodeResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryContractsByCodeResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *QueryContractsByCodeResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryContractsByCodeResponse.Merge(m, src) -} - -func (m *QueryContractsByCodeResponse) XXX_Size() int { - return m.Size() -} - -func (m *QueryContractsByCodeResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryContractsByCodeResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryContractsByCodeResponse proto.InternalMessageInfo - -// QueryAllContractStateRequest is the request type for the -// Query/AllContractState RPC method -type QueryAllContractStateRequest struct { - // address is the address of the contract - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - // pagination defines an optional pagination for the request. - Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryAllContractStateRequest) Reset() { *m = QueryAllContractStateRequest{} } -func (m *QueryAllContractStateRequest) String() string { return proto.CompactTextString(m) } -func (*QueryAllContractStateRequest) ProtoMessage() {} -func (*QueryAllContractStateRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{6} -} - -func (m *QueryAllContractStateRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryAllContractStateRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAllContractStateRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *QueryAllContractStateRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAllContractStateRequest.Merge(m, src) -} - -func (m *QueryAllContractStateRequest) XXX_Size() int { - return m.Size() -} - -func (m *QueryAllContractStateRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAllContractStateRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAllContractStateRequest proto.InternalMessageInfo - -// QueryAllContractStateResponse is the response type for the -// Query/AllContractState RPC method -type QueryAllContractStateResponse struct { - Models []Model `protobuf:"bytes,1,rep,name=models,proto3" json:"models"` - // pagination defines the pagination in the response. - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryAllContractStateResponse) Reset() { *m = QueryAllContractStateResponse{} } -func (m *QueryAllContractStateResponse) String() string { return proto.CompactTextString(m) } -func (*QueryAllContractStateResponse) ProtoMessage() {} -func (*QueryAllContractStateResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{7} -} - -func (m *QueryAllContractStateResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryAllContractStateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAllContractStateResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *QueryAllContractStateResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAllContractStateResponse.Merge(m, src) -} - -func (m *QueryAllContractStateResponse) XXX_Size() int { - return m.Size() -} - -func (m *QueryAllContractStateResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAllContractStateResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAllContractStateResponse proto.InternalMessageInfo - -// QueryRawContractStateRequest is the request type for the -// Query/RawContractState RPC method -type QueryRawContractStateRequest struct { - // address is the address of the contract - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - QueryData []byte `protobuf:"bytes,2,opt,name=query_data,json=queryData,proto3" json:"query_data,omitempty"` -} - -func (m *QueryRawContractStateRequest) Reset() { *m = QueryRawContractStateRequest{} } -func (m *QueryRawContractStateRequest) String() string { return proto.CompactTextString(m) } -func (*QueryRawContractStateRequest) ProtoMessage() {} -func (*QueryRawContractStateRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{8} -} - -func (m *QueryRawContractStateRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryRawContractStateRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryRawContractStateRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *QueryRawContractStateRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryRawContractStateRequest.Merge(m, src) -} - -func (m *QueryRawContractStateRequest) XXX_Size() int { - return m.Size() -} - -func (m *QueryRawContractStateRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryRawContractStateRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryRawContractStateRequest proto.InternalMessageInfo - -// QueryRawContractStateResponse is the response type for the -// Query/RawContractState RPC method -type QueryRawContractStateResponse struct { - // Data contains the raw store data - Data []byte `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"` -} - -func (m *QueryRawContractStateResponse) Reset() { *m = QueryRawContractStateResponse{} } -func (m *QueryRawContractStateResponse) String() string { return proto.CompactTextString(m) } -func (*QueryRawContractStateResponse) ProtoMessage() {} -func (*QueryRawContractStateResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{9} -} - -func (m *QueryRawContractStateResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryRawContractStateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryRawContractStateResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *QueryRawContractStateResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryRawContractStateResponse.Merge(m, src) -} - -func (m *QueryRawContractStateResponse) XXX_Size() int { - return m.Size() -} - -func (m *QueryRawContractStateResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryRawContractStateResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryRawContractStateResponse proto.InternalMessageInfo - -// QuerySmartContractStateRequest is the request type for the -// Query/SmartContractState RPC method -type QuerySmartContractStateRequest struct { - // address is the address of the contract - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - // QueryData contains the query data passed to the contract - QueryData RawContractMessage `protobuf:"bytes,2,opt,name=query_data,json=queryData,proto3,casttype=RawContractMessage" json:"query_data,omitempty"` -} - -func (m *QuerySmartContractStateRequest) Reset() { *m = QuerySmartContractStateRequest{} } -func (m *QuerySmartContractStateRequest) String() string { return proto.CompactTextString(m) } -func (*QuerySmartContractStateRequest) ProtoMessage() {} -func (*QuerySmartContractStateRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{10} -} - -func (m *QuerySmartContractStateRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QuerySmartContractStateRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QuerySmartContractStateRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *QuerySmartContractStateRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QuerySmartContractStateRequest.Merge(m, src) -} - -func (m *QuerySmartContractStateRequest) XXX_Size() int { - return m.Size() -} - -func (m *QuerySmartContractStateRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QuerySmartContractStateRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QuerySmartContractStateRequest proto.InternalMessageInfo - -// QuerySmartContractStateResponse is the response type for the -// Query/SmartContractState RPC method -type QuerySmartContractStateResponse struct { - // Data contains the json data returned from the smart contract - Data RawContractMessage `protobuf:"bytes,1,opt,name=data,proto3,casttype=RawContractMessage" json:"data,omitempty"` -} - -func (m *QuerySmartContractStateResponse) Reset() { *m = QuerySmartContractStateResponse{} } -func (m *QuerySmartContractStateResponse) String() string { return proto.CompactTextString(m) } -func (*QuerySmartContractStateResponse) ProtoMessage() {} -func (*QuerySmartContractStateResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{11} -} - -func (m *QuerySmartContractStateResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QuerySmartContractStateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QuerySmartContractStateResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *QuerySmartContractStateResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QuerySmartContractStateResponse.Merge(m, src) -} - -func (m *QuerySmartContractStateResponse) XXX_Size() int { - return m.Size() -} - -func (m *QuerySmartContractStateResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QuerySmartContractStateResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QuerySmartContractStateResponse proto.InternalMessageInfo - -// QueryCodeRequest is the request type for the Query/Code RPC method -type QueryCodeRequest struct { - CodeId uint64 `protobuf:"varint,1,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` -} - -func (m *QueryCodeRequest) Reset() { *m = QueryCodeRequest{} } -func (m *QueryCodeRequest) String() string { return proto.CompactTextString(m) } -func (*QueryCodeRequest) ProtoMessage() {} -func (*QueryCodeRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{12} -} - -func (m *QueryCodeRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryCodeRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryCodeRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *QueryCodeRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryCodeRequest.Merge(m, src) -} - -func (m *QueryCodeRequest) XXX_Size() int { - return m.Size() -} - -func (m *QueryCodeRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryCodeRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryCodeRequest proto.InternalMessageInfo - -// CodeInfoResponse contains code meta data from CodeInfo -type CodeInfoResponse struct { - CodeID uint64 `protobuf:"varint,1,opt,name=code_id,json=codeId,proto3" json:"id"` - Creator string `protobuf:"bytes,2,opt,name=creator,proto3" json:"creator,omitempty"` - DataHash github_com_cometbft_cometbft_libs_bytes.HexBytes `protobuf:"bytes,3,opt,name=data_hash,json=dataHash,proto3,casttype=github.com/cometbft/cometbft/libs/bytes.HexBytes" json:"data_hash,omitempty"` - InstantiatePermission AccessConfig `protobuf:"bytes,6,opt,name=instantiate_permission,json=instantiatePermission,proto3" json:"instantiate_permission"` -} - -func (m *CodeInfoResponse) Reset() { *m = CodeInfoResponse{} } -func (m *CodeInfoResponse) String() string { return proto.CompactTextString(m) } -func (*CodeInfoResponse) ProtoMessage() {} -func (*CodeInfoResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{13} -} - -func (m *CodeInfoResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *CodeInfoResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CodeInfoResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *CodeInfoResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_CodeInfoResponse.Merge(m, src) -} - -func (m *CodeInfoResponse) XXX_Size() int { - return m.Size() -} - -func (m *CodeInfoResponse) XXX_DiscardUnknown() { - xxx_messageInfo_CodeInfoResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_CodeInfoResponse proto.InternalMessageInfo - -// QueryCodeResponse is the response type for the Query/Code RPC method -type QueryCodeResponse struct { - *CodeInfoResponse `protobuf:"bytes,1,opt,name=code_info,json=codeInfo,proto3,embedded=code_info" json:""` - Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data"` -} - -func (m *QueryCodeResponse) Reset() { *m = QueryCodeResponse{} } -func (m *QueryCodeResponse) String() string { return proto.CompactTextString(m) } -func (*QueryCodeResponse) ProtoMessage() {} -func (*QueryCodeResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{14} -} - -func (m *QueryCodeResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryCodeResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryCodeResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *QueryCodeResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryCodeResponse.Merge(m, src) -} - -func (m *QueryCodeResponse) XXX_Size() int { - return m.Size() -} - -func (m *QueryCodeResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryCodeResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryCodeResponse proto.InternalMessageInfo - -// QueryCodesRequest is the request type for the Query/Codes RPC method -type QueryCodesRequest struct { - // pagination defines an optional pagination for the request. - Pagination *query.PageRequest `protobuf:"bytes,1,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryCodesRequest) Reset() { *m = QueryCodesRequest{} } -func (m *QueryCodesRequest) String() string { return proto.CompactTextString(m) } -func (*QueryCodesRequest) ProtoMessage() {} -func (*QueryCodesRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{15} -} - -func (m *QueryCodesRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryCodesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryCodesRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *QueryCodesRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryCodesRequest.Merge(m, src) -} - -func (m *QueryCodesRequest) XXX_Size() int { - return m.Size() -} - -func (m *QueryCodesRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryCodesRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryCodesRequest proto.InternalMessageInfo - -// QueryCodesResponse is the response type for the Query/Codes RPC method -type QueryCodesResponse struct { - CodeInfos []CodeInfoResponse `protobuf:"bytes,1,rep,name=code_infos,json=codeInfos,proto3" json:"code_infos"` - // pagination defines the pagination in the response. - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryCodesResponse) Reset() { *m = QueryCodesResponse{} } -func (m *QueryCodesResponse) String() string { return proto.CompactTextString(m) } -func (*QueryCodesResponse) ProtoMessage() {} -func (*QueryCodesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{16} -} - -func (m *QueryCodesResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryCodesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryCodesResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *QueryCodesResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryCodesResponse.Merge(m, src) -} - -func (m *QueryCodesResponse) XXX_Size() int { - return m.Size() -} - -func (m *QueryCodesResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryCodesResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryCodesResponse proto.InternalMessageInfo - -// QueryPinnedCodesRequest is the request type for the Query/PinnedCodes -// RPC method -type QueryPinnedCodesRequest struct { - // pagination defines an optional pagination for the request. - Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryPinnedCodesRequest) Reset() { *m = QueryPinnedCodesRequest{} } -func (m *QueryPinnedCodesRequest) String() string { return proto.CompactTextString(m) } -func (*QueryPinnedCodesRequest) ProtoMessage() {} -func (*QueryPinnedCodesRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{17} -} - -func (m *QueryPinnedCodesRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryPinnedCodesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryPinnedCodesRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *QueryPinnedCodesRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryPinnedCodesRequest.Merge(m, src) -} - -func (m *QueryPinnedCodesRequest) XXX_Size() int { - return m.Size() -} - -func (m *QueryPinnedCodesRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryPinnedCodesRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryPinnedCodesRequest proto.InternalMessageInfo - -// QueryPinnedCodesResponse is the response type for the -// Query/PinnedCodes RPC method -type QueryPinnedCodesResponse struct { - CodeIDs []uint64 `protobuf:"varint,1,rep,packed,name=code_ids,json=codeIds,proto3" json:"code_ids,omitempty"` - // pagination defines the pagination in the response. - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryPinnedCodesResponse) Reset() { *m = QueryPinnedCodesResponse{} } -func (m *QueryPinnedCodesResponse) String() string { return proto.CompactTextString(m) } -func (*QueryPinnedCodesResponse) ProtoMessage() {} -func (*QueryPinnedCodesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{18} -} - -func (m *QueryPinnedCodesResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryPinnedCodesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryPinnedCodesResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *QueryPinnedCodesResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryPinnedCodesResponse.Merge(m, src) -} - -func (m *QueryPinnedCodesResponse) XXX_Size() int { - return m.Size() -} - -func (m *QueryPinnedCodesResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryPinnedCodesResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryPinnedCodesResponse proto.InternalMessageInfo - -// QueryParamsRequest is the request type for the Query/Params RPC method. -type QueryParamsRequest struct{} - -func (m *QueryParamsRequest) Reset() { *m = QueryParamsRequest{} } -func (m *QueryParamsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryParamsRequest) ProtoMessage() {} -func (*QueryParamsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{19} -} - -func (m *QueryParamsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryParamsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryParamsRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *QueryParamsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsRequest.Merge(m, src) -} - -func (m *QueryParamsRequest) XXX_Size() int { - return m.Size() -} - -func (m *QueryParamsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryParamsRequest proto.InternalMessageInfo - -// QueryParamsResponse is the response type for the Query/Params RPC method. -type QueryParamsResponse struct { - // params defines the parameters of the module. - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` -} - -func (m *QueryParamsResponse) Reset() { *m = QueryParamsResponse{} } -func (m *QueryParamsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryParamsResponse) ProtoMessage() {} -func (*QueryParamsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{20} -} - -func (m *QueryParamsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryParamsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *QueryParamsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsResponse.Merge(m, src) -} - -func (m *QueryParamsResponse) XXX_Size() int { - return m.Size() -} - -func (m *QueryParamsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryParamsResponse proto.InternalMessageInfo - -// QueryContractsByCreatorRequest is the request type for the -// Query/ContractsByCreator RPC method. -type QueryContractsByCreatorRequest struct { - // CreatorAddress is the address of contract creator - CreatorAddress string `protobuf:"bytes,1,opt,name=creator_address,json=creatorAddress,proto3" json:"creator_address,omitempty"` - // Pagination defines an optional pagination for the request. - Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryContractsByCreatorRequest) Reset() { *m = QueryContractsByCreatorRequest{} } -func (m *QueryContractsByCreatorRequest) String() string { return proto.CompactTextString(m) } -func (*QueryContractsByCreatorRequest) ProtoMessage() {} -func (*QueryContractsByCreatorRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{21} -} - -func (m *QueryContractsByCreatorRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryContractsByCreatorRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryContractsByCreatorRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *QueryContractsByCreatorRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryContractsByCreatorRequest.Merge(m, src) -} - -func (m *QueryContractsByCreatorRequest) XXX_Size() int { - return m.Size() -} - -func (m *QueryContractsByCreatorRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryContractsByCreatorRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryContractsByCreatorRequest proto.InternalMessageInfo - -// QueryContractsByCreatorResponse is the response type for the -// Query/ContractsByCreator RPC method. -type QueryContractsByCreatorResponse struct { - // ContractAddresses result set - ContractAddresses []string `protobuf:"bytes,1,rep,name=contract_addresses,json=contractAddresses,proto3" json:"contract_addresses,omitempty"` - // Pagination defines the pagination in the response. - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryContractsByCreatorResponse) Reset() { *m = QueryContractsByCreatorResponse{} } -func (m *QueryContractsByCreatorResponse) String() string { return proto.CompactTextString(m) } -func (*QueryContractsByCreatorResponse) ProtoMessage() {} -func (*QueryContractsByCreatorResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{22} -} - -func (m *QueryContractsByCreatorResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryContractsByCreatorResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryContractsByCreatorResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *QueryContractsByCreatorResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryContractsByCreatorResponse.Merge(m, src) -} - -func (m *QueryContractsByCreatorResponse) XXX_Size() int { - return m.Size() -} - -func (m *QueryContractsByCreatorResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryContractsByCreatorResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryContractsByCreatorResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*QueryContractInfoRequest)(nil), "cosmwasm.wasm.v1.QueryContractInfoRequest") - proto.RegisterType((*QueryContractInfoResponse)(nil), "cosmwasm.wasm.v1.QueryContractInfoResponse") - proto.RegisterType((*QueryContractHistoryRequest)(nil), "cosmwasm.wasm.v1.QueryContractHistoryRequest") - proto.RegisterType((*QueryContractHistoryResponse)(nil), "cosmwasm.wasm.v1.QueryContractHistoryResponse") - proto.RegisterType((*QueryContractsByCodeRequest)(nil), "cosmwasm.wasm.v1.QueryContractsByCodeRequest") - proto.RegisterType((*QueryContractsByCodeResponse)(nil), "cosmwasm.wasm.v1.QueryContractsByCodeResponse") - proto.RegisterType((*QueryAllContractStateRequest)(nil), "cosmwasm.wasm.v1.QueryAllContractStateRequest") - proto.RegisterType((*QueryAllContractStateResponse)(nil), "cosmwasm.wasm.v1.QueryAllContractStateResponse") - proto.RegisterType((*QueryRawContractStateRequest)(nil), "cosmwasm.wasm.v1.QueryRawContractStateRequest") - proto.RegisterType((*QueryRawContractStateResponse)(nil), "cosmwasm.wasm.v1.QueryRawContractStateResponse") - proto.RegisterType((*QuerySmartContractStateRequest)(nil), "cosmwasm.wasm.v1.QuerySmartContractStateRequest") - proto.RegisterType((*QuerySmartContractStateResponse)(nil), "cosmwasm.wasm.v1.QuerySmartContractStateResponse") - proto.RegisterType((*QueryCodeRequest)(nil), "cosmwasm.wasm.v1.QueryCodeRequest") - proto.RegisterType((*CodeInfoResponse)(nil), "cosmwasm.wasm.v1.CodeInfoResponse") - proto.RegisterType((*QueryCodeResponse)(nil), "cosmwasm.wasm.v1.QueryCodeResponse") - proto.RegisterType((*QueryCodesRequest)(nil), "cosmwasm.wasm.v1.QueryCodesRequest") - proto.RegisterType((*QueryCodesResponse)(nil), "cosmwasm.wasm.v1.QueryCodesResponse") - proto.RegisterType((*QueryPinnedCodesRequest)(nil), "cosmwasm.wasm.v1.QueryPinnedCodesRequest") - proto.RegisterType((*QueryPinnedCodesResponse)(nil), "cosmwasm.wasm.v1.QueryPinnedCodesResponse") - proto.RegisterType((*QueryParamsRequest)(nil), "cosmwasm.wasm.v1.QueryParamsRequest") - proto.RegisterType((*QueryParamsResponse)(nil), "cosmwasm.wasm.v1.QueryParamsResponse") - proto.RegisterType((*QueryContractsByCreatorRequest)(nil), "cosmwasm.wasm.v1.QueryContractsByCreatorRequest") - proto.RegisterType((*QueryContractsByCreatorResponse)(nil), "cosmwasm.wasm.v1.QueryContractsByCreatorResponse") -} - -func init() { proto.RegisterFile("cosmwasm/wasm/v1/query.proto", fileDescriptor_9677c207036b9f2b) } - -var fileDescriptor_9677c207036b9f2b = []byte{ - // 1355 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x98, 0xcf, 0x6f, 0x1b, 0x45, - 0x1b, 0xc7, 0x3d, 0xa9, 0xe3, 0x1f, 0x93, 0xf6, 0xad, 0x33, 0x6f, 0x69, 0x8d, 0x49, 0xd7, 0xd1, - 0x52, 0xd2, 0xd4, 0x6d, 0x76, 0x9b, 0xb4, 0x55, 0x45, 0x11, 0x42, 0x71, 0x0b, 0xb4, 0x15, 0x55, - 0xd3, 0xad, 0x04, 0x12, 0x1c, 0xcc, 0x78, 0x3d, 0x71, 0x56, 0xc4, 0x3b, 0xce, 0xce, 0x24, 0xa9, - 0x15, 0x05, 0x50, 0x25, 0x4e, 0x70, 0x00, 0x55, 0x1c, 0xb8, 0x20, 0x0e, 0x15, 0x54, 0xe2, 0x82, - 0x38, 0x55, 0x5c, 0xb9, 0xe4, 0x18, 0x89, 0x0b, 0x27, 0x0b, 0x1c, 0x24, 0x50, 0xfe, 0x84, 0x9e, - 0xd0, 0xce, 0xce, 0xda, 0xbb, 0xb6, 0x37, 0x76, 0x2a, 0x8b, 0x8b, 0xb5, 0xbb, 0x33, 0xcf, 0xcc, - 0xe7, 0xf9, 0xce, 0x33, 0xcf, 0xf3, 0xc8, 0x70, 0xca, 0xa4, 0xac, 0xb6, 0x89, 0x59, 0x4d, 0x17, - 0x3f, 0x1b, 0xf3, 0xfa, 0xda, 0x3a, 0x71, 0x1a, 0x5a, 0xdd, 0xa1, 0x9c, 0xa2, 0x8c, 0x3f, 0xaa, - 0x89, 0x9f, 0x8d, 0xf9, 0xdc, 0x89, 0x2a, 0xad, 0x52, 0x31, 0xa8, 0xbb, 0x4f, 0xde, 0xbc, 0x5c, - 0xef, 0x2a, 0xbc, 0x51, 0x27, 0xcc, 0x1f, 0xad, 0x52, 0x5a, 0x5d, 0x25, 0x3a, 0xae, 0x5b, 0x3a, - 0xb6, 0x6d, 0xca, 0x31, 0xb7, 0xa8, 0xed, 0x8f, 0x16, 0x5c, 0x5b, 0xca, 0xf4, 0x32, 0x66, 0xc4, - 0xdb, 0x5c, 0xdf, 0x98, 0x2f, 0x13, 0x8e, 0xe7, 0xf5, 0x3a, 0xae, 0x5a, 0xb6, 0x98, 0x2c, 0xe7, - 0x4e, 0xe2, 0x9a, 0x65, 0x53, 0x5d, 0xfc, 0x7a, 0x9f, 0xd4, 0xcb, 0x30, 0x7b, 0xcf, 0x35, 0xba, - 0x4e, 0x6d, 0xee, 0x60, 0x93, 0xdf, 0xb2, 0x97, 0xa9, 0x41, 0xd6, 0xd6, 0x09, 0xe3, 0x28, 0x0b, - 0x93, 0xb8, 0x52, 0x71, 0x08, 0x63, 0x59, 0x30, 0x0d, 0x66, 0xd3, 0x86, 0xff, 0xaa, 0x3e, 0x02, - 0xf0, 0xc5, 0x3e, 0x66, 0xac, 0x4e, 0x6d, 0x46, 0xa2, 0xed, 0xd0, 0xbb, 0xf0, 0x98, 0x29, 0x2d, - 0x4a, 0x96, 0xbd, 0x4c, 0xb3, 0x63, 0xd3, 0x60, 0x76, 0x62, 0x41, 0xd1, 0xba, 0x85, 0xd2, 0x82, - 0x0b, 0x17, 0x27, 0x77, 0x9a, 0xf9, 0xd8, 0x6e, 0x33, 0x0f, 0xf6, 0x9b, 0xf9, 0xd8, 0x93, 0xbf, - 0x7f, 0x2a, 0x00, 0xe3, 0xa8, 0x19, 0x98, 0x70, 0x2d, 0xfe, 0xcf, 0x77, 0x79, 0xa0, 0x7e, 0x02, - 0x5f, 0x0a, 0x41, 0xdd, 0xb4, 0x18, 0xa7, 0x4e, 0x63, 0xa0, 0x3b, 0xe8, 0x2d, 0x08, 0x3b, 0x5a, - 0x49, 0xa6, 0x19, 0xcd, 0x13, 0x56, 0x73, 0x85, 0xd5, 0xbc, 0x53, 0x95, 0xc2, 0x6a, 0x4b, 0xb8, - 0x4a, 0xe4, 0xaa, 0x46, 0xc0, 0x52, 0x7d, 0x0a, 0xe0, 0x54, 0x7f, 0x02, 0xa9, 0xcc, 0x5d, 0x98, - 0x24, 0x36, 0x77, 0x2c, 0xe2, 0x22, 0x1c, 0x99, 0x9d, 0x58, 0x28, 0x44, 0x7b, 0x7e, 0x9d, 0x56, - 0x88, 0xb4, 0x7f, 0xd3, 0xe6, 0x4e, 0xa3, 0x98, 0xde, 0x69, 0x7b, 0xef, 0xaf, 0x82, 0xde, 0xee, - 0x43, 0x7e, 0x76, 0x20, 0xb9, 0x47, 0x13, 0x42, 0xff, 0xb8, 0x4b, 0x3b, 0x56, 0x6c, 0xb8, 0x00, - 0xbe, 0x76, 0xa7, 0x60, 0xd2, 0xa4, 0x15, 0x52, 0xb2, 0x2a, 0x42, 0xbb, 0xb8, 0x91, 0x70, 0x5f, - 0x6f, 0x55, 0x46, 0x26, 0xdd, 0x67, 0xdd, 0xd2, 0xb5, 0x01, 0xa4, 0x74, 0x53, 0x30, 0xed, 0x1f, - 0xb9, 0x27, 0x5e, 0xda, 0xe8, 0x7c, 0x18, 0x9d, 0x0e, 0x9f, 0xfa, 0x1c, 0x8b, 0xab, 0xab, 0x3e, - 0xca, 0x7d, 0x8e, 0x39, 0xf9, 0xef, 0xa2, 0xe8, 0x31, 0x80, 0xa7, 0x23, 0x10, 0xa4, 0x16, 0xd7, - 0x60, 0xa2, 0x46, 0x2b, 0x64, 0xd5, 0x8f, 0xa2, 0x53, 0xbd, 0x51, 0x74, 0xc7, 0x1d, 0x0f, 0x86, - 0x8c, 0xb4, 0x18, 0x9d, 0x52, 0xef, 0x49, 0xa1, 0x0c, 0xbc, 0x79, 0x48, 0xa1, 0x4e, 0x43, 0x28, - 0xf6, 0x28, 0x55, 0x30, 0xc7, 0x02, 0xe1, 0xa8, 0x91, 0x16, 0x5f, 0x6e, 0x60, 0x8e, 0xd5, 0x4b, - 0xd2, 0xfd, 0xde, 0x85, 0xa5, 0xfb, 0x08, 0xc6, 0x85, 0x25, 0x10, 0x96, 0xe2, 0x59, 0x5d, 0x83, - 0x8a, 0x30, 0xba, 0x5f, 0xc3, 0x0e, 0x3f, 0x24, 0xcf, 0x95, 0x5e, 0x9e, 0xe2, 0xc9, 0x67, 0xcd, - 0x3c, 0x0a, 0x10, 0xdc, 0x21, 0x8c, 0xb9, 0x4a, 0x04, 0x38, 0xef, 0xc0, 0x7c, 0xe4, 0x96, 0x92, - 0xb4, 0x10, 0x24, 0x8d, 0x5c, 0xd3, 0xf3, 0xe0, 0x3c, 0xcc, 0xc8, 0x0b, 0x30, 0xf8, 0xda, 0xa9, - 0xdf, 0x8e, 0xc1, 0x8c, 0x3b, 0x31, 0x94, 0x77, 0xcf, 0x75, 0xcd, 0x2e, 0x66, 0x5a, 0xcd, 0x7c, - 0x42, 0x4c, 0xbb, 0xb1, 0xdf, 0xcc, 0x8f, 0x59, 0x95, 0xf6, 0xb5, 0xcd, 0xc2, 0xa4, 0xe9, 0x10, - 0xcc, 0xa9, 0x23, 0xfc, 0x4d, 0x1b, 0xfe, 0x2b, 0xba, 0x07, 0xd3, 0x2e, 0x4e, 0x69, 0x05, 0xb3, - 0x95, 0xec, 0x11, 0xc1, 0x7d, 0xf9, 0x59, 0x33, 0x7f, 0xb1, 0x6a, 0xf1, 0x95, 0xf5, 0xb2, 0x66, - 0xd2, 0x9a, 0x6e, 0xd2, 0x1a, 0xe1, 0xe5, 0x65, 0xde, 0x79, 0x58, 0xb5, 0xca, 0x4c, 0x2f, 0x37, - 0x38, 0x61, 0xda, 0x4d, 0xf2, 0xa0, 0xe8, 0x3e, 0x18, 0x29, 0x77, 0x99, 0x9b, 0x98, 0xad, 0xa0, - 0x0f, 0xe1, 0x49, 0xcb, 0x66, 0x1c, 0xdb, 0xdc, 0xc2, 0x9c, 0x94, 0xea, 0xc4, 0xa9, 0x59, 0x8c, - 0xb9, 0xe1, 0x97, 0x88, 0x4a, 0xff, 0x8b, 0xa6, 0x49, 0x18, 0xbb, 0x4e, 0xed, 0x65, 0xab, 0x1a, - 0x8c, 0xe2, 0x17, 0x02, 0x0b, 0x2d, 0xb5, 0xd7, 0xf1, 0xf2, 0xff, 0xed, 0x78, 0x2a, 0x9e, 0x19, - 0xbf, 0x1d, 0x4f, 0x8d, 0x67, 0x12, 0xea, 0x43, 0x00, 0x27, 0x03, 0x72, 0x4a, 0x85, 0x6e, 0xb9, - 0x49, 0xc4, 0x55, 0xc8, 0xad, 0x3d, 0x40, 0x6c, 0xae, 0xf6, 0xcb, 0xc0, 0x61, 0x61, 0x8b, 0x29, - 0xbf, 0xf6, 0x18, 0x29, 0x53, 0x8e, 0xa1, 0x29, 0x79, 0xb4, 0x5e, 0xb8, 0xa4, 0xf6, 0x9b, 0x79, - 0xf1, 0xee, 0x1d, 0xa6, 0x2c, 0x48, 0x1f, 0x04, 0x18, 0x98, 0x7f, 0xa6, 0xe1, 0x34, 0x01, 0x9e, - 0x3b, 0x4d, 0xfc, 0x08, 0x20, 0x0a, 0xae, 0x2e, 0x5d, 0x7c, 0x07, 0xc2, 0xb6, 0x8b, 0x7e, 0x7e, - 0x18, 0xc6, 0xc7, 0x80, 0xc8, 0x69, 0xdf, 0xc9, 0x11, 0x66, 0x0b, 0x0c, 0x4f, 0x09, 0xd8, 0x25, - 0xcb, 0xb6, 0x49, 0xe5, 0x00, 0x41, 0x9e, 0x3f, 0x6f, 0x7e, 0x0e, 0x64, 0x2f, 0x13, 0xda, 0x43, - 0xca, 0x32, 0x03, 0x53, 0xf2, 0x6e, 0x78, 0xa2, 0xc4, 0x8b, 0x13, 0xad, 0x66, 0x3e, 0xe9, 0x5d, - 0x0e, 0x66, 0x24, 0xbd, 0x7b, 0x31, 0x42, 0x87, 0x4f, 0xc8, 0xd3, 0x59, 0xc2, 0x0e, 0xae, 0xf9, - 0xbe, 0xaa, 0x06, 0xfc, 0x7f, 0xe8, 0xab, 0xa4, 0x7b, 0x0d, 0x26, 0xea, 0xe2, 0x8b, 0x8c, 0x87, - 0x6c, 0xef, 0x81, 0x79, 0x16, 0xa1, 0x8c, 0xee, 0x99, 0xa8, 0x5f, 0x01, 0x99, 0xfb, 0x82, 0xa5, - 0xd3, 0xbb, 0xcd, 0xbe, 0xc4, 0x67, 0xe1, 0x71, 0x79, 0xbf, 0x4b, 0xe1, 0x1c, 0xf8, 0x3f, 0xf9, - 0x79, 0x71, 0xc4, 0x35, 0xec, 0x1b, 0x20, 0x93, 0x63, 0x3f, 0x26, 0xe9, 0xf4, 0x1c, 0x44, 0xed, - 0x66, 0x50, 0x52, 0x11, 0xbf, 0xb4, 0x4f, 0xfa, 0x23, 0x8b, 0xfe, 0xc0, 0xc8, 0x4e, 0x66, 0xe1, - 0xd7, 0x63, 0x70, 0x5c, 0xb0, 0xa1, 0xaf, 0x01, 0x3c, 0x1a, 0x6c, 0x34, 0x51, 0x9f, 0x76, 0x2c, - 0xaa, 0x3b, 0xce, 0x9d, 0x1f, 0x6a, 0xae, 0xb7, 0xbf, 0x7a, 0xe1, 0xe1, 0x6f, 0x7f, 0x3d, 0x1a, - 0x9b, 0x41, 0x67, 0xf4, 0x9e, 0x56, 0xdf, 0xf7, 0x54, 0xdf, 0x92, 0x22, 0x6c, 0xa3, 0xef, 0x01, - 0x3c, 0xde, 0xd5, 0x42, 0xa2, 0xb9, 0x01, 0xdb, 0x85, 0x9b, 0xdd, 0x9c, 0x36, 0xec, 0x74, 0x09, - 0x78, 0x59, 0x00, 0x6a, 0xe8, 0xc2, 0x30, 0x80, 0xfa, 0x8a, 0x84, 0x7a, 0x1c, 0x00, 0x95, 0x0d, - 0xdb, 0x40, 0xd0, 0x70, 0x67, 0x39, 0x10, 0xb4, 0xab, 0x0f, 0x54, 0x17, 0x04, 0xe8, 0x05, 0x54, - 0xe8, 0x07, 0x5a, 0x21, 0xfa, 0x96, 0xbc, 0xe6, 0xdb, 0x7a, 0xa7, 0x3b, 0xfc, 0x01, 0xc0, 0x4c, - 0x77, 0x33, 0x85, 0xa2, 0x36, 0x8e, 0x68, 0xfc, 0x72, 0xfa, 0xd0, 0xf3, 0x87, 0x21, 0xed, 0x91, - 0x94, 0x09, 0xa8, 0x9f, 0x01, 0xcc, 0x74, 0xf7, 0x3d, 0x91, 0xa4, 0x11, 0x9d, 0x57, 0x24, 0x69, - 0x54, 0x43, 0xa5, 0xbe, 0x2e, 0x48, 0xaf, 0xa2, 0x2b, 0x43, 0x91, 0x3a, 0x78, 0x53, 0xdf, 0xea, - 0x34, 0x4c, 0xdb, 0xe8, 0x17, 0x00, 0x51, 0x6f, 0x13, 0x84, 0x2e, 0x46, 0x60, 0x44, 0xb6, 0x68, - 0xb9, 0xf9, 0x43, 0x58, 0x48, 0xf4, 0x37, 0x04, 0xfa, 0xab, 0xe8, 0xea, 0x70, 0x22, 0xbb, 0x0b, - 0x85, 0xe1, 0x1b, 0x30, 0x2e, 0xc2, 0x56, 0x8d, 0x8c, 0xc3, 0x4e, 0xac, 0xbe, 0x7c, 0xe0, 0x1c, - 0x49, 0x34, 0x2b, 0x88, 0x54, 0x34, 0x3d, 0x28, 0x40, 0x91, 0x03, 0xc7, 0x45, 0x91, 0x42, 0x07, - 0xad, 0xeb, 0x97, 0x8e, 0xdc, 0x99, 0x83, 0x27, 0xc9, 0xdd, 0x15, 0xb1, 0x7b, 0x16, 0x9d, 0xec, - 0xbf, 0x3b, 0xfa, 0x02, 0xc0, 0x89, 0x40, 0x7d, 0x44, 0xe7, 0x22, 0x56, 0xed, 0xad, 0xd3, 0xb9, - 0xc2, 0x30, 0x53, 0x25, 0xc6, 0x8c, 0xc0, 0x98, 0x46, 0x4a, 0x7f, 0x0c, 0xa6, 0xd7, 0x85, 0x11, - 0xda, 0x86, 0x09, 0xaf, 0xb0, 0xa1, 0x28, 0xf7, 0x42, 0xf5, 0x33, 0xf7, 0xca, 0x80, 0x59, 0x43, - 0x6f, 0xef, 0x6d, 0xfa, 0x14, 0x40, 0xd4, 0x5b, 0xa1, 0x22, 0x23, 0x37, 0xb2, 0xc0, 0x46, 0x46, - 0x6e, 0x74, 0xf9, 0x1b, 0xe6, 0xd2, 0x31, 0x5d, 0x96, 0x67, 0x7d, 0xab, 0xab, 0x7c, 0x6f, 0x17, - 0xef, 0xee, 0xfc, 0xa9, 0xc4, 0x9e, 0xb4, 0x94, 0xd8, 0x4e, 0x4b, 0x01, 0xbb, 0x2d, 0x05, 0xfc, - 0xd1, 0x52, 0xc0, 0x97, 0x7b, 0x4a, 0x6c, 0x77, 0x4f, 0x89, 0xfd, 0xbe, 0xa7, 0xc4, 0xde, 0x9f, - 0x0b, 0xb4, 0xec, 0x9c, 0x38, 0x75, 0x9b, 0xf0, 0x4d, 0xea, 0x7c, 0x24, 0x9e, 0xe7, 0x4c, 0xea, - 0x10, 0xfd, 0x81, 0xb7, 0xa3, 0xf8, 0xb3, 0xa9, 0x9c, 0x10, 0x7f, 0x08, 0x5d, 0xfa, 0x37, 0x00, - 0x00, 0xff, 0xff, 0x16, 0xa8, 0x59, 0xd9, 0xd3, 0x12, 0x00, 0x00, -} - -func (this *QueryContractInfoResponse) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*QueryContractInfoResponse) - if !ok { - that2, ok := that.(QueryContractInfoResponse) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Address != that1.Address { - return false - } - if !this.ContractInfo.Equal(&that1.ContractInfo) { - return false - } - return true -} - -func (this *CodeInfoResponse) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*CodeInfoResponse) - if !ok { - that2, ok := that.(CodeInfoResponse) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.CodeID != that1.CodeID { - return false - } - if this.Creator != that1.Creator { - return false - } - if !bytes.Equal(this.DataHash, that1.DataHash) { - return false - } - if !this.InstantiatePermission.Equal(&that1.InstantiatePermission) { - return false - } - return true -} - -func (this *QueryCodeResponse) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*QueryCodeResponse) - if !ok { - that2, ok := that.(QueryCodeResponse) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if !this.CodeInfoResponse.Equal(that1.CodeInfoResponse) { - return false - } - if !bytes.Equal(this.Data, that1.Data) { - return false - } - return true -} - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ context.Context - _ grpc.ClientConn -) - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// QueryClient is the client API for Query service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type QueryClient interface { - // ContractInfo gets the contract meta data - ContractInfo(ctx context.Context, in *QueryContractInfoRequest, opts ...grpc.CallOption) (*QueryContractInfoResponse, error) - // ContractHistory gets the contract code history - ContractHistory(ctx context.Context, in *QueryContractHistoryRequest, opts ...grpc.CallOption) (*QueryContractHistoryResponse, error) - // ContractsByCode lists all smart contracts for a code id - ContractsByCode(ctx context.Context, in *QueryContractsByCodeRequest, opts ...grpc.CallOption) (*QueryContractsByCodeResponse, error) - // AllContractState gets all raw store data for a single contract - AllContractState(ctx context.Context, in *QueryAllContractStateRequest, opts ...grpc.CallOption) (*QueryAllContractStateResponse, error) - // RawContractState gets single key from the raw store data of a contract - RawContractState(ctx context.Context, in *QueryRawContractStateRequest, opts ...grpc.CallOption) (*QueryRawContractStateResponse, error) - // SmartContractState get smart query result from the contract - SmartContractState(ctx context.Context, in *QuerySmartContractStateRequest, opts ...grpc.CallOption) (*QuerySmartContractStateResponse, error) - // Code gets the binary code and metadata for a singe wasm code - Code(ctx context.Context, in *QueryCodeRequest, opts ...grpc.CallOption) (*QueryCodeResponse, error) - // Codes gets the metadata for all stored wasm codes - Codes(ctx context.Context, in *QueryCodesRequest, opts ...grpc.CallOption) (*QueryCodesResponse, error) - // PinnedCodes gets the pinned code ids - PinnedCodes(ctx context.Context, in *QueryPinnedCodesRequest, opts ...grpc.CallOption) (*QueryPinnedCodesResponse, error) - // Params gets the module params - Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) - // ContractsByCreator gets the contracts by creator - ContractsByCreator(ctx context.Context, in *QueryContractsByCreatorRequest, opts ...grpc.CallOption) (*QueryContractsByCreatorResponse, error) -} - -type queryClient struct { - cc grpc1.ClientConn -} - -func NewQueryClient(cc grpc1.ClientConn) QueryClient { - return &queryClient{cc} -} - -func (c *queryClient) ContractInfo(ctx context.Context, in *QueryContractInfoRequest, opts ...grpc.CallOption) (*QueryContractInfoResponse, error) { - out := new(QueryContractInfoResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/ContractInfo", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) ContractHistory(ctx context.Context, in *QueryContractHistoryRequest, opts ...grpc.CallOption) (*QueryContractHistoryResponse, error) { - out := new(QueryContractHistoryResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/ContractHistory", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) ContractsByCode(ctx context.Context, in *QueryContractsByCodeRequest, opts ...grpc.CallOption) (*QueryContractsByCodeResponse, error) { - out := new(QueryContractsByCodeResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/ContractsByCode", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) AllContractState(ctx context.Context, in *QueryAllContractStateRequest, opts ...grpc.CallOption) (*QueryAllContractStateResponse, error) { - out := new(QueryAllContractStateResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/AllContractState", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) RawContractState(ctx context.Context, in *QueryRawContractStateRequest, opts ...grpc.CallOption) (*QueryRawContractStateResponse, error) { - out := new(QueryRawContractStateResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/RawContractState", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) SmartContractState(ctx context.Context, in *QuerySmartContractStateRequest, opts ...grpc.CallOption) (*QuerySmartContractStateResponse, error) { - out := new(QuerySmartContractStateResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/SmartContractState", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Code(ctx context.Context, in *QueryCodeRequest, opts ...grpc.CallOption) (*QueryCodeResponse, error) { - out := new(QueryCodeResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/Code", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Codes(ctx context.Context, in *QueryCodesRequest, opts ...grpc.CallOption) (*QueryCodesResponse, error) { - out := new(QueryCodesResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/Codes", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) PinnedCodes(ctx context.Context, in *QueryPinnedCodesRequest, opts ...grpc.CallOption) (*QueryPinnedCodesResponse, error) { - out := new(QueryPinnedCodesResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/PinnedCodes", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) { - out := new(QueryParamsResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/Params", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) ContractsByCreator(ctx context.Context, in *QueryContractsByCreatorRequest, opts ...grpc.CallOption) (*QueryContractsByCreatorResponse, error) { - out := new(QueryContractsByCreatorResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/ContractsByCreator", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - // ContractInfo gets the contract meta data - ContractInfo(context.Context, *QueryContractInfoRequest) (*QueryContractInfoResponse, error) - // ContractHistory gets the contract code history - ContractHistory(context.Context, *QueryContractHistoryRequest) (*QueryContractHistoryResponse, error) - // ContractsByCode lists all smart contracts for a code id - ContractsByCode(context.Context, *QueryContractsByCodeRequest) (*QueryContractsByCodeResponse, error) - // AllContractState gets all raw store data for a single contract - AllContractState(context.Context, *QueryAllContractStateRequest) (*QueryAllContractStateResponse, error) - // RawContractState gets single key from the raw store data of a contract - RawContractState(context.Context, *QueryRawContractStateRequest) (*QueryRawContractStateResponse, error) - // SmartContractState get smart query result from the contract - SmartContractState(context.Context, *QuerySmartContractStateRequest) (*QuerySmartContractStateResponse, error) - // Code gets the binary code and metadata for a singe wasm code - Code(context.Context, *QueryCodeRequest) (*QueryCodeResponse, error) - // Codes gets the metadata for all stored wasm codes - Codes(context.Context, *QueryCodesRequest) (*QueryCodesResponse, error) - // PinnedCodes gets the pinned code ids - PinnedCodes(context.Context, *QueryPinnedCodesRequest) (*QueryPinnedCodesResponse, error) - // Params gets the module params - Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) - // ContractsByCreator gets the contracts by creator - ContractsByCreator(context.Context, *QueryContractsByCreatorRequest) (*QueryContractsByCreatorResponse, error) -} - -// UnimplementedQueryServer can be embedded to have forward compatible implementations. -type UnimplementedQueryServer struct{} - -func (*UnimplementedQueryServer) ContractInfo(ctx context.Context, req *QueryContractInfoRequest) (*QueryContractInfoResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ContractInfo not implemented") -} - -func (*UnimplementedQueryServer) ContractHistory(ctx context.Context, req *QueryContractHistoryRequest) (*QueryContractHistoryResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ContractHistory not implemented") -} - -func (*UnimplementedQueryServer) ContractsByCode(ctx context.Context, req *QueryContractsByCodeRequest) (*QueryContractsByCodeResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ContractsByCode not implemented") -} - -func (*UnimplementedQueryServer) AllContractState(ctx context.Context, req *QueryAllContractStateRequest) (*QueryAllContractStateResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method AllContractState not implemented") -} - -func (*UnimplementedQueryServer) RawContractState(ctx context.Context, req *QueryRawContractStateRequest) (*QueryRawContractStateResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method RawContractState not implemented") -} - -func (*UnimplementedQueryServer) SmartContractState(ctx context.Context, req *QuerySmartContractStateRequest) (*QuerySmartContractStateResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method SmartContractState not implemented") -} - -func (*UnimplementedQueryServer) Code(ctx context.Context, req *QueryCodeRequest) (*QueryCodeResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Code not implemented") -} - -func (*UnimplementedQueryServer) Codes(ctx context.Context, req *QueryCodesRequest) (*QueryCodesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Codes not implemented") -} - -func (*UnimplementedQueryServer) PinnedCodes(ctx context.Context, req *QueryPinnedCodesRequest) (*QueryPinnedCodesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method PinnedCodes not implemented") -} - -func (*UnimplementedQueryServer) Params(ctx context.Context, req *QueryParamsRequest) (*QueryParamsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Params not implemented") -} - -func (*UnimplementedQueryServer) ContractsByCreator(ctx context.Context, req *QueryContractsByCreatorRequest) (*QueryContractsByCreatorResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ContractsByCreator not implemented") -} - -func RegisterQueryServer(s grpc1.Server, srv QueryServer) { - s.RegisterService(&_Query_serviceDesc, srv) -} - -func _Query_ContractInfo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryContractInfoRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).ContractInfo(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Query/ContractInfo", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).ContractInfo(ctx, req.(*QueryContractInfoRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_ContractHistory_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryContractHistoryRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).ContractHistory(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Query/ContractHistory", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).ContractHistory(ctx, req.(*QueryContractHistoryRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_ContractsByCode_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryContractsByCodeRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).ContractsByCode(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Query/ContractsByCode", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).ContractsByCode(ctx, req.(*QueryContractsByCodeRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_AllContractState_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryAllContractStateRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).AllContractState(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Query/AllContractState", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).AllContractState(ctx, req.(*QueryAllContractStateRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_RawContractState_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryRawContractStateRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).RawContractState(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Query/RawContractState", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).RawContractState(ctx, req.(*QueryRawContractStateRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_SmartContractState_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QuerySmartContractStateRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).SmartContractState(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Query/SmartContractState", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).SmartContractState(ctx, req.(*QuerySmartContractStateRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Code_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryCodeRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Code(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Query/Code", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Code(ctx, req.(*QueryCodeRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Codes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryCodesRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Codes(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Query/Codes", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Codes(ctx, req.(*QueryCodesRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_PinnedCodes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryPinnedCodesRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).PinnedCodes(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Query/PinnedCodes", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).PinnedCodes(ctx, req.(*QueryPinnedCodesRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Params_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryParamsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Params(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Query/Params", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Params(ctx, req.(*QueryParamsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_ContractsByCreator_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryContractsByCreatorRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).ContractsByCreator(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Query/ContractsByCreator", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).ContractsByCreator(ctx, req.(*QueryContractsByCreatorRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "cosmwasm.wasm.v1.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "ContractInfo", - Handler: _Query_ContractInfo_Handler, - }, - { - MethodName: "ContractHistory", - Handler: _Query_ContractHistory_Handler, - }, - { - MethodName: "ContractsByCode", - Handler: _Query_ContractsByCode_Handler, - }, - { - MethodName: "AllContractState", - Handler: _Query_AllContractState_Handler, - }, - { - MethodName: "RawContractState", - Handler: _Query_RawContractState_Handler, - }, - { - MethodName: "SmartContractState", - Handler: _Query_SmartContractState_Handler, - }, - { - MethodName: "Code", - Handler: _Query_Code_Handler, - }, - { - MethodName: "Codes", - Handler: _Query_Codes_Handler, - }, - { - MethodName: "PinnedCodes", - Handler: _Query_PinnedCodes_Handler, - }, - { - MethodName: "Params", - Handler: _Query_Params_Handler, - }, - { - MethodName: "ContractsByCreator", - Handler: _Query_ContractsByCreator_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "cosmwasm/wasm/v1/query.proto", -} - -func (m *QueryContractInfoRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryContractInfoRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryContractInfoRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryContractInfoResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryContractInfoResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryContractInfoResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.ContractInfo.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryContractHistoryRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryContractHistoryRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryContractHistoryRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryContractHistoryResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryContractHistoryResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryContractHistoryResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.Entries) > 0 { - for iNdEx := len(m.Entries) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Entries[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryContractsByCodeRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryContractsByCodeRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryContractsByCodeRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if m.CodeId != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.CodeId)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *QueryContractsByCodeResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryContractsByCodeResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryContractsByCodeResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.Contracts) > 0 { - for iNdEx := len(m.Contracts) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.Contracts[iNdEx]) - copy(dAtA[i:], m.Contracts[iNdEx]) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Contracts[iNdEx]))) - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryAllContractStateRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryAllContractStateRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAllContractStateRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryAllContractStateResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryAllContractStateResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAllContractStateResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.Models) > 0 { - for iNdEx := len(m.Models) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Models[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryRawContractStateRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryRawContractStateRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryRawContractStateRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.QueryData) > 0 { - i -= len(m.QueryData) - copy(dAtA[i:], m.QueryData) - i = encodeVarintQuery(dAtA, i, uint64(len(m.QueryData))) - i-- - dAtA[i] = 0x12 - } - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryRawContractStateResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryRawContractStateResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryRawContractStateResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Data) > 0 { - i -= len(m.Data) - copy(dAtA[i:], m.Data) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Data))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QuerySmartContractStateRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QuerySmartContractStateRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QuerySmartContractStateRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.QueryData) > 0 { - i -= len(m.QueryData) - copy(dAtA[i:], m.QueryData) - i = encodeVarintQuery(dAtA, i, uint64(len(m.QueryData))) - i-- - dAtA[i] = 0x12 - } - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QuerySmartContractStateResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QuerySmartContractStateResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QuerySmartContractStateResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Data) > 0 { - i -= len(m.Data) - copy(dAtA[i:], m.Data) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Data))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryCodeRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryCodeRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryCodeRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.CodeId != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.CodeId)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *CodeInfoResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *CodeInfoResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CodeInfoResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.InstantiatePermission.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - if len(m.DataHash) > 0 { - i -= len(m.DataHash) - copy(dAtA[i:], m.DataHash) - i = encodeVarintQuery(dAtA, i, uint64(len(m.DataHash))) - i-- - dAtA[i] = 0x1a - } - if len(m.Creator) > 0 { - i -= len(m.Creator) - copy(dAtA[i:], m.Creator) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Creator))) - i-- - dAtA[i] = 0x12 - } - if m.CodeID != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.CodeID)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *QueryCodeResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryCodeResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryCodeResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Data) > 0 { - i -= len(m.Data) - copy(dAtA[i:], m.Data) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Data))) - i-- - dAtA[i] = 0x12 - } - if m.CodeInfoResponse != nil { - { - size, err := m.CodeInfoResponse.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryCodesRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryCodesRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryCodesRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryCodesResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryCodesResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryCodesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.CodeInfos) > 0 { - for iNdEx := len(m.CodeInfos) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.CodeInfos[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryPinnedCodesRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryPinnedCodesRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryPinnedCodesRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - return len(dAtA) - i, nil -} - -func (m *QueryPinnedCodesResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryPinnedCodesResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryPinnedCodesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.CodeIDs) > 0 { - dAtA15 := make([]byte, len(m.CodeIDs)*10) - var j14 int - for _, num := range m.CodeIDs { - for num >= 1<<7 { - dAtA15[j14] = uint8(uint64(num)&0x7f | 0x80) - num >>= 7 - j14++ - } - dAtA15[j14] = uint8(num) - j14++ - } - i -= j14 - copy(dAtA[i:], dAtA15[:j14]) - i = encodeVarintQuery(dAtA, i, uint64(j14)) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryParamsRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryParamsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryParamsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryParamsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryParamsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *QueryContractsByCreatorRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryContractsByCreatorRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryContractsByCreatorRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.CreatorAddress) > 0 { - i -= len(m.CreatorAddress) - copy(dAtA[i:], m.CreatorAddress) - i = encodeVarintQuery(dAtA, i, uint64(len(m.CreatorAddress))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryContractsByCreatorResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryContractsByCreatorResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryContractsByCreatorResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.ContractAddresses) > 0 { - for iNdEx := len(m.ContractAddresses) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.ContractAddresses[iNdEx]) - copy(dAtA[i:], m.ContractAddresses[iNdEx]) - i = encodeVarintQuery(dAtA, i, uint64(len(m.ContractAddresses[iNdEx]))) - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { - offset -= sovQuery(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} - -func (m *QueryContractInfoRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryContractInfoResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = m.ContractInfo.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryContractHistoryRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryContractHistoryResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Entries) > 0 { - for _, e := range m.Entries { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryContractsByCodeRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.CodeId != 0 { - n += 1 + sovQuery(uint64(m.CodeId)) - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryContractsByCodeResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Contracts) > 0 { - for _, s := range m.Contracts { - l = len(s) - n += 1 + l + sovQuery(uint64(l)) - } - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryAllContractStateRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryAllContractStateResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Models) > 0 { - for _, e := range m.Models { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryRawContractStateRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.QueryData) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryRawContractStateResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Data) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QuerySmartContractStateRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.QueryData) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QuerySmartContractStateResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Data) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryCodeRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.CodeId != 0 { - n += 1 + sovQuery(uint64(m.CodeId)) - } - return n -} - -func (m *CodeInfoResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.CodeID != 0 { - n += 1 + sovQuery(uint64(m.CodeID)) - } - l = len(m.Creator) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.DataHash) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = m.InstantiatePermission.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryCodeResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.CodeInfoResponse != nil { - l = m.CodeInfoResponse.Size() - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Data) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryCodesRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryCodesResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.CodeInfos) > 0 { - for _, e := range m.CodeInfos { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryPinnedCodesRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryPinnedCodesResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.CodeIDs) > 0 { - l = 0 - for _, e := range m.CodeIDs { - l += sovQuery(uint64(e)) - } - n += 1 + sovQuery(uint64(l)) + l - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryParamsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryParamsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Params.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryContractsByCreatorRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.CreatorAddress) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryContractsByCreatorResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.ContractAddresses) > 0 { - for _, s := range m.ContractAddresses { - l = len(s) - n += 1 + l + sovQuery(uint64(l)) - } - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func sovQuery(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} - -func sozQuery(x uint64) (n int) { - return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} - -func (m *QueryContractInfoRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryContractInfoRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryContractInfoRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *QueryContractInfoResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryContractInfoResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryContractInfoResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ContractInfo", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ContractInfo.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *QueryContractHistoryRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryContractHistoryRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryContractHistoryRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageRequest{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *QueryContractHistoryResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryContractHistoryResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryContractHistoryResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Entries", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Entries = append(m.Entries, ContractCodeHistoryEntry{}) - if err := m.Entries[len(m.Entries)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageResponse{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *QueryContractsByCodeRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryContractsByCodeRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryContractsByCodeRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeId", wireType) - } - m.CodeId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CodeId |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageRequest{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *QueryContractsByCodeResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryContractsByCodeResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryContractsByCodeResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Contracts", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Contracts = append(m.Contracts, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageResponse{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *QueryAllContractStateRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryAllContractStateRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAllContractStateRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageRequest{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *QueryAllContractStateResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryAllContractStateResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAllContractStateResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Models", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Models = append(m.Models, Model{}) - if err := m.Models[len(m.Models)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageResponse{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *QueryRawContractStateRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryRawContractStateRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryRawContractStateRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field QueryData", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.QueryData = append(m.QueryData[:0], dAtA[iNdEx:postIndex]...) - if m.QueryData == nil { - m.QueryData = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *QueryRawContractStateResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryRawContractStateResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryRawContractStateResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) - if m.Data == nil { - m.Data = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *QuerySmartContractStateRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QuerySmartContractStateRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QuerySmartContractStateRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field QueryData", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.QueryData = append(m.QueryData[:0], dAtA[iNdEx:postIndex]...) - if m.QueryData == nil { - m.QueryData = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *QuerySmartContractStateResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QuerySmartContractStateResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QuerySmartContractStateResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) - if m.Data == nil { - m.Data = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *QueryCodeRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryCodeRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryCodeRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeId", wireType) - } - m.CodeId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CodeId |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *CodeInfoResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CodeInfoResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CodeInfoResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) - } - m.CodeID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CodeID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Creator", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Creator = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DataHash", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DataHash = append(m.DataHash[:0], dAtA[iNdEx:postIndex]...) - if m.DataHash == nil { - m.DataHash = []byte{} - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field InstantiatePermission", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.InstantiatePermission.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *QueryCodeResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryCodeResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryCodeResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeInfoResponse", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.CodeInfoResponse == nil { - m.CodeInfoResponse = &CodeInfoResponse{} - } - if err := m.CodeInfoResponse.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) - if m.Data == nil { - m.Data = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *QueryCodesRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryCodesRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryCodesRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageRequest{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *QueryCodesResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryCodesResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryCodesResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeInfos", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CodeInfos = append(m.CodeInfos, CodeInfoResponse{}) - if err := m.CodeInfos[len(m.CodeInfos)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageResponse{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *QueryPinnedCodesRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryPinnedCodesRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryPinnedCodesRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageRequest{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *QueryPinnedCodesResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryPinnedCodesResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryPinnedCodesResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType == 0 { - var v uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.CodeIDs = append(m.CodeIDs, v) - } else if wireType == 2 { - var packedLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - packedLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if packedLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + packedLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - var elementCount int - var count int - for _, integer := range dAtA[iNdEx:postIndex] { - if integer < 128 { - count++ - } - } - elementCount = count - if elementCount != 0 && len(m.CodeIDs) == 0 { - m.CodeIDs = make([]uint64, 0, elementCount) - } - for iNdEx < postIndex { - var v uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.CodeIDs = append(m.CodeIDs, v) - } - } else { - return fmt.Errorf("proto: wrong wireType = %d for field CodeIDs", wireType) - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageResponse{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *QueryParamsRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryParamsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryParamsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *QueryContractsByCreatorRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryContractsByCreatorRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryContractsByCreatorRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CreatorAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CreatorAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageRequest{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *QueryContractsByCreatorResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryContractsByCreatorResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryContractsByCreatorResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ContractAddresses", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ContractAddresses = append(m.ContractAddresses, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageResponse{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func skipQuery(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthQuery - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupQuery - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthQuery - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/wasm/types/query.pb.gw.go b/x/wasm/types/query.pb.gw.go deleted file mode 100644 index 32f3fd2..0000000 --- a/x/wasm/types/query.pb.gw.go +++ /dev/null @@ -1,1187 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: cosmwasm/wasm/v1/query.proto - -/* -Package types is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package types - -import ( - "context" - "io" - "net/http" - - "github.com/golang/protobuf/descriptor" - "github.com/golang/protobuf/proto" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" -) - -// Suppress "imported and not used" errors -var ( - _ codes.Code - _ io.Reader - _ status.Status - _ = runtime.String - _ = utilities.NewDoubleArray - _ = descriptor.ForMessage - _ = metadata.Join -) - -func request_Query_ContractInfo_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryContractInfoRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") - } - - protoReq.Address, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) - } - - msg, err := client.ContractInfo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err -} - -func local_request_Query_ContractInfo_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryContractInfoRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") - } - - protoReq.Address, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) - } - - msg, err := server.ContractInfo(ctx, &protoReq) - return msg, metadata, err -} - -var filter_Query_ContractHistory_0 = &utilities.DoubleArray{Encoding: map[string]int{"address": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} - -func request_Query_ContractHistory_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryContractHistoryRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") - } - - protoReq.Address, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_ContractHistory_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.ContractHistory(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err -} - -func local_request_Query_ContractHistory_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryContractHistoryRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") - } - - protoReq.Address, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_ContractHistory_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.ContractHistory(ctx, &protoReq) - return msg, metadata, err -} - -var filter_Query_ContractsByCode_0 = &utilities.DoubleArray{Encoding: map[string]int{"code_id": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} - -func request_Query_ContractsByCode_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryContractsByCodeRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["code_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "code_id") - } - - protoReq.CodeId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "code_id", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_ContractsByCode_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.ContractsByCode(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err -} - -func local_request_Query_ContractsByCode_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryContractsByCodeRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["code_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "code_id") - } - - protoReq.CodeId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "code_id", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_ContractsByCode_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.ContractsByCode(ctx, &protoReq) - return msg, metadata, err -} - -var filter_Query_AllContractState_0 = &utilities.DoubleArray{Encoding: map[string]int{"address": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} - -func request_Query_AllContractState_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAllContractStateRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") - } - - protoReq.Address, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_AllContractState_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.AllContractState(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err -} - -func local_request_Query_AllContractState_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAllContractStateRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") - } - - protoReq.Address, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_AllContractState_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.AllContractState(ctx, &protoReq) - return msg, metadata, err -} - -func request_Query_RawContractState_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRawContractStateRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") - } - - protoReq.Address, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) - } - - val, ok = pathParams["query_data"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "query_data") - } - - protoReq.QueryData, err = runtime.Bytes(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "query_data", err) - } - - msg, err := client.RawContractState(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err -} - -func local_request_Query_RawContractState_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRawContractStateRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") - } - - protoReq.Address, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) - } - - val, ok = pathParams["query_data"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "query_data") - } - - protoReq.QueryData, err = runtime.Bytes(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "query_data", err) - } - - msg, err := server.RawContractState(ctx, &protoReq) - return msg, metadata, err -} - -func request_Query_SmartContractState_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QuerySmartContractStateRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") - } - - protoReq.Address, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) - } - - val, ok = pathParams["query_data"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "query_data") - } - - protoReq.QueryData, err = runtime.Bytes(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "query_data", err) - } - - msg, err := client.SmartContractState(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err -} - -func local_request_Query_SmartContractState_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QuerySmartContractStateRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") - } - - protoReq.Address, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) - } - - val, ok = pathParams["query_data"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "query_data") - } - - protoReq.QueryData, err = runtime.Bytes(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "query_data", err) - } - - msg, err := server.SmartContractState(ctx, &protoReq) - return msg, metadata, err -} - -func request_Query_Code_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryCodeRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["code_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "code_id") - } - - protoReq.CodeId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "code_id", err) - } - - msg, err := client.Code(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err -} - -func local_request_Query_Code_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryCodeRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["code_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "code_id") - } - - protoReq.CodeId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "code_id", err) - } - - msg, err := server.Code(ctx, &protoReq) - return msg, metadata, err -} - -var filter_Query_Codes_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} - -func request_Query_Codes_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryCodesRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Codes_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Codes(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err -} - -func local_request_Query_Codes_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryCodesRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Codes_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Codes(ctx, &protoReq) - return msg, metadata, err -} - -var filter_Query_PinnedCodes_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} - -func request_Query_PinnedCodes_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryPinnedCodesRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_PinnedCodes_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.PinnedCodes(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err -} - -func local_request_Query_PinnedCodes_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryPinnedCodesRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_PinnedCodes_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.PinnedCodes(ctx, &protoReq) - return msg, metadata, err -} - -func request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryParamsRequest - var metadata runtime.ServerMetadata - - msg, err := client.Params(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err -} - -func local_request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryParamsRequest - var metadata runtime.ServerMetadata - - msg, err := server.Params(ctx, &protoReq) - return msg, metadata, err -} - -var filter_Query_ContractsByCreator_0 = &utilities.DoubleArray{Encoding: map[string]int{"creator_address": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} - -func request_Query_ContractsByCreator_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryContractsByCreatorRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["creator_address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "creator_address") - } - - protoReq.CreatorAddress, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "creator_address", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_ContractsByCreator_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.ContractsByCreator(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err -} - -func local_request_Query_ContractsByCreator_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryContractsByCreatorRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["creator_address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "creator_address") - } - - protoReq.CreatorAddress, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "creator_address", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_ContractsByCreator_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.ContractsByCreator(ctx, &protoReq) - return msg, metadata, err -} - -// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". -// UnaryRPC :call QueryServer directly. -// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. -// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. -func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { - mux.Handle("GET", pattern_Query_ContractInfo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_ContractInfo_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_ContractInfo_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_ContractHistory_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_ContractHistory_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_ContractHistory_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_ContractsByCode_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_ContractsByCode_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_ContractsByCode_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_AllContractState_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_AllContractState_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_AllContractState_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_RawContractState_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_RawContractState_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_RawContractState_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_SmartContractState_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_SmartContractState_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_SmartContractState_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_Code_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Code_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Code_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_Codes_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Codes_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Codes_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_PinnedCodes_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_PinnedCodes_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_PinnedCodes_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Params_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_ContractsByCreator_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_ContractsByCreator_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_ContractsByCreator_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - return nil -} - -// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterQueryHandler(ctx, mux, conn) -} - -// RegisterQueryHandler registers the http handlers for service Query to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) -} - -// RegisterQueryHandlerClient registers the http handlers for service Query -// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "QueryClient" to call the correct interceptors. -func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { - mux.Handle("GET", pattern_Query_ContractInfo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_ContractInfo_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_ContractInfo_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_ContractHistory_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_ContractHistory_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_ContractHistory_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_ContractsByCode_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_ContractsByCode_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_ContractsByCode_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_AllContractState_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_AllContractState_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_AllContractState_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_RawContractState_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_RawContractState_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_RawContractState_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_SmartContractState_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_SmartContractState_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_SmartContractState_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_Code_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Code_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Code_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_Codes_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Codes_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Codes_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_PinnedCodes_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_PinnedCodes_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_PinnedCodes_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Params_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_ContractsByCreator_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_ContractsByCreator_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_ContractsByCreator_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - return nil -} - -var ( - pattern_Query_ContractInfo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"cosmwasm", "wasm", "v1", "contract", "address"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_ContractHistory_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 2, 5}, []string{"cosmwasm", "wasm", "v1", "contract", "address", "history"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_ContractsByCode_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 2, 5}, []string{"cosmwasm", "wasm", "v1", "code", "code_id", "contracts"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_AllContractState_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 2, 5}, []string{"cosmwasm", "wasm", "v1", "contract", "address", "state"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_RawContractState_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 2, 5, 1, 0, 4, 1, 5, 6}, []string{"cosmwasm", "wasm", "v1", "contract", "address", "raw", "query_data"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_SmartContractState_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 2, 5, 1, 0, 4, 1, 5, 6}, []string{"cosmwasm", "wasm", "v1", "contract", "address", "smart", "query_data"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Code_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"cosmwasm", "wasm", "v1", "code", "code_id"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Codes_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"cosmwasm", "wasm", "v1", "code"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_PinnedCodes_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"cosmwasm", "wasm", "v1", "codes", "pinned"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"cosmwasm", "wasm", "v1", "codes", "params"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_ContractsByCreator_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4, 1, 0, 4, 1, 5, 5}, []string{"cosmwasm", "wasm", "v1", "contracts", "creator", "creator_address"}, "", runtime.AssumeColonVerbOpt(false))) -) - -var ( - forward_Query_ContractInfo_0 = runtime.ForwardResponseMessage - - forward_Query_ContractHistory_0 = runtime.ForwardResponseMessage - - forward_Query_ContractsByCode_0 = runtime.ForwardResponseMessage - - forward_Query_AllContractState_0 = runtime.ForwardResponseMessage - - forward_Query_RawContractState_0 = runtime.ForwardResponseMessage - - forward_Query_SmartContractState_0 = runtime.ForwardResponseMessage - - forward_Query_Code_0 = runtime.ForwardResponseMessage - - forward_Query_Codes_0 = runtime.ForwardResponseMessage - - forward_Query_PinnedCodes_0 = runtime.ForwardResponseMessage - - forward_Query_Params_0 = runtime.ForwardResponseMessage - - forward_Query_ContractsByCreator_0 = runtime.ForwardResponseMessage -) diff --git a/x/wasm/types/test_fixtures.go b/x/wasm/types/test_fixtures.go deleted file mode 100644 index e84b61f..0000000 --- a/x/wasm/types/test_fixtures.go +++ /dev/null @@ -1,443 +0,0 @@ -package types - -import ( - "bytes" - "crypto/sha256" - "encoding/hex" - "encoding/json" - "math/rand" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func GenesisFixture(mutators ...func(*GenesisState)) GenesisState { - const ( - numCodes = 2 - numContracts = 2 - numSequences = 2 - numMsg = 3 - ) - - fixture := GenesisState{ - Params: DefaultParams(), - Codes: make([]Code, numCodes), - Contracts: make([]Contract, numContracts), - Sequences: make([]Sequence, numSequences), - } - for i := 0; i < numCodes; i++ { - fixture.Codes[i] = CodeFixture() - } - for i := 0; i < numContracts; i++ { - fixture.Contracts[i] = ContractFixture() - } - for i := 0; i < numSequences; i++ { - fixture.Sequences[i] = Sequence{ - IDKey: randBytes(5), - Value: uint64(i), - } - } - - for _, m := range mutators { - m(&fixture) - } - return fixture -} - -func randBytes(n int) []byte { - r := make([]byte, n) - rand.Read(r) - return r -} - -func CodeFixture(mutators ...func(*Code)) Code { - wasmCode := randBytes(100) - - fixture := Code{ - CodeID: 1, - CodeInfo: CodeInfoFixture(WithSHA256CodeHash(wasmCode)), - CodeBytes: wasmCode, - } - - for _, m := range mutators { - m(&fixture) - } - return fixture -} - -func CodeInfoFixture(mutators ...func(*CodeInfo)) CodeInfo { - wasmCode := bytes.Repeat([]byte{0x1}, 10) - codeHash := sha256.Sum256(wasmCode) - const anyAddress = "cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4" - fixture := CodeInfo{ - CodeHash: codeHash[:], - Creator: anyAddress, - InstantiateConfig: AllowEverybody, - } - for _, m := range mutators { - m(&fixture) - } - return fixture -} - -func ContractFixture(mutators ...func(*Contract)) Contract { - const anyAddress = "cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4" - - fixture := Contract{ - ContractAddress: anyAddress, - ContractInfo: ContractInfoFixture(RandCreatedFields), - ContractState: []Model{{Key: []byte("anyKey"), Value: []byte("anyValue")}}, - } - fixture.ContractCodeHistory = []ContractCodeHistoryEntry{ContractCodeHistoryEntryFixture(func(e *ContractCodeHistoryEntry) { - e.Updated = fixture.ContractInfo.Created - })} - - for _, m := range mutators { - m(&fixture) - } - return fixture -} - -func OnlyGenesisFields(info *ContractInfo) { - info.Created = nil -} - -func RandCreatedFields(info *ContractInfo) { - info.Created = &AbsoluteTxPosition{BlockHeight: rand.Uint64(), TxIndex: rand.Uint64()} -} - -func ContractInfoFixture(mutators ...func(*ContractInfo)) ContractInfo { - const anyAddress = "cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4" - - fixture := ContractInfo{ - CodeID: 1, - Creator: anyAddress, - Label: "any", - Created: &AbsoluteTxPosition{BlockHeight: 1, TxIndex: 1}, - } - - for _, m := range mutators { - m(&fixture) - } - return fixture -} - -// ContractCodeHistoryEntryFixture test fixture -func ContractCodeHistoryEntryFixture(mutators ...func(*ContractCodeHistoryEntry)) ContractCodeHistoryEntry { - fixture := ContractCodeHistoryEntry{ - Operation: ContractCodeHistoryOperationTypeInit, - CodeID: 1, - Updated: ContractInfoFixture().Created, - Msg: []byte(`{"foo":"bar"}`), - } - for _, m := range mutators { - m(&fixture) - } - return fixture -} - -func WithSHA256CodeHash(wasmCode []byte) func(info *CodeInfo) { - return func(info *CodeInfo) { - codeHash := sha256.Sum256(wasmCode) - info.CodeHash = codeHash[:] - } -} - -func MsgStoreCodeFixture(mutators ...func(*MsgStoreCode)) *MsgStoreCode { - wasmIdent := []byte("\x00\x61\x73\x6D") - const anyAddress = "cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4" - r := &MsgStoreCode{ - Sender: anyAddress, - WASMByteCode: wasmIdent, - InstantiatePermission: &AllowEverybody, - } - for _, m := range mutators { - m(r) - } - return r -} - -func MsgInstantiateContractFixture(mutators ...func(*MsgInstantiateContract)) *MsgInstantiateContract { - const anyAddress = "cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4" - r := &MsgInstantiateContract{ - Sender: anyAddress, - Admin: anyAddress, - CodeID: 1, - Label: "testing", - Msg: []byte(`{"foo":"bar"}`), - Funds: sdk.Coins{{ - Denom: "stake", - Amount: sdk.NewInt(1), - }}, - } - for _, m := range mutators { - m(r) - } - return r -} - -func MsgExecuteContractFixture(mutators ...func(*MsgExecuteContract)) *MsgExecuteContract { - const ( - anyAddress = "cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4" - firstContractAddress = "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr" - ) - r := &MsgExecuteContract{ - Sender: anyAddress, - Contract: firstContractAddress, - Msg: []byte(`{"do":"something"}`), - Funds: sdk.Coins{{ - Denom: "stake", - Amount: sdk.NewInt(1), - }}, - } - for _, m := range mutators { - m(r) - } - return r -} - -func StoreCodeProposalFixture(mutators ...func(*StoreCodeProposal)) *StoreCodeProposal { - const anyAddress = "cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4" - wasm := []byte{0x0} - // got the value from shell sha256sum - codeHash, err := hex.DecodeString("6E340B9CFFB37A989CA544E6BB780A2C78901D3FB33738768511A30617AFA01D") - if err != nil { - panic(err) - } - - p := &StoreCodeProposal{ - Title: "Foo", - Description: "Bar", - RunAs: anyAddress, - WASMByteCode: wasm, - Source: "https://example.com/", - Builder: "cosmwasm/workspace-optimizer:v0.12.8", - CodeHash: codeHash, - } - for _, m := range mutators { - m(p) - } - return p -} - -func InstantiateContractProposalFixture(mutators ...func(p *InstantiateContractProposal)) *InstantiateContractProposal { - var ( - anyValidAddress sdk.AccAddress = bytes.Repeat([]byte{0x1}, ContractAddrLen) - - initMsg = struct { - Verifier sdk.AccAddress `json:"verifier"` - Beneficiary sdk.AccAddress `json:"beneficiary"` - }{ - Verifier: anyValidAddress, - Beneficiary: anyValidAddress, - } - ) - const anyAddress = "cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4" - - initMsgBz, err := json.Marshal(initMsg) - if err != nil { - panic(err) - } - p := &InstantiateContractProposal{ - Title: "Foo", - Description: "Bar", - RunAs: anyAddress, - Admin: anyAddress, - CodeID: 1, - Label: "testing", - Msg: initMsgBz, - Funds: nil, - } - - for _, m := range mutators { - m(p) - } - return p -} - -func InstantiateContract2ProposalFixture(mutators ...func(p *InstantiateContract2Proposal)) *InstantiateContract2Proposal { - var ( - anyValidAddress sdk.AccAddress = bytes.Repeat([]byte{0x1}, ContractAddrLen) - - initMsg = struct { - Verifier sdk.AccAddress `json:"verifier"` - Beneficiary sdk.AccAddress `json:"beneficiary"` - }{ - Verifier: anyValidAddress, - Beneficiary: anyValidAddress, - } - ) - const ( - anyAddress = "cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4" - mySalt = "myDefaultSalt" - ) - - initMsgBz, err := json.Marshal(initMsg) - if err != nil { - panic(err) - } - p := &InstantiateContract2Proposal{ - Title: "Foo", - Description: "Bar", - RunAs: anyAddress, - Admin: anyAddress, - CodeID: 1, - Label: "testing", - Msg: initMsgBz, - Funds: nil, - Salt: []byte(mySalt), - FixMsg: false, - } - - for _, m := range mutators { - m(p) - } - return p -} - -func StoreAndInstantiateContractProposalFixture(mutators ...func(p *StoreAndInstantiateContractProposal)) *StoreAndInstantiateContractProposal { - var ( - anyValidAddress sdk.AccAddress = bytes.Repeat([]byte{0x1}, ContractAddrLen) - - initMsg = struct { - Verifier sdk.AccAddress `json:"verifier"` - Beneficiary sdk.AccAddress `json:"beneficiary"` - }{ - Verifier: anyValidAddress, - Beneficiary: anyValidAddress, - } - ) - const anyAddress = "cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4" - wasm := []byte{0x0} - // got the value from shell sha256sum - codeHash, err := hex.DecodeString("6E340B9CFFB37A989CA544E6BB780A2C78901D3FB33738768511A30617AFA01D") - if err != nil { - panic(err) - } - - initMsgBz, err := json.Marshal(initMsg) - if err != nil { - panic(err) - } - p := &StoreAndInstantiateContractProposal{ - Title: "Foo", - Description: "Bar", - RunAs: anyAddress, - WASMByteCode: wasm, - Source: "https://example.com/", - Builder: "cosmwasm/workspace-optimizer:v0.12.9", - CodeHash: codeHash, - Admin: anyAddress, - Label: "testing", - Msg: initMsgBz, - Funds: nil, - } - - for _, m := range mutators { - m(p) - } - return p -} - -func MigrateContractProposalFixture(mutators ...func(p *MigrateContractProposal)) *MigrateContractProposal { - var ( - anyValidAddress sdk.AccAddress = bytes.Repeat([]byte{0x1}, ContractAddrLen) - - migMsg = struct { - Verifier sdk.AccAddress `json:"verifier"` - }{Verifier: anyValidAddress} - ) - - migMsgBz, err := json.Marshal(migMsg) - if err != nil { - panic(err) - } - const ( - contractAddr = "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr" - anyAddress = "cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4" - ) - p := &MigrateContractProposal{ - Title: "Foo", - Description: "Bar", - Contract: contractAddr, - CodeID: 1, - Msg: migMsgBz, - } - - for _, m := range mutators { - m(p) - } - return p -} - -func SudoContractProposalFixture(mutators ...func(p *SudoContractProposal)) *SudoContractProposal { - const ( - contractAddr = "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr" - ) - - p := &SudoContractProposal{ - Title: "Foo", - Description: "Bar", - Contract: contractAddr, - Msg: []byte(`{"do":"something"}`), - } - - for _, m := range mutators { - m(p) - } - return p -} - -func ExecuteContractProposalFixture(mutators ...func(p *ExecuteContractProposal)) *ExecuteContractProposal { - const ( - contractAddr = "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr" - anyAddress = "cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4" - ) - - p := &ExecuteContractProposal{ - Title: "Foo", - Description: "Bar", - Contract: contractAddr, - RunAs: anyAddress, - Msg: []byte(`{"do":"something"}`), - Funds: sdk.Coins{{ - Denom: "stake", - Amount: sdk.NewInt(1), - }}, - } - - for _, m := range mutators { - m(p) - } - return p -} - -func UpdateAdminProposalFixture(mutators ...func(p *UpdateAdminProposal)) *UpdateAdminProposal { - const ( - contractAddr = "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr" - anyAddress = "cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4" - ) - - p := &UpdateAdminProposal{ - Title: "Foo", - Description: "Bar", - NewAdmin: anyAddress, - Contract: contractAddr, - } - for _, m := range mutators { - m(p) - } - return p -} - -func ClearAdminProposalFixture(mutators ...func(p *ClearAdminProposal)) *ClearAdminProposal { - const contractAddr = "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr" - p := &ClearAdminProposal{ - Title: "Foo", - Description: "Bar", - Contract: contractAddr, - } - for _, m := range mutators { - m(p) - } - return p -} diff --git a/x/wasm/types/tx.go b/x/wasm/types/tx.go deleted file mode 100644 index 023cfdb..0000000 --- a/x/wasm/types/tx.go +++ /dev/null @@ -1,637 +0,0 @@ -package types - -import ( - "bytes" - "encoding/json" - "errors" - "strings" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -// RawContractMessage defines a json message that is sent or returned by a wasm contract. -// This type can hold any type of bytes. Until validateBasic is called there should not be -// any assumptions made that the data is valid syntax or semantic. -type RawContractMessage []byte - -func (r RawContractMessage) MarshalJSON() ([]byte, error) { - return json.RawMessage(r).MarshalJSON() -} - -func (r *RawContractMessage) UnmarshalJSON(b []byte) error { - if r == nil { - return errors.New("unmarshalJSON on nil pointer") - } - *r = append((*r)[0:0], b...) - return nil -} - -func (r *RawContractMessage) ValidateBasic() error { - if r == nil { - return ErrEmpty - } - if !json.Valid(*r) { - return ErrInvalid - } - return nil -} - -// Bytes returns raw bytes type -func (r RawContractMessage) Bytes() []byte { - return r -} - -// Equal content is equal json. Byte equal but this can change in the future. -func (r RawContractMessage) Equal(o RawContractMessage) bool { - return bytes.Equal(r.Bytes(), o.Bytes()) -} - -func (msg MsgStoreCode) Route() string { - return RouterKey -} - -func (msg MsgStoreCode) Type() string { - return "store-code" -} - -func (msg MsgStoreCode) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { - return err - } - - if err := validateWasmCode(msg.WASMByteCode, MaxWasmSize); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "code bytes %s", err.Error()) - } - - if msg.InstantiatePermission != nil { - if err := msg.InstantiatePermission.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "instantiate permission") - } - // AccessTypeOnlyAddress is still considered valid as legacy instantiation permission - // but not for new contracts - if msg.InstantiatePermission.Permission == AccessTypeOnlyAddress { - return ErrInvalid.Wrap("unsupported type, use AccessTypeAnyOfAddresses instead") - } - } - return nil -} - -func (msg MsgStoreCode) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -func (msg MsgStoreCode) GetSigners() []sdk.AccAddress { - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } - return []sdk.AccAddress{senderAddr} -} - -func (msg MsgInstantiateContract) Route() string { - return RouterKey -} - -func (msg MsgInstantiateContract) Type() string { - return "instantiate" -} - -func (msg MsgInstantiateContract) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { - return errorsmod.Wrap(err, "sender") - } - - if msg.CodeID == 0 { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "code id is required") - } - - if err := ValidateLabel(msg.Label); err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "label is required") - } - - if !msg.Funds.IsValid() { - return sdkerrors.ErrInvalidCoins - } - - if len(msg.Admin) != 0 { - if _, err := sdk.AccAddressFromBech32(msg.Admin); err != nil { - return errorsmod.Wrap(err, "admin") - } - } - if err := msg.Msg.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "payload msg") - } - return nil -} - -func (msg MsgInstantiateContract) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -func (msg MsgInstantiateContract) GetSigners() []sdk.AccAddress { - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } - return []sdk.AccAddress{senderAddr} -} - -func (msg MsgExecuteContract) Route() string { - return RouterKey -} - -func (msg MsgExecuteContract) Type() string { - return "execute" -} - -func (msg MsgExecuteContract) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { - return errorsmod.Wrap(err, "sender") - } - if _, err := sdk.AccAddressFromBech32(msg.Contract); err != nil { - return errorsmod.Wrap(err, "contract") - } - - if !msg.Funds.IsValid() { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, "sentFunds") - } - if err := msg.Msg.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "payload msg") - } - return nil -} - -func (msg MsgExecuteContract) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -func (msg MsgExecuteContract) GetSigners() []sdk.AccAddress { - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } - return []sdk.AccAddress{senderAddr} -} - -// GetMsg returns the payload message send to the contract -func (msg MsgExecuteContract) GetMsg() RawContractMessage { - return msg.Msg -} - -// GetFunds returns tokens send to the contract -func (msg MsgExecuteContract) GetFunds() sdk.Coins { - return msg.Funds -} - -// GetContract returns the bech32 address of the contract -func (msg MsgExecuteContract) GetContract() string { - return msg.Contract -} - -func (msg MsgMigrateContract) Route() string { - return RouterKey -} - -func (msg MsgMigrateContract) Type() string { - return "migrate" -} - -func (msg MsgMigrateContract) ValidateBasic() error { - if msg.CodeID == 0 { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "code id is required") - } - if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { - return errorsmod.Wrap(err, "sender") - } - if _, err := sdk.AccAddressFromBech32(msg.Contract); err != nil { - return errorsmod.Wrap(err, "contract") - } - - if err := msg.Msg.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "payload msg") - } - - return nil -} - -func (msg MsgMigrateContract) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -func (msg MsgMigrateContract) GetSigners() []sdk.AccAddress { - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } - return []sdk.AccAddress{senderAddr} -} - -// GetMsg returns the payload message send to the contract -func (msg MsgMigrateContract) GetMsg() RawContractMessage { - return msg.Msg -} - -// GetFunds returns tokens send to the contract -func (msg MsgMigrateContract) GetFunds() sdk.Coins { - return sdk.NewCoins() -} - -// GetContract returns the bech32 address of the contract -func (msg MsgMigrateContract) GetContract() string { - return msg.Contract -} - -func (msg MsgUpdateAdmin) Route() string { - return RouterKey -} - -func (msg MsgUpdateAdmin) Type() string { - return "update-contract-admin" -} - -func (msg MsgUpdateAdmin) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { - return errorsmod.Wrap(err, "sender") - } - if _, err := sdk.AccAddressFromBech32(msg.Contract); err != nil { - return errorsmod.Wrap(err, "contract") - } - if _, err := sdk.AccAddressFromBech32(msg.NewAdmin); err != nil { - return errorsmod.Wrap(err, "new admin") - } - if strings.EqualFold(msg.Sender, msg.NewAdmin) { - return errorsmod.Wrap(ErrInvalid, "new admin is the same as the old") - } - return nil -} - -func (msg MsgUpdateAdmin) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -func (msg MsgUpdateAdmin) GetSigners() []sdk.AccAddress { - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } - return []sdk.AccAddress{senderAddr} -} - -func (msg MsgClearAdmin) Route() string { - return RouterKey -} - -func (msg MsgClearAdmin) Type() string { - return "clear-contract-admin" -} - -func (msg MsgClearAdmin) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { - return errorsmod.Wrap(err, "sender") - } - if _, err := sdk.AccAddressFromBech32(msg.Contract); err != nil { - return errorsmod.Wrap(err, "contract") - } - return nil -} - -func (msg MsgClearAdmin) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -func (msg MsgClearAdmin) GetSigners() []sdk.AccAddress { - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } - return []sdk.AccAddress{senderAddr} -} - -func (msg MsgIBCSend) Route() string { - return RouterKey -} - -func (msg MsgIBCSend) Type() string { - return "wasm-ibc-send" -} - -func (msg MsgIBCSend) ValidateBasic() error { - return nil -} - -func (msg MsgIBCSend) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -func (msg MsgIBCSend) GetSigners() []sdk.AccAddress { - return nil -} - -func (msg MsgIBCCloseChannel) Route() string { - return RouterKey -} - -func (msg MsgIBCCloseChannel) Type() string { - return "wasm-ibc-close" -} - -func (msg MsgIBCCloseChannel) ValidateBasic() error { - return nil -} - -func (msg MsgIBCCloseChannel) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -func (msg MsgIBCCloseChannel) GetSigners() []sdk.AccAddress { - return nil -} - -var _ sdk.Msg = &MsgInstantiateContract2{} - -func (msg MsgInstantiateContract2) Route() string { - return RouterKey -} - -func (msg MsgInstantiateContract2) Type() string { - return "instantiate2" -} - -func (msg MsgInstantiateContract2) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { - return errorsmod.Wrap(err, "sender") - } - - if msg.CodeID == 0 { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "code id is required") - } - - if err := ValidateLabel(msg.Label); err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "label is required") - } - - if !msg.Funds.IsValid() { - return sdkerrors.ErrInvalidCoins - } - - if len(msg.Admin) != 0 { - if _, err := sdk.AccAddressFromBech32(msg.Admin); err != nil { - return errorsmod.Wrap(err, "admin") - } - } - if err := msg.Msg.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "payload msg") - } - if err := ValidateSalt(msg.Salt); err != nil { - return errorsmod.Wrap(err, "salt") - } - return nil -} - -func (msg MsgInstantiateContract2) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -func (msg MsgInstantiateContract2) GetSigners() []sdk.AccAddress { - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } - return []sdk.AccAddress{senderAddr} -} - -func (msg MsgUpdateInstantiateConfig) Route() string { - return RouterKey -} - -func (msg MsgUpdateInstantiateConfig) Type() string { - return "update-instantiate-config" -} - -func (msg MsgUpdateInstantiateConfig) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { - return errorsmod.Wrap(err, "sender") - } - - if msg.CodeID == 0 { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "code id is required") - } - - if msg.NewInstantiatePermission == nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "instantiate permission is required") - } - - if err := msg.NewInstantiatePermission.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "instantiate permission") - } - // AccessTypeOnlyAddress is still considered valid as legacy instantiation permission - // but not for new contracts - if msg.NewInstantiatePermission.Permission == AccessTypeOnlyAddress { - return ErrInvalid.Wrap("unsupported type, use AccessTypeAnyOfAddresses instead") - } - // AccessTypeOnlyAddress is still considered valid as legacy instantiation permission - // but not for new contracts - if msg.NewInstantiatePermission.Permission == AccessTypeOnlyAddress { - return ErrInvalid.Wrap("unsupported type, use AccessTypeAnyOfAddresses instead") - } - - return nil -} - -func (msg MsgUpdateInstantiateConfig) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -func (msg MsgUpdateInstantiateConfig) GetSigners() []sdk.AccAddress { - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } - return []sdk.AccAddress{senderAddr} -} - -func (msg MsgUpdateParams) Route() string { - return RouterKey -} - -func (msg MsgUpdateParams) Type() string { - return "update-params" -} - -func (msg MsgUpdateParams) GetSigners() []sdk.AccAddress { - authority, err := sdk.AccAddressFromBech32(msg.Authority) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } - return []sdk.AccAddress{authority} -} - -func (msg MsgUpdateParams) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -func (msg MsgUpdateParams) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Authority); err != nil { - return errorsmod.Wrap(err, "authority") - } - return msg.Params.ValidateBasic() -} - -func (msg MsgPinCodes) Route() string { - return RouterKey -} - -func (msg MsgPinCodes) Type() string { - return "pin-codes" -} - -func (msg MsgPinCodes) GetSigners() []sdk.AccAddress { - authority, err := sdk.AccAddressFromBech32(msg.Authority) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } - return []sdk.AccAddress{authority} -} - -func (msg MsgPinCodes) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -func (msg MsgPinCodes) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Authority); err != nil { - return errorsmod.Wrap(err, "authority") - } - if len(msg.CodeIDs) == 0 { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "empty code ids") - } - return nil -} - -func (msg MsgUnpinCodes) Route() string { - return RouterKey -} - -func (msg MsgUnpinCodes) Type() string { - return "unpin-codes" -} - -func (msg MsgUnpinCodes) GetSigners() []sdk.AccAddress { - authority, err := sdk.AccAddressFromBech32(msg.Authority) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } - return []sdk.AccAddress{authority} -} - -func (msg MsgUnpinCodes) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -func (msg MsgUnpinCodes) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Authority); err != nil { - return errorsmod.Wrap(err, "authority") - } - if len(msg.CodeIDs) == 0 { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "empty code ids") - } - return nil -} - -func (msg MsgSudoContract) Route() string { - return RouterKey -} - -func (msg MsgSudoContract) Type() string { - return "sudo-contract" -} - -func (msg MsgSudoContract) GetSigners() []sdk.AccAddress { - authority, err := sdk.AccAddressFromBech32(msg.Authority) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } - return []sdk.AccAddress{authority} -} - -func (msg MsgSudoContract) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -func (msg MsgSudoContract) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Authority); err != nil { - return errorsmod.Wrap(err, "authority") - } - if _, err := sdk.AccAddressFromBech32(msg.Contract); err != nil { - return errorsmod.Wrap(err, "contract") - } - if err := msg.Msg.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "payload msg") - } - return nil -} - -func (msg MsgStoreAndInstantiateContract) Route() string { - return RouterKey -} - -func (msg MsgStoreAndInstantiateContract) Type() string { - return "store-and-instantiate-contract" -} - -func (msg MsgStoreAndInstantiateContract) GetSigners() []sdk.AccAddress { - authority, err := sdk.AccAddressFromBech32(msg.Authority) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } - return []sdk.AccAddress{authority} -} - -func (msg MsgStoreAndInstantiateContract) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -func (msg MsgStoreAndInstantiateContract) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Authority); err != nil { - return errorsmod.Wrap(err, "authority") - } - - if err := ValidateLabel(msg.Label); err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "label is required") - } - - if !msg.Funds.IsValid() { - return sdkerrors.ErrInvalidCoins - } - - if len(msg.Admin) != 0 { - if _, err := sdk.AccAddressFromBech32(msg.Admin); err != nil { - return errorsmod.Wrap(err, "admin") - } - } - - if err := ValidateVerificationInfo(msg.Source, msg.Builder, msg.CodeHash); err != nil { - return errorsmod.Wrapf(err, "code verification info") - } - - if err := msg.Msg.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "payload msg") - } - - if err := validateWasmCode(msg.WASMByteCode, MaxWasmSize); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "code bytes %s", err.Error()) - } - - if msg.InstantiatePermission != nil { - if err := msg.InstantiatePermission.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "instantiate permission") - } - // AccessTypeOnlyAddress is still considered valid as legacy instantiation permission - // but not for new contracts - if msg.InstantiatePermission.Permission == AccessTypeOnlyAddress { - return ErrInvalid.Wrap("unsupported type, use AccessTypeAnyOfAddresses instead") - } - } - return nil -} diff --git a/x/wasm/types/tx.pb.go b/x/wasm/types/tx.pb.go deleted file mode 100644 index ae7879a..0000000 --- a/x/wasm/types/tx.pb.go +++ /dev/null @@ -1,7139 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmwasm/wasm/v1/tx.proto - -package types - -import ( - context "context" - fmt "fmt" - io "io" - math "math" - math_bits "math/bits" - - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/cosmos-sdk/types/msgservice" - _ "github.com/cosmos/cosmos-sdk/types/tx/amino" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = proto.Marshal - _ = fmt.Errorf - _ = math.Inf -) - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// MsgStoreCode submit Wasm code to the system -type MsgStoreCode struct { - // Sender is the actor that signed the messages - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - // WASMByteCode can be raw or gzip compressed - WASMByteCode []byte `protobuf:"bytes,2,opt,name=wasm_byte_code,json=wasmByteCode,proto3" json:"wasm_byte_code,omitempty"` - // InstantiatePermission access control to apply on contract creation, - // optional - InstantiatePermission *AccessConfig `protobuf:"bytes,5,opt,name=instantiate_permission,json=instantiatePermission,proto3" json:"instantiate_permission,omitempty"` -} - -func (m *MsgStoreCode) Reset() { *m = MsgStoreCode{} } -func (m *MsgStoreCode) String() string { return proto.CompactTextString(m) } -func (*MsgStoreCode) ProtoMessage() {} -func (*MsgStoreCode) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{0} -} - -func (m *MsgStoreCode) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgStoreCode) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgStoreCode.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *MsgStoreCode) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgStoreCode.Merge(m, src) -} - -func (m *MsgStoreCode) XXX_Size() int { - return m.Size() -} - -func (m *MsgStoreCode) XXX_DiscardUnknown() { - xxx_messageInfo_MsgStoreCode.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgStoreCode proto.InternalMessageInfo - -// MsgStoreCodeResponse returns store result data. -type MsgStoreCodeResponse struct { - // CodeID is the reference to the stored WASM code - CodeID uint64 `protobuf:"varint,1,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` - // Checksum is the sha256 hash of the stored code - Checksum []byte `protobuf:"bytes,2,opt,name=checksum,proto3" json:"checksum,omitempty"` -} - -func (m *MsgStoreCodeResponse) Reset() { *m = MsgStoreCodeResponse{} } -func (m *MsgStoreCodeResponse) String() string { return proto.CompactTextString(m) } -func (*MsgStoreCodeResponse) ProtoMessage() {} -func (*MsgStoreCodeResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{1} -} - -func (m *MsgStoreCodeResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgStoreCodeResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgStoreCodeResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *MsgStoreCodeResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgStoreCodeResponse.Merge(m, src) -} - -func (m *MsgStoreCodeResponse) XXX_Size() int { - return m.Size() -} - -func (m *MsgStoreCodeResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgStoreCodeResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgStoreCodeResponse proto.InternalMessageInfo - -// MsgInstantiateContract create a new smart contract instance for the given -// code id. -type MsgInstantiateContract struct { - // Sender is the that actor that signed the messages - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - // Admin is an optional address that can execute migrations - Admin string `protobuf:"bytes,2,opt,name=admin,proto3" json:"admin,omitempty"` - // CodeID is the reference to the stored WASM code - CodeID uint64 `protobuf:"varint,3,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` - // Label is optional metadata to be stored with a contract instance. - Label string `protobuf:"bytes,4,opt,name=label,proto3" json:"label,omitempty"` - // Msg json encoded message to be passed to the contract on instantiation - Msg RawContractMessage `protobuf:"bytes,5,opt,name=msg,proto3,casttype=RawContractMessage" json:"msg,omitempty"` - // Funds coins that are transferred to the contract on instantiation - Funds github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,6,rep,name=funds,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"funds"` -} - -func (m *MsgInstantiateContract) Reset() { *m = MsgInstantiateContract{} } -func (m *MsgInstantiateContract) String() string { return proto.CompactTextString(m) } -func (*MsgInstantiateContract) ProtoMessage() {} -func (*MsgInstantiateContract) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{2} -} - -func (m *MsgInstantiateContract) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgInstantiateContract) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgInstantiateContract.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *MsgInstantiateContract) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgInstantiateContract.Merge(m, src) -} - -func (m *MsgInstantiateContract) XXX_Size() int { - return m.Size() -} - -func (m *MsgInstantiateContract) XXX_DiscardUnknown() { - xxx_messageInfo_MsgInstantiateContract.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgInstantiateContract proto.InternalMessageInfo - -// MsgInstantiateContractResponse return instantiation result data -type MsgInstantiateContractResponse struct { - // Address is the bech32 address of the new contract instance. - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - // Data contains bytes to returned from the contract - Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"` -} - -func (m *MsgInstantiateContractResponse) Reset() { *m = MsgInstantiateContractResponse{} } -func (m *MsgInstantiateContractResponse) String() string { return proto.CompactTextString(m) } -func (*MsgInstantiateContractResponse) ProtoMessage() {} -func (*MsgInstantiateContractResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{3} -} - -func (m *MsgInstantiateContractResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgInstantiateContractResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgInstantiateContractResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *MsgInstantiateContractResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgInstantiateContractResponse.Merge(m, src) -} - -func (m *MsgInstantiateContractResponse) XXX_Size() int { - return m.Size() -} - -func (m *MsgInstantiateContractResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgInstantiateContractResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgInstantiateContractResponse proto.InternalMessageInfo - -// MsgInstantiateContract2 create a new smart contract instance for the given -// code id with a predicable address. -type MsgInstantiateContract2 struct { - // Sender is the that actor that signed the messages - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - // Admin is an optional address that can execute migrations - Admin string `protobuf:"bytes,2,opt,name=admin,proto3" json:"admin,omitempty"` - // CodeID is the reference to the stored WASM code - CodeID uint64 `protobuf:"varint,3,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` - // Label is optional metadata to be stored with a contract instance. - Label string `protobuf:"bytes,4,opt,name=label,proto3" json:"label,omitempty"` - // Msg json encoded message to be passed to the contract on instantiation - Msg RawContractMessage `protobuf:"bytes,5,opt,name=msg,proto3,casttype=RawContractMessage" json:"msg,omitempty"` - // Funds coins that are transferred to the contract on instantiation - Funds github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,6,rep,name=funds,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"funds"` - // Salt is an arbitrary value provided by the sender. Size can be 1 to 64. - Salt []byte `protobuf:"bytes,7,opt,name=salt,proto3" json:"salt,omitempty"` - // FixMsg include the msg value into the hash for the predictable address. - // Default is false - FixMsg bool `protobuf:"varint,8,opt,name=fix_msg,json=fixMsg,proto3" json:"fix_msg,omitempty"` -} - -func (m *MsgInstantiateContract2) Reset() { *m = MsgInstantiateContract2{} } -func (m *MsgInstantiateContract2) String() string { return proto.CompactTextString(m) } -func (*MsgInstantiateContract2) ProtoMessage() {} -func (*MsgInstantiateContract2) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{4} -} - -func (m *MsgInstantiateContract2) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgInstantiateContract2) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgInstantiateContract2.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *MsgInstantiateContract2) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgInstantiateContract2.Merge(m, src) -} - -func (m *MsgInstantiateContract2) XXX_Size() int { - return m.Size() -} - -func (m *MsgInstantiateContract2) XXX_DiscardUnknown() { - xxx_messageInfo_MsgInstantiateContract2.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgInstantiateContract2 proto.InternalMessageInfo - -// MsgInstantiateContract2Response return instantiation result data -type MsgInstantiateContract2Response struct { - // Address is the bech32 address of the new contract instance. - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - // Data contains bytes to returned from the contract - Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"` -} - -func (m *MsgInstantiateContract2Response) Reset() { *m = MsgInstantiateContract2Response{} } -func (m *MsgInstantiateContract2Response) String() string { return proto.CompactTextString(m) } -func (*MsgInstantiateContract2Response) ProtoMessage() {} -func (*MsgInstantiateContract2Response) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{5} -} - -func (m *MsgInstantiateContract2Response) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgInstantiateContract2Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgInstantiateContract2Response.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *MsgInstantiateContract2Response) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgInstantiateContract2Response.Merge(m, src) -} - -func (m *MsgInstantiateContract2Response) XXX_Size() int { - return m.Size() -} - -func (m *MsgInstantiateContract2Response) XXX_DiscardUnknown() { - xxx_messageInfo_MsgInstantiateContract2Response.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgInstantiateContract2Response proto.InternalMessageInfo - -// MsgExecuteContract submits the given message data to a smart contract -type MsgExecuteContract struct { - // Sender is the that actor that signed the messages - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - // Contract is the address of the smart contract - Contract string `protobuf:"bytes,2,opt,name=contract,proto3" json:"contract,omitempty"` - // Msg json encoded message to be passed to the contract - Msg RawContractMessage `protobuf:"bytes,3,opt,name=msg,proto3,casttype=RawContractMessage" json:"msg,omitempty"` - // Funds coins that are transferred to the contract on execution - Funds github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,5,rep,name=funds,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"funds"` -} - -func (m *MsgExecuteContract) Reset() { *m = MsgExecuteContract{} } -func (m *MsgExecuteContract) String() string { return proto.CompactTextString(m) } -func (*MsgExecuteContract) ProtoMessage() {} -func (*MsgExecuteContract) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{6} -} - -func (m *MsgExecuteContract) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgExecuteContract) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgExecuteContract.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *MsgExecuteContract) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgExecuteContract.Merge(m, src) -} - -func (m *MsgExecuteContract) XXX_Size() int { - return m.Size() -} - -func (m *MsgExecuteContract) XXX_DiscardUnknown() { - xxx_messageInfo_MsgExecuteContract.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgExecuteContract proto.InternalMessageInfo - -// MsgExecuteContractResponse returns execution result data. -type MsgExecuteContractResponse struct { - // Data contains bytes to returned from the contract - Data []byte `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"` -} - -func (m *MsgExecuteContractResponse) Reset() { *m = MsgExecuteContractResponse{} } -func (m *MsgExecuteContractResponse) String() string { return proto.CompactTextString(m) } -func (*MsgExecuteContractResponse) ProtoMessage() {} -func (*MsgExecuteContractResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{7} -} - -func (m *MsgExecuteContractResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgExecuteContractResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgExecuteContractResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *MsgExecuteContractResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgExecuteContractResponse.Merge(m, src) -} - -func (m *MsgExecuteContractResponse) XXX_Size() int { - return m.Size() -} - -func (m *MsgExecuteContractResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgExecuteContractResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgExecuteContractResponse proto.InternalMessageInfo - -// MsgMigrateContract runs a code upgrade/ downgrade for a smart contract -type MsgMigrateContract struct { - // Sender is the that actor that signed the messages - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - // Contract is the address of the smart contract - Contract string `protobuf:"bytes,2,opt,name=contract,proto3" json:"contract,omitempty"` - // CodeID references the new WASM code - CodeID uint64 `protobuf:"varint,3,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` - // Msg json encoded message to be passed to the contract on migration - Msg RawContractMessage `protobuf:"bytes,4,opt,name=msg,proto3,casttype=RawContractMessage" json:"msg,omitempty"` -} - -func (m *MsgMigrateContract) Reset() { *m = MsgMigrateContract{} } -func (m *MsgMigrateContract) String() string { return proto.CompactTextString(m) } -func (*MsgMigrateContract) ProtoMessage() {} -func (*MsgMigrateContract) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{8} -} - -func (m *MsgMigrateContract) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgMigrateContract) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgMigrateContract.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *MsgMigrateContract) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgMigrateContract.Merge(m, src) -} - -func (m *MsgMigrateContract) XXX_Size() int { - return m.Size() -} - -func (m *MsgMigrateContract) XXX_DiscardUnknown() { - xxx_messageInfo_MsgMigrateContract.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgMigrateContract proto.InternalMessageInfo - -// MsgMigrateContractResponse returns contract migration result data. -type MsgMigrateContractResponse struct { - // Data contains same raw bytes returned as data from the wasm contract. - // (May be empty) - Data []byte `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"` -} - -func (m *MsgMigrateContractResponse) Reset() { *m = MsgMigrateContractResponse{} } -func (m *MsgMigrateContractResponse) String() string { return proto.CompactTextString(m) } -func (*MsgMigrateContractResponse) ProtoMessage() {} -func (*MsgMigrateContractResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{9} -} - -func (m *MsgMigrateContractResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgMigrateContractResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgMigrateContractResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *MsgMigrateContractResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgMigrateContractResponse.Merge(m, src) -} - -func (m *MsgMigrateContractResponse) XXX_Size() int { - return m.Size() -} - -func (m *MsgMigrateContractResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgMigrateContractResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgMigrateContractResponse proto.InternalMessageInfo - -// MsgUpdateAdmin sets a new admin for a smart contract -type MsgUpdateAdmin struct { - // Sender is the that actor that signed the messages - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - // NewAdmin address to be set - NewAdmin string `protobuf:"bytes,2,opt,name=new_admin,json=newAdmin,proto3" json:"new_admin,omitempty"` - // Contract is the address of the smart contract - Contract string `protobuf:"bytes,3,opt,name=contract,proto3" json:"contract,omitempty"` -} - -func (m *MsgUpdateAdmin) Reset() { *m = MsgUpdateAdmin{} } -func (m *MsgUpdateAdmin) String() string { return proto.CompactTextString(m) } -func (*MsgUpdateAdmin) ProtoMessage() {} -func (*MsgUpdateAdmin) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{10} -} - -func (m *MsgUpdateAdmin) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgUpdateAdmin) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgUpdateAdmin.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *MsgUpdateAdmin) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgUpdateAdmin.Merge(m, src) -} - -func (m *MsgUpdateAdmin) XXX_Size() int { - return m.Size() -} - -func (m *MsgUpdateAdmin) XXX_DiscardUnknown() { - xxx_messageInfo_MsgUpdateAdmin.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgUpdateAdmin proto.InternalMessageInfo - -// MsgUpdateAdminResponse returns empty data -type MsgUpdateAdminResponse struct{} - -func (m *MsgUpdateAdminResponse) Reset() { *m = MsgUpdateAdminResponse{} } -func (m *MsgUpdateAdminResponse) String() string { return proto.CompactTextString(m) } -func (*MsgUpdateAdminResponse) ProtoMessage() {} -func (*MsgUpdateAdminResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{11} -} - -func (m *MsgUpdateAdminResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgUpdateAdminResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgUpdateAdminResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *MsgUpdateAdminResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgUpdateAdminResponse.Merge(m, src) -} - -func (m *MsgUpdateAdminResponse) XXX_Size() int { - return m.Size() -} - -func (m *MsgUpdateAdminResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgUpdateAdminResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgUpdateAdminResponse proto.InternalMessageInfo - -// MsgClearAdmin removes any admin stored for a smart contract -type MsgClearAdmin struct { - // Sender is the actor that signed the messages - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - // Contract is the address of the smart contract - Contract string `protobuf:"bytes,3,opt,name=contract,proto3" json:"contract,omitempty"` -} - -func (m *MsgClearAdmin) Reset() { *m = MsgClearAdmin{} } -func (m *MsgClearAdmin) String() string { return proto.CompactTextString(m) } -func (*MsgClearAdmin) ProtoMessage() {} -func (*MsgClearAdmin) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{12} -} - -func (m *MsgClearAdmin) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgClearAdmin) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgClearAdmin.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *MsgClearAdmin) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgClearAdmin.Merge(m, src) -} - -func (m *MsgClearAdmin) XXX_Size() int { - return m.Size() -} - -func (m *MsgClearAdmin) XXX_DiscardUnknown() { - xxx_messageInfo_MsgClearAdmin.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgClearAdmin proto.InternalMessageInfo - -// MsgClearAdminResponse returns empty data -type MsgClearAdminResponse struct{} - -func (m *MsgClearAdminResponse) Reset() { *m = MsgClearAdminResponse{} } -func (m *MsgClearAdminResponse) String() string { return proto.CompactTextString(m) } -func (*MsgClearAdminResponse) ProtoMessage() {} -func (*MsgClearAdminResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{13} -} - -func (m *MsgClearAdminResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgClearAdminResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgClearAdminResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *MsgClearAdminResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgClearAdminResponse.Merge(m, src) -} - -func (m *MsgClearAdminResponse) XXX_Size() int { - return m.Size() -} - -func (m *MsgClearAdminResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgClearAdminResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgClearAdminResponse proto.InternalMessageInfo - -// MsgUpdateInstantiateConfig updates instantiate config for a smart contract -type MsgUpdateInstantiateConfig struct { - // Sender is the that actor that signed the messages - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - // CodeID references the stored WASM code - CodeID uint64 `protobuf:"varint,2,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` - // NewInstantiatePermission is the new access control - NewInstantiatePermission *AccessConfig `protobuf:"bytes,3,opt,name=new_instantiate_permission,json=newInstantiatePermission,proto3" json:"new_instantiate_permission,omitempty"` -} - -func (m *MsgUpdateInstantiateConfig) Reset() { *m = MsgUpdateInstantiateConfig{} } -func (m *MsgUpdateInstantiateConfig) String() string { return proto.CompactTextString(m) } -func (*MsgUpdateInstantiateConfig) ProtoMessage() {} -func (*MsgUpdateInstantiateConfig) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{14} -} - -func (m *MsgUpdateInstantiateConfig) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgUpdateInstantiateConfig) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgUpdateInstantiateConfig.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *MsgUpdateInstantiateConfig) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgUpdateInstantiateConfig.Merge(m, src) -} - -func (m *MsgUpdateInstantiateConfig) XXX_Size() int { - return m.Size() -} - -func (m *MsgUpdateInstantiateConfig) XXX_DiscardUnknown() { - xxx_messageInfo_MsgUpdateInstantiateConfig.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgUpdateInstantiateConfig proto.InternalMessageInfo - -// MsgUpdateInstantiateConfigResponse returns empty data -type MsgUpdateInstantiateConfigResponse struct{} - -func (m *MsgUpdateInstantiateConfigResponse) Reset() { *m = MsgUpdateInstantiateConfigResponse{} } -func (m *MsgUpdateInstantiateConfigResponse) String() string { return proto.CompactTextString(m) } -func (*MsgUpdateInstantiateConfigResponse) ProtoMessage() {} -func (*MsgUpdateInstantiateConfigResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{15} -} - -func (m *MsgUpdateInstantiateConfigResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgUpdateInstantiateConfigResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgUpdateInstantiateConfigResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *MsgUpdateInstantiateConfigResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgUpdateInstantiateConfigResponse.Merge(m, src) -} - -func (m *MsgUpdateInstantiateConfigResponse) XXX_Size() int { - return m.Size() -} - -func (m *MsgUpdateInstantiateConfigResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgUpdateInstantiateConfigResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgUpdateInstantiateConfigResponse proto.InternalMessageInfo - -// MsgUpdateParams is the MsgUpdateParams request type. -// -// Since: 0.40 -type MsgUpdateParams struct { - // Authority is the address of the governance account. - Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` - // params defines the x/wasm parameters to update. - // - // NOTE: All parameters must be supplied. - Params Params `protobuf:"bytes,2,opt,name=params,proto3" json:"params"` -} - -func (m *MsgUpdateParams) Reset() { *m = MsgUpdateParams{} } -func (m *MsgUpdateParams) String() string { return proto.CompactTextString(m) } -func (*MsgUpdateParams) ProtoMessage() {} -func (*MsgUpdateParams) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{16} -} - -func (m *MsgUpdateParams) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgUpdateParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgUpdateParams.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *MsgUpdateParams) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgUpdateParams.Merge(m, src) -} - -func (m *MsgUpdateParams) XXX_Size() int { - return m.Size() -} - -func (m *MsgUpdateParams) XXX_DiscardUnknown() { - xxx_messageInfo_MsgUpdateParams.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgUpdateParams proto.InternalMessageInfo - -// MsgUpdateParamsResponse defines the response structure for executing a -// MsgUpdateParams message. -// -// Since: 0.40 -type MsgUpdateParamsResponse struct{} - -func (m *MsgUpdateParamsResponse) Reset() { *m = MsgUpdateParamsResponse{} } -func (m *MsgUpdateParamsResponse) String() string { return proto.CompactTextString(m) } -func (*MsgUpdateParamsResponse) ProtoMessage() {} -func (*MsgUpdateParamsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{17} -} - -func (m *MsgUpdateParamsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgUpdateParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgUpdateParamsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *MsgUpdateParamsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgUpdateParamsResponse.Merge(m, src) -} - -func (m *MsgUpdateParamsResponse) XXX_Size() int { - return m.Size() -} - -func (m *MsgUpdateParamsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgUpdateParamsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgUpdateParamsResponse proto.InternalMessageInfo - -// MsgSudoContract is the MsgSudoContract request type. -// -// Since: 0.40 -type MsgSudoContract struct { - // Authority is the address of the governance account. - Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` - // Contract is the address of the smart contract - Contract string `protobuf:"bytes,2,opt,name=contract,proto3" json:"contract,omitempty"` - // Msg json encoded message to be passed to the contract as sudo - Msg RawContractMessage `protobuf:"bytes,3,opt,name=msg,proto3,casttype=RawContractMessage" json:"msg,omitempty"` -} - -func (m *MsgSudoContract) Reset() { *m = MsgSudoContract{} } -func (m *MsgSudoContract) String() string { return proto.CompactTextString(m) } -func (*MsgSudoContract) ProtoMessage() {} -func (*MsgSudoContract) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{18} -} - -func (m *MsgSudoContract) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgSudoContract) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgSudoContract.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *MsgSudoContract) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgSudoContract.Merge(m, src) -} - -func (m *MsgSudoContract) XXX_Size() int { - return m.Size() -} - -func (m *MsgSudoContract) XXX_DiscardUnknown() { - xxx_messageInfo_MsgSudoContract.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgSudoContract proto.InternalMessageInfo - -// MsgSudoContractResponse defines the response structure for executing a -// MsgSudoContract message. -// -// Since: 0.40 -type MsgSudoContractResponse struct { - // Data contains bytes to returned from the contract - Data []byte `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"` -} - -func (m *MsgSudoContractResponse) Reset() { *m = MsgSudoContractResponse{} } -func (m *MsgSudoContractResponse) String() string { return proto.CompactTextString(m) } -func (*MsgSudoContractResponse) ProtoMessage() {} -func (*MsgSudoContractResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{19} -} - -func (m *MsgSudoContractResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgSudoContractResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgSudoContractResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *MsgSudoContractResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgSudoContractResponse.Merge(m, src) -} - -func (m *MsgSudoContractResponse) XXX_Size() int { - return m.Size() -} - -func (m *MsgSudoContractResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgSudoContractResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgSudoContractResponse proto.InternalMessageInfo - -// MsgPinCodes is the MsgPinCodes request type. -// -// Since: 0.40 -type MsgPinCodes struct { - // Authority is the address of the governance account. - Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` - // CodeIDs references the new WASM codes - CodeIDs []uint64 `protobuf:"varint,2,rep,packed,name=code_ids,json=codeIds,proto3" json:"code_ids,omitempty" yaml:"code_ids"` -} - -func (m *MsgPinCodes) Reset() { *m = MsgPinCodes{} } -func (m *MsgPinCodes) String() string { return proto.CompactTextString(m) } -func (*MsgPinCodes) ProtoMessage() {} -func (*MsgPinCodes) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{20} -} - -func (m *MsgPinCodes) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgPinCodes) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgPinCodes.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *MsgPinCodes) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgPinCodes.Merge(m, src) -} - -func (m *MsgPinCodes) XXX_Size() int { - return m.Size() -} - -func (m *MsgPinCodes) XXX_DiscardUnknown() { - xxx_messageInfo_MsgPinCodes.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgPinCodes proto.InternalMessageInfo - -// MsgPinCodesResponse defines the response structure for executing a -// MsgPinCodes message. -// -// Since: 0.40 -type MsgPinCodesResponse struct{} - -func (m *MsgPinCodesResponse) Reset() { *m = MsgPinCodesResponse{} } -func (m *MsgPinCodesResponse) String() string { return proto.CompactTextString(m) } -func (*MsgPinCodesResponse) ProtoMessage() {} -func (*MsgPinCodesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{21} -} - -func (m *MsgPinCodesResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgPinCodesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgPinCodesResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *MsgPinCodesResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgPinCodesResponse.Merge(m, src) -} - -func (m *MsgPinCodesResponse) XXX_Size() int { - return m.Size() -} - -func (m *MsgPinCodesResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgPinCodesResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgPinCodesResponse proto.InternalMessageInfo - -// MsgUnpinCodes is the MsgUnpinCodes request type. -// -// Since: 0.40 -type MsgUnpinCodes struct { - // Authority is the address of the governance account. - Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` - // CodeIDs references the WASM codes - CodeIDs []uint64 `protobuf:"varint,2,rep,packed,name=code_ids,json=codeIds,proto3" json:"code_ids,omitempty" yaml:"code_ids"` -} - -func (m *MsgUnpinCodes) Reset() { *m = MsgUnpinCodes{} } -func (m *MsgUnpinCodes) String() string { return proto.CompactTextString(m) } -func (*MsgUnpinCodes) ProtoMessage() {} -func (*MsgUnpinCodes) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{22} -} - -func (m *MsgUnpinCodes) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgUnpinCodes) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgUnpinCodes.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *MsgUnpinCodes) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgUnpinCodes.Merge(m, src) -} - -func (m *MsgUnpinCodes) XXX_Size() int { - return m.Size() -} - -func (m *MsgUnpinCodes) XXX_DiscardUnknown() { - xxx_messageInfo_MsgUnpinCodes.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgUnpinCodes proto.InternalMessageInfo - -// MsgUnpinCodesResponse defines the response structure for executing a -// MsgUnpinCodes message. -// -// Since: 0.40 -type MsgUnpinCodesResponse struct{} - -func (m *MsgUnpinCodesResponse) Reset() { *m = MsgUnpinCodesResponse{} } -func (m *MsgUnpinCodesResponse) String() string { return proto.CompactTextString(m) } -func (*MsgUnpinCodesResponse) ProtoMessage() {} -func (*MsgUnpinCodesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{23} -} - -func (m *MsgUnpinCodesResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgUnpinCodesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgUnpinCodesResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *MsgUnpinCodesResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgUnpinCodesResponse.Merge(m, src) -} - -func (m *MsgUnpinCodesResponse) XXX_Size() int { - return m.Size() -} - -func (m *MsgUnpinCodesResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgUnpinCodesResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgUnpinCodesResponse proto.InternalMessageInfo - -// MsgStoreAndInstantiateContract is the MsgStoreAndInstantiateContract -// request type. -// -// Since: 0.40 -type MsgStoreAndInstantiateContract struct { - // Authority is the address of the governance account. - Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` - // WASMByteCode can be raw or gzip compressed - WASMByteCode []byte `protobuf:"bytes,3,opt,name=wasm_byte_code,json=wasmByteCode,proto3" json:"wasm_byte_code,omitempty"` - // InstantiatePermission to apply on contract creation, optional - InstantiatePermission *AccessConfig `protobuf:"bytes,4,opt,name=instantiate_permission,json=instantiatePermission,proto3" json:"instantiate_permission,omitempty"` - // UnpinCode code on upload, optional. As default the uploaded contract is - // pinned to cache. - UnpinCode bool `protobuf:"varint,5,opt,name=unpin_code,json=unpinCode,proto3" json:"unpin_code,omitempty"` - // Admin is an optional address that can execute migrations - Admin string `protobuf:"bytes,6,opt,name=admin,proto3" json:"admin,omitempty"` - // Label is optional metadata to be stored with a constract instance. - Label string `protobuf:"bytes,7,opt,name=label,proto3" json:"label,omitempty"` - // Msg json encoded message to be passed to the contract on instantiation - Msg RawContractMessage `protobuf:"bytes,8,opt,name=msg,proto3,casttype=RawContractMessage" json:"msg,omitempty"` - // Funds coins that are transferred from the authority account to the contract - // on instantiation - Funds github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,9,rep,name=funds,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"funds"` - // Source is the URL where the code is hosted - Source string `protobuf:"bytes,10,opt,name=source,proto3" json:"source,omitempty"` - // Builder is the docker image used to build the code deterministically, used - // for smart contract verification - Builder string `protobuf:"bytes,11,opt,name=builder,proto3" json:"builder,omitempty"` - // CodeHash is the SHA256 sum of the code outputted by builder, used for smart - // contract verification - CodeHash []byte `protobuf:"bytes,12,opt,name=code_hash,json=codeHash,proto3" json:"code_hash,omitempty"` -} - -func (m *MsgStoreAndInstantiateContract) Reset() { *m = MsgStoreAndInstantiateContract{} } -func (m *MsgStoreAndInstantiateContract) String() string { return proto.CompactTextString(m) } -func (*MsgStoreAndInstantiateContract) ProtoMessage() {} -func (*MsgStoreAndInstantiateContract) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{24} -} - -func (m *MsgStoreAndInstantiateContract) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgStoreAndInstantiateContract) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgStoreAndInstantiateContract.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *MsgStoreAndInstantiateContract) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgStoreAndInstantiateContract.Merge(m, src) -} - -func (m *MsgStoreAndInstantiateContract) XXX_Size() int { - return m.Size() -} - -func (m *MsgStoreAndInstantiateContract) XXX_DiscardUnknown() { - xxx_messageInfo_MsgStoreAndInstantiateContract.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgStoreAndInstantiateContract proto.InternalMessageInfo - -// MsgStoreAndInstantiateContractResponse defines the response structure -// for executing a MsgStoreAndInstantiateContract message. -// -// Since: 0.40 -type MsgStoreAndInstantiateContractResponse struct { - // Address is the bech32 address of the new contract instance. - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - // Data contains bytes to returned from the contract - Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"` -} - -func (m *MsgStoreAndInstantiateContractResponse) Reset() { - *m = MsgStoreAndInstantiateContractResponse{} -} -func (m *MsgStoreAndInstantiateContractResponse) String() string { return proto.CompactTextString(m) } -func (*MsgStoreAndInstantiateContractResponse) ProtoMessage() {} -func (*MsgStoreAndInstantiateContractResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{25} -} - -func (m *MsgStoreAndInstantiateContractResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgStoreAndInstantiateContractResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgStoreAndInstantiateContractResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *MsgStoreAndInstantiateContractResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgStoreAndInstantiateContractResponse.Merge(m, src) -} - -func (m *MsgStoreAndInstantiateContractResponse) XXX_Size() int { - return m.Size() -} - -func (m *MsgStoreAndInstantiateContractResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgStoreAndInstantiateContractResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgStoreAndInstantiateContractResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*MsgStoreCode)(nil), "cosmwasm.wasm.v1.MsgStoreCode") - proto.RegisterType((*MsgStoreCodeResponse)(nil), "cosmwasm.wasm.v1.MsgStoreCodeResponse") - proto.RegisterType((*MsgInstantiateContract)(nil), "cosmwasm.wasm.v1.MsgInstantiateContract") - proto.RegisterType((*MsgInstantiateContractResponse)(nil), "cosmwasm.wasm.v1.MsgInstantiateContractResponse") - proto.RegisterType((*MsgInstantiateContract2)(nil), "cosmwasm.wasm.v1.MsgInstantiateContract2") - proto.RegisterType((*MsgInstantiateContract2Response)(nil), "cosmwasm.wasm.v1.MsgInstantiateContract2Response") - proto.RegisterType((*MsgExecuteContract)(nil), "cosmwasm.wasm.v1.MsgExecuteContract") - proto.RegisterType((*MsgExecuteContractResponse)(nil), "cosmwasm.wasm.v1.MsgExecuteContractResponse") - proto.RegisterType((*MsgMigrateContract)(nil), "cosmwasm.wasm.v1.MsgMigrateContract") - proto.RegisterType((*MsgMigrateContractResponse)(nil), "cosmwasm.wasm.v1.MsgMigrateContractResponse") - proto.RegisterType((*MsgUpdateAdmin)(nil), "cosmwasm.wasm.v1.MsgUpdateAdmin") - proto.RegisterType((*MsgUpdateAdminResponse)(nil), "cosmwasm.wasm.v1.MsgUpdateAdminResponse") - proto.RegisterType((*MsgClearAdmin)(nil), "cosmwasm.wasm.v1.MsgClearAdmin") - proto.RegisterType((*MsgClearAdminResponse)(nil), "cosmwasm.wasm.v1.MsgClearAdminResponse") - proto.RegisterType((*MsgUpdateInstantiateConfig)(nil), "cosmwasm.wasm.v1.MsgUpdateInstantiateConfig") - proto.RegisterType((*MsgUpdateInstantiateConfigResponse)(nil), "cosmwasm.wasm.v1.MsgUpdateInstantiateConfigResponse") - proto.RegisterType((*MsgUpdateParams)(nil), "cosmwasm.wasm.v1.MsgUpdateParams") - proto.RegisterType((*MsgUpdateParamsResponse)(nil), "cosmwasm.wasm.v1.MsgUpdateParamsResponse") - proto.RegisterType((*MsgSudoContract)(nil), "cosmwasm.wasm.v1.MsgSudoContract") - proto.RegisterType((*MsgSudoContractResponse)(nil), "cosmwasm.wasm.v1.MsgSudoContractResponse") - proto.RegisterType((*MsgPinCodes)(nil), "cosmwasm.wasm.v1.MsgPinCodes") - proto.RegisterType((*MsgPinCodesResponse)(nil), "cosmwasm.wasm.v1.MsgPinCodesResponse") - proto.RegisterType((*MsgUnpinCodes)(nil), "cosmwasm.wasm.v1.MsgUnpinCodes") - proto.RegisterType((*MsgUnpinCodesResponse)(nil), "cosmwasm.wasm.v1.MsgUnpinCodesResponse") - proto.RegisterType((*MsgStoreAndInstantiateContract)(nil), "cosmwasm.wasm.v1.MsgStoreAndInstantiateContract") - proto.RegisterType((*MsgStoreAndInstantiateContractResponse)(nil), "cosmwasm.wasm.v1.MsgStoreAndInstantiateContractResponse") -} - -func init() { proto.RegisterFile("cosmwasm/wasm/v1/tx.proto", fileDescriptor_4f74d82755520264) } - -var fileDescriptor_4f74d82755520264 = []byte{ - // 1447 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe4, 0x58, 0xcf, 0x6f, 0x1b, 0xc5, - 0x17, 0xcf, 0xc6, 0xbf, 0x5f, 0xfc, 0x6d, 0xd3, 0xad, 0x9b, 0x6c, 0xb6, 0xad, 0x9d, 0x6e, 0x7f, - 0xb9, 0xfd, 0x36, 0x76, 0x63, 0xa0, 0x82, 0x70, 0x8a, 0x03, 0x12, 0x29, 0x32, 0x44, 0x1b, 0xb5, - 0x15, 0xa8, 0x92, 0xb5, 0xf6, 0x4e, 0x36, 0xab, 0xc6, 0xbb, 0x66, 0x67, 0xdd, 0x24, 0x07, 0x2e, - 0x20, 0x21, 0xc1, 0x89, 0x7f, 0x02, 0x09, 0xb8, 0xd0, 0x03, 0x48, 0x1c, 0x7b, 0xac, 0xc4, 0xa5, - 0xe2, 0xc4, 0x29, 0x40, 0x8a, 0x54, 0x6e, 0x48, 0x1c, 0x39, 0xa1, 0x99, 0xd9, 0x5d, 0x8f, 0xd7, - 0xbb, 0x8e, 0x93, 0x50, 0x71, 0xe0, 0xe2, 0xec, 0xcc, 0xfb, 0x31, 0xef, 0xf3, 0x79, 0x6f, 0x66, - 0xde, 0x04, 0xe6, 0xda, 0x36, 0xee, 0x6c, 0x6b, 0xb8, 0x53, 0xa5, 0x3f, 0x0f, 0x17, 0xab, 0xee, - 0x4e, 0xa5, 0xeb, 0xd8, 0xae, 0x2d, 0x4e, 0xfb, 0xa2, 0x0a, 0xfd, 0x79, 0xb8, 0x28, 0x17, 0xc9, - 0x8c, 0x8d, 0xab, 0x2d, 0x0d, 0xa3, 0xea, 0xc3, 0xc5, 0x16, 0x72, 0xb5, 0xc5, 0x6a, 0xdb, 0x36, - 0x2d, 0x66, 0x21, 0xcf, 0x7a, 0xf2, 0x0e, 0x36, 0x88, 0xa7, 0x0e, 0x36, 0x3c, 0x41, 0xc1, 0xb0, - 0x0d, 0x9b, 0x7e, 0x56, 0xc9, 0x97, 0x37, 0x7b, 0x6e, 0x78, 0xed, 0xdd, 0x2e, 0xc2, 0x9e, 0x74, - 0x8e, 0x39, 0x6b, 0x32, 0x33, 0x36, 0xf0, 0x44, 0xa7, 0xb4, 0x8e, 0x69, 0xd9, 0x55, 0xfa, 0xcb, - 0xa6, 0x94, 0xdf, 0x04, 0xc8, 0x37, 0xb0, 0xb1, 0xee, 0xda, 0x0e, 0x5a, 0xb1, 0x75, 0x24, 0xce, - 0x40, 0x1a, 0x23, 0x4b, 0x47, 0x8e, 0x24, 0xcc, 0x0b, 0xe5, 0x9c, 0xea, 0x8d, 0xc4, 0x5b, 0x70, - 0x82, 0xac, 0xd6, 0x6c, 0xed, 0xba, 0xa8, 0xd9, 0xb6, 0x75, 0x24, 0x4d, 0xce, 0x0b, 0xe5, 0x7c, - 0x7d, 0x7a, 0x7f, 0xaf, 0x94, 0xbf, 0xb7, 0xbc, 0xde, 0xa8, 0xef, 0xba, 0xd4, 0x83, 0x9a, 0x27, - 0x7a, 0xfe, 0x48, 0xbc, 0x03, 0x33, 0xa6, 0x85, 0x5d, 0xcd, 0x72, 0x4d, 0xcd, 0x45, 0xcd, 0x2e, - 0x72, 0x3a, 0x26, 0xc6, 0xa6, 0x6d, 0x49, 0xa9, 0x79, 0xa1, 0x3c, 0x55, 0x2b, 0x56, 0xc2, 0x74, - 0x55, 0x96, 0xdb, 0x6d, 0x84, 0xf1, 0x8a, 0x6d, 0x6d, 0x98, 0x86, 0x7a, 0x86, 0xb3, 0x5e, 0x0b, - 0x8c, 0x97, 0x2e, 0x7c, 0xf4, 0xfc, 0xd1, 0x75, 0x2f, 0xb6, 0xcf, 0x9e, 0x3f, 0xba, 0x7e, 0x8a, - 0x52, 0xc1, 0x23, 0xb9, 0x9d, 0xcc, 0x26, 0xa6, 0x93, 0xb7, 0x93, 0xd9, 0xe4, 0x74, 0x4a, 0xb9, - 0x07, 0x05, 0x5e, 0xa6, 0x22, 0xdc, 0xb5, 0x2d, 0x8c, 0xc4, 0x8b, 0x90, 0x21, 0x58, 0x9a, 0xa6, - 0x4e, 0xe1, 0x26, 0xeb, 0xb0, 0xbf, 0x57, 0x4a, 0x13, 0x95, 0xd5, 0x37, 0xd4, 0x34, 0x11, 0xad, - 0xea, 0xa2, 0x0c, 0xd9, 0xf6, 0x26, 0x6a, 0x3f, 0xc0, 0xbd, 0x0e, 0x03, 0xad, 0x06, 0x63, 0xe5, - 0xf1, 0x24, 0xcc, 0x34, 0xb0, 0xb1, 0xda, 0x0f, 0x72, 0xc5, 0xb6, 0x5c, 0x47, 0x6b, 0xbb, 0xb1, - 0x4c, 0x16, 0x20, 0xa5, 0xe9, 0x1d, 0xd3, 0xa2, 0xbe, 0x72, 0x2a, 0x1b, 0xf0, 0x91, 0x24, 0x62, - 0x23, 0x29, 0x40, 0x6a, 0x4b, 0x6b, 0xa1, 0x2d, 0x29, 0xc9, 0x4c, 0xe9, 0x40, 0x2c, 0x43, 0xa2, - 0x83, 0x0d, 0xca, 0x67, 0xbe, 0x3e, 0xf3, 0xd7, 0x5e, 0x49, 0x54, 0xb5, 0x6d, 0x3f, 0x8c, 0x06, - 0xc2, 0x58, 0x33, 0x90, 0x4a, 0x54, 0xc4, 0x0d, 0x48, 0x6d, 0xf4, 0x2c, 0x1d, 0x4b, 0xe9, 0xf9, - 0x44, 0x79, 0xaa, 0x36, 0x57, 0xf1, 0xca, 0x83, 0x14, 0x66, 0xc5, 0x2b, 0xcc, 0xca, 0x8a, 0x6d, - 0x5a, 0xf5, 0x57, 0x9e, 0xec, 0x95, 0x26, 0xbe, 0xfe, 0xb9, 0x54, 0x36, 0x4c, 0x77, 0xb3, 0xd7, - 0xaa, 0xb4, 0xed, 0x8e, 0x57, 0x4b, 0xde, 0x9f, 0x05, 0xac, 0x3f, 0xf0, 0xea, 0x8e, 0x18, 0xe0, - 0x2f, 0x9f, 0x3f, 0xba, 0x2e, 0xa8, 0xcc, 0xfd, 0xd2, 0xff, 0x43, 0xd9, 0x39, 0xeb, 0x67, 0x27, - 0x82, 0x27, 0xe5, 0x1d, 0x28, 0x46, 0x4b, 0x82, 0x2c, 0x49, 0x90, 0xd1, 0x74, 0xdd, 0x41, 0x18, - 0x7b, 0x54, 0xfa, 0x43, 0x51, 0x84, 0xa4, 0xae, 0xb9, 0x9a, 0x97, 0x16, 0xfa, 0xad, 0xfc, 0x31, - 0x09, 0xb3, 0xd1, 0x0e, 0x6b, 0xff, 0xe1, 0x9c, 0x10, 0xaa, 0xb0, 0xb6, 0xe5, 0x4a, 0x19, 0x46, - 0x15, 0xf9, 0x16, 0x67, 0x21, 0xb3, 0x61, 0xee, 0x34, 0x49, 0xa4, 0xd9, 0x79, 0xa1, 0x9c, 0x55, - 0xd3, 0x1b, 0xe6, 0x4e, 0x03, 0x1b, 0x4b, 0x37, 0x42, 0x09, 0x3c, 0x37, 0x22, 0x81, 0x35, 0xe5, - 0x5d, 0x28, 0xc5, 0x88, 0x8e, 0x98, 0xc2, 0x8f, 0x27, 0x41, 0x6c, 0x60, 0xe3, 0xcd, 0x1d, 0xd4, - 0xee, 0x8d, 0xb1, 0xa3, 0xc8, 0x06, 0xf5, 0x74, 0xbc, 0x04, 0x06, 0x63, 0x3f, 0x11, 0x89, 0x43, - 0x24, 0x22, 0xf5, 0x62, 0x37, 0xc7, 0xd5, 0x10, 0xb7, 0xb3, 0x3e, 0xb7, 0x21, 0xb8, 0xca, 0x4d, - 0x90, 0x87, 0x67, 0x03, 0x46, 0x7d, 0xde, 0x04, 0x8e, 0xb7, 0xc7, 0x02, 0xe5, 0xad, 0x61, 0x1a, - 0x8e, 0x76, 0x4c, 0xde, 0xc6, 0xaa, 0x7d, 0x8f, 0xdc, 0xe4, 0x81, 0xe4, 0xc6, 0x83, 0x0e, 0xc5, - 0xea, 0x81, 0x0e, 0xcd, 0x8e, 0x04, 0xfd, 0x89, 0x00, 0x27, 0x1a, 0xd8, 0xb8, 0xd3, 0xd5, 0x35, - 0x17, 0x2d, 0xd3, 0x8d, 0x1b, 0x07, 0xf8, 0x2c, 0xe4, 0x2c, 0xb4, 0xdd, 0xe4, 0xb7, 0x7a, 0xd6, - 0x42, 0xdb, 0xcc, 0x88, 0x67, 0x23, 0x31, 0xc8, 0xc6, 0xd2, 0xc5, 0x50, 0xf8, 0xa7, 0xfd, 0xf0, - 0xb9, 0x55, 0x15, 0x89, 0x5e, 0x05, 0xdc, 0x8c, 0x1f, 0xb6, 0x62, 0xc0, 0xff, 0x1a, 0xd8, 0x58, - 0xd9, 0x42, 0x9a, 0x33, 0x3a, 0xc0, 0x51, 0x31, 0x28, 0xa1, 0x18, 0x44, 0x3f, 0x86, 0xbe, 0x5f, - 0x65, 0x16, 0xce, 0x0c, 0x4c, 0x04, 0x11, 0xfc, 0x2e, 0x50, 0x5e, 0x59, 0x70, 0x83, 0x3b, 0x75, - 0xc3, 0x34, 0x62, 0xe3, 0xe1, 0xaa, 0x60, 0x32, 0xb6, 0x0a, 0xee, 0x83, 0x4c, 0x58, 0x8d, 0xb9, - 0xe6, 0x13, 0x63, 0x5d, 0xf3, 0x92, 0x85, 0xb6, 0x57, 0x23, 0x6f, 0xfa, 0x6a, 0x08, 0x76, 0x69, - 0x90, 0xfa, 0x21, 0x2c, 0xca, 0x25, 0x50, 0xe2, 0xa5, 0x01, 0x21, 0xdf, 0x08, 0x70, 0x32, 0x50, - 0x5b, 0xd3, 0x1c, 0xad, 0x83, 0xc5, 0x5b, 0x90, 0xd3, 0x7a, 0xee, 0xa6, 0xed, 0x98, 0xee, 0x2e, - 0x23, 0xa2, 0x2e, 0xfd, 0xf8, 0xed, 0x42, 0xc1, 0x3b, 0x08, 0x96, 0xd9, 0x89, 0xb5, 0xee, 0x3a, - 0xa6, 0x65, 0xa8, 0x7d, 0x55, 0xf1, 0x75, 0x48, 0x77, 0xa9, 0x07, 0x4a, 0xd2, 0x54, 0x4d, 0x1a, - 0x06, 0xcb, 0x56, 0xa8, 0xe7, 0xc8, 0xc9, 0xc1, 0x4e, 0x03, 0xcf, 0x84, 0xed, 0x8c, 0xbe, 0x33, - 0x02, 0xb1, 0x30, 0x08, 0x91, 0xd9, 0x2a, 0x73, 0xf4, 0x5a, 0xe3, 0xa7, 0x02, 0x30, 0xdf, 0x33, - 0x30, 0xeb, 0x3d, 0xdd, 0x0e, 0x36, 0xfd, 0x51, 0xc1, 0xfc, 0x23, 0x87, 0xe9, 0x48, 0x54, 0x7c, - 0x98, 0xca, 0x02, 0x45, 0xc5, 0x4f, 0x8d, 0xdc, 0xec, 0x5f, 0x08, 0x30, 0xd5, 0xc0, 0xc6, 0x9a, - 0x69, 0x91, 0x22, 0x3c, 0x7a, 0xca, 0x5e, 0x23, 0x28, 0x69, 0x61, 0x93, 0xa4, 0x25, 0xca, 0xc9, - 0x7a, 0x71, 0x7f, 0xaf, 0x94, 0x61, 0x95, 0x8d, 0xff, 0xdc, 0x2b, 0x9d, 0xdc, 0xd5, 0x3a, 0x5b, - 0x4b, 0x8a, 0xaf, 0xa4, 0xa8, 0x19, 0x56, 0xed, 0x98, 0x9d, 0x05, 0x83, 0xd0, 0xa6, 0x7d, 0x68, - 0x7e, 0x5c, 0xca, 0x19, 0x38, 0xcd, 0x0d, 0x83, 0x44, 0x7d, 0x25, 0xd0, 0x93, 0xe0, 0x8e, 0xd5, - 0xfd, 0x17, 0x01, 0x5c, 0x1e, 0x06, 0x10, 0x9c, 0x25, 0xfd, 0xc8, 0xbc, 0xb3, 0xa4, 0x3f, 0x11, - 0x80, 0xf8, 0x21, 0x49, 0x3b, 0x36, 0xda, 0x4d, 0x2f, 0x5b, 0x7a, 0x54, 0xef, 0x7b, 0x54, 0x54, - 0xc3, 0xaf, 0x8c, 0xc4, 0x31, 0x5f, 0x19, 0xc9, 0x63, 0xbc, 0x32, 0xc4, 0xf3, 0x00, 0x3d, 0x82, - 0x9f, 0x85, 0x92, 0xa2, 0x2d, 0x52, 0xae, 0xe7, 0x33, 0xd2, 0xef, 0x1a, 0xd3, 0x7c, 0xd7, 0x18, - 0x34, 0x84, 0x99, 0x88, 0x86, 0x30, 0x7b, 0x88, 0x3e, 0x24, 0xf7, 0x62, 0x1b, 0x42, 0x72, 0xe6, - 0xdb, 0x3d, 0xa7, 0x8d, 0x24, 0xf0, 0xce, 0x7c, 0x3a, 0x22, 0xad, 0x5a, 0xab, 0x67, 0x6e, 0x91, - 0xcb, 0x60, 0x8a, 0xb5, 0x6a, 0xde, 0x90, 0x5c, 0x9f, 0xb4, 0x9c, 0x36, 0x35, 0xbc, 0x29, 0xe5, - 0xbd, 0x97, 0x90, 0xad, 0xa3, 0xb7, 0x34, 0xbc, 0xb9, 0x74, 0x6b, 0xb8, 0xaa, 0x2e, 0x0e, 0x3c, - 0xca, 0xa2, 0x4b, 0x45, 0xb9, 0x0b, 0x57, 0x46, 0x6b, 0x1c, 0xad, 0x87, 0xac, 0x7d, 0x07, 0x90, - 0x68, 0x60, 0x43, 0x5c, 0x87, 0x5c, 0xff, 0x75, 0x1b, 0x51, 0x07, 0xfc, 0xbb, 0x50, 0xbe, 0x32, - 0x5a, 0x1e, 0x84, 0xf2, 0x01, 0x9c, 0x8e, 0x2a, 0xfb, 0x72, 0xa4, 0x79, 0x84, 0xa6, 0x7c, 0x73, - 0x5c, 0xcd, 0x60, 0x49, 0x17, 0x0a, 0x91, 0x4f, 0x9a, 0x6b, 0xe3, 0x7a, 0xaa, 0xc9, 0x8b, 0x63, - 0xab, 0x06, 0xab, 0x22, 0x38, 0x19, 0xee, 0xc2, 0x2f, 0x45, 0x7a, 0x09, 0x69, 0xc9, 0x37, 0xc6, - 0xd1, 0xe2, 0x97, 0x09, 0x37, 0xad, 0xd1, 0xcb, 0x84, 0xb4, 0x62, 0x96, 0x89, 0x6b, 0x1f, 0xdf, - 0x83, 0x29, 0xbe, 0x4d, 0x9c, 0x8f, 0x34, 0xe6, 0x34, 0xe4, 0xf2, 0x41, 0x1a, 0x81, 0xeb, 0xbb, - 0x00, 0x5c, 0x7f, 0x57, 0x8a, 0xb4, 0xeb, 0x2b, 0xc8, 0x57, 0x0f, 0x50, 0x08, 0xfc, 0x7e, 0x08, - 0xb3, 0x71, 0x4d, 0xdb, 0x8d, 0x11, 0xc1, 0x0d, 0x69, 0xcb, 0x2f, 0x1f, 0x46, 0x3b, 0x58, 0xfe, - 0x3e, 0xe4, 0x07, 0x5a, 0xa4, 0x0b, 0x23, 0xbc, 0x30, 0x15, 0xf9, 0xda, 0x81, 0x2a, 0xbc, 0xf7, - 0x81, 0x9e, 0x25, 0xda, 0x3b, 0xaf, 0x12, 0xe3, 0x3d, 0xb2, 0x7f, 0x58, 0x83, 0x6c, 0xd0, 0x27, - 0x9c, 0x8f, 0x34, 0xf3, 0xc5, 0xf2, 0xe5, 0x91, 0x62, 0x3e, 0xc9, 0xdc, 0xd5, 0x1d, 0x9d, 0xe4, - 0xbe, 0x42, 0x4c, 0x92, 0x87, 0x6f, 0x54, 0xf1, 0x53, 0x01, 0xce, 0x8e, 0xba, 0x4e, 0x6f, 0xc6, - 0x1f, 0x4b, 0xd1, 0x16, 0xf2, 0xab, 0x87, 0xb5, 0xf0, 0x63, 0xa9, 0xbf, 0xfd, 0xe4, 0xd7, 0xe2, - 0xc4, 0x93, 0xfd, 0xa2, 0xf0, 0x74, 0xbf, 0x28, 0xfc, 0xb2, 0x5f, 0x14, 0x3e, 0x7f, 0x56, 0x9c, - 0x78, 0xfa, 0xac, 0x38, 0xf1, 0xd3, 0xb3, 0xe2, 0xc4, 0xfb, 0x0b, 0xdc, 0x55, 0xe3, 0x22, 0xa7, - 0x6b, 0x21, 0x77, 0xdb, 0x76, 0x1e, 0xd0, 0xef, 0x85, 0xb6, 0xed, 0xa0, 0xea, 0x0e, 0xfb, 0xaf, - 0x24, 0xbd, 0x75, 0x5a, 0x69, 0xfa, 0x5f, 0xc6, 0x97, 0xfe, 0x0e, 0x00, 0x00, 0xff, 0xff, 0x9a, - 0xd3, 0x93, 0x78, 0x2f, 0x15, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ context.Context - _ grpc.ClientConn -) - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - // StoreCode to submit Wasm code to the system - StoreCode(ctx context.Context, in *MsgStoreCode, opts ...grpc.CallOption) (*MsgStoreCodeResponse, error) - // InstantiateContract creates a new smart contract instance for the given - // code id. - InstantiateContract(ctx context.Context, in *MsgInstantiateContract, opts ...grpc.CallOption) (*MsgInstantiateContractResponse, error) - // InstantiateContract2 creates a new smart contract instance for the given - // code id with a predictable address - InstantiateContract2(ctx context.Context, in *MsgInstantiateContract2, opts ...grpc.CallOption) (*MsgInstantiateContract2Response, error) - // Execute submits the given message data to a smart contract - ExecuteContract(ctx context.Context, in *MsgExecuteContract, opts ...grpc.CallOption) (*MsgExecuteContractResponse, error) - // Migrate runs a code upgrade/ downgrade for a smart contract - MigrateContract(ctx context.Context, in *MsgMigrateContract, opts ...grpc.CallOption) (*MsgMigrateContractResponse, error) - // UpdateAdmin sets a new admin for a smart contract - UpdateAdmin(ctx context.Context, in *MsgUpdateAdmin, opts ...grpc.CallOption) (*MsgUpdateAdminResponse, error) - // ClearAdmin removes any admin stored for a smart contract - ClearAdmin(ctx context.Context, in *MsgClearAdmin, opts ...grpc.CallOption) (*MsgClearAdminResponse, error) - // UpdateInstantiateConfig updates instantiate config for a smart contract - UpdateInstantiateConfig(ctx context.Context, in *MsgUpdateInstantiateConfig, opts ...grpc.CallOption) (*MsgUpdateInstantiateConfigResponse, error) - // UpdateParams defines a governance operation for updating the x/wasm - // module parameters. The authority is defined in the keeper. - // - // Since: 0.40 - UpdateParams(ctx context.Context, in *MsgUpdateParams, opts ...grpc.CallOption) (*MsgUpdateParamsResponse, error) - // SudoContract defines a governance operation for calling sudo - // on a contract. The authority is defined in the keeper. - // - // Since: 0.40 - SudoContract(ctx context.Context, in *MsgSudoContract, opts ...grpc.CallOption) (*MsgSudoContractResponse, error) - // PinCodes defines a governance operation for pinning a set of - // code ids in the wasmvm cache. The authority is defined in the keeper. - // - // Since: 0.40 - PinCodes(ctx context.Context, in *MsgPinCodes, opts ...grpc.CallOption) (*MsgPinCodesResponse, error) - // UnpinCodes defines a governance operation for unpinning a set of - // code ids in the wasmvm cache. The authority is defined in the keeper. - // - // Since: 0.40 - UnpinCodes(ctx context.Context, in *MsgUnpinCodes, opts ...grpc.CallOption) (*MsgUnpinCodesResponse, error) - // StoreAndInstantiateContract defines a governance operation for storing - // and instantiating the contract. The authority is defined in the keeper. - // - // Since: 0.40 - StoreAndInstantiateContract(ctx context.Context, in *MsgStoreAndInstantiateContract, opts ...grpc.CallOption) (*MsgStoreAndInstantiateContractResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) StoreCode(ctx context.Context, in *MsgStoreCode, opts ...grpc.CallOption) (*MsgStoreCodeResponse, error) { - out := new(MsgStoreCodeResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Msg/StoreCode", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) InstantiateContract(ctx context.Context, in *MsgInstantiateContract, opts ...grpc.CallOption) (*MsgInstantiateContractResponse, error) { - out := new(MsgInstantiateContractResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Msg/InstantiateContract", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) InstantiateContract2(ctx context.Context, in *MsgInstantiateContract2, opts ...grpc.CallOption) (*MsgInstantiateContract2Response, error) { - out := new(MsgInstantiateContract2Response) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Msg/InstantiateContract2", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) ExecuteContract(ctx context.Context, in *MsgExecuteContract, opts ...grpc.CallOption) (*MsgExecuteContractResponse, error) { - out := new(MsgExecuteContractResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Msg/ExecuteContract", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) MigrateContract(ctx context.Context, in *MsgMigrateContract, opts ...grpc.CallOption) (*MsgMigrateContractResponse, error) { - out := new(MsgMigrateContractResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Msg/MigrateContract", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) UpdateAdmin(ctx context.Context, in *MsgUpdateAdmin, opts ...grpc.CallOption) (*MsgUpdateAdminResponse, error) { - out := new(MsgUpdateAdminResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Msg/UpdateAdmin", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) ClearAdmin(ctx context.Context, in *MsgClearAdmin, opts ...grpc.CallOption) (*MsgClearAdminResponse, error) { - out := new(MsgClearAdminResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Msg/ClearAdmin", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) UpdateInstantiateConfig(ctx context.Context, in *MsgUpdateInstantiateConfig, opts ...grpc.CallOption) (*MsgUpdateInstantiateConfigResponse, error) { - out := new(MsgUpdateInstantiateConfigResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Msg/UpdateInstantiateConfig", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) UpdateParams(ctx context.Context, in *MsgUpdateParams, opts ...grpc.CallOption) (*MsgUpdateParamsResponse, error) { - out := new(MsgUpdateParamsResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Msg/UpdateParams", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) SudoContract(ctx context.Context, in *MsgSudoContract, opts ...grpc.CallOption) (*MsgSudoContractResponse, error) { - out := new(MsgSudoContractResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Msg/SudoContract", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) PinCodes(ctx context.Context, in *MsgPinCodes, opts ...grpc.CallOption) (*MsgPinCodesResponse, error) { - out := new(MsgPinCodesResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Msg/PinCodes", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) UnpinCodes(ctx context.Context, in *MsgUnpinCodes, opts ...grpc.CallOption) (*MsgUnpinCodesResponse, error) { - out := new(MsgUnpinCodesResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Msg/UnpinCodes", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) StoreAndInstantiateContract(ctx context.Context, in *MsgStoreAndInstantiateContract, opts ...grpc.CallOption) (*MsgStoreAndInstantiateContractResponse, error) { - out := new(MsgStoreAndInstantiateContractResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Msg/StoreAndInstantiateContract", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - // StoreCode to submit Wasm code to the system - StoreCode(context.Context, *MsgStoreCode) (*MsgStoreCodeResponse, error) - // InstantiateContract creates a new smart contract instance for the given - // code id. - InstantiateContract(context.Context, *MsgInstantiateContract) (*MsgInstantiateContractResponse, error) - // InstantiateContract2 creates a new smart contract instance for the given - // code id with a predictable address - InstantiateContract2(context.Context, *MsgInstantiateContract2) (*MsgInstantiateContract2Response, error) - // Execute submits the given message data to a smart contract - ExecuteContract(context.Context, *MsgExecuteContract) (*MsgExecuteContractResponse, error) - // Migrate runs a code upgrade/ downgrade for a smart contract - MigrateContract(context.Context, *MsgMigrateContract) (*MsgMigrateContractResponse, error) - // UpdateAdmin sets a new admin for a smart contract - UpdateAdmin(context.Context, *MsgUpdateAdmin) (*MsgUpdateAdminResponse, error) - // ClearAdmin removes any admin stored for a smart contract - ClearAdmin(context.Context, *MsgClearAdmin) (*MsgClearAdminResponse, error) - // UpdateInstantiateConfig updates instantiate config for a smart contract - UpdateInstantiateConfig(context.Context, *MsgUpdateInstantiateConfig) (*MsgUpdateInstantiateConfigResponse, error) - // UpdateParams defines a governance operation for updating the x/wasm - // module parameters. The authority is defined in the keeper. - // - // Since: 0.40 - UpdateParams(context.Context, *MsgUpdateParams) (*MsgUpdateParamsResponse, error) - // SudoContract defines a governance operation for calling sudo - // on a contract. The authority is defined in the keeper. - // - // Since: 0.40 - SudoContract(context.Context, *MsgSudoContract) (*MsgSudoContractResponse, error) - // PinCodes defines a governance operation for pinning a set of - // code ids in the wasmvm cache. The authority is defined in the keeper. - // - // Since: 0.40 - PinCodes(context.Context, *MsgPinCodes) (*MsgPinCodesResponse, error) - // UnpinCodes defines a governance operation for unpinning a set of - // code ids in the wasmvm cache. The authority is defined in the keeper. - // - // Since: 0.40 - UnpinCodes(context.Context, *MsgUnpinCodes) (*MsgUnpinCodesResponse, error) - // StoreAndInstantiateContract defines a governance operation for storing - // and instantiating the contract. The authority is defined in the keeper. - // - // Since: 0.40 - StoreAndInstantiateContract(context.Context, *MsgStoreAndInstantiateContract) (*MsgStoreAndInstantiateContractResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct{} - -func (*UnimplementedMsgServer) StoreCode(ctx context.Context, req *MsgStoreCode) (*MsgStoreCodeResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method StoreCode not implemented") -} - -func (*UnimplementedMsgServer) InstantiateContract(ctx context.Context, req *MsgInstantiateContract) (*MsgInstantiateContractResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method InstantiateContract not implemented") -} - -func (*UnimplementedMsgServer) InstantiateContract2(ctx context.Context, req *MsgInstantiateContract2) (*MsgInstantiateContract2Response, error) { - return nil, status.Errorf(codes.Unimplemented, "method InstantiateContract2 not implemented") -} - -func (*UnimplementedMsgServer) ExecuteContract(ctx context.Context, req *MsgExecuteContract) (*MsgExecuteContractResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ExecuteContract not implemented") -} - -func (*UnimplementedMsgServer) MigrateContract(ctx context.Context, req *MsgMigrateContract) (*MsgMigrateContractResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method MigrateContract not implemented") -} - -func (*UnimplementedMsgServer) UpdateAdmin(ctx context.Context, req *MsgUpdateAdmin) (*MsgUpdateAdminResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method UpdateAdmin not implemented") -} - -func (*UnimplementedMsgServer) ClearAdmin(ctx context.Context, req *MsgClearAdmin) (*MsgClearAdminResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ClearAdmin not implemented") -} - -func (*UnimplementedMsgServer) UpdateInstantiateConfig(ctx context.Context, req *MsgUpdateInstantiateConfig) (*MsgUpdateInstantiateConfigResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method UpdateInstantiateConfig not implemented") -} - -func (*UnimplementedMsgServer) UpdateParams(ctx context.Context, req *MsgUpdateParams) (*MsgUpdateParamsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method UpdateParams not implemented") -} - -func (*UnimplementedMsgServer) SudoContract(ctx context.Context, req *MsgSudoContract) (*MsgSudoContractResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method SudoContract not implemented") -} - -func (*UnimplementedMsgServer) PinCodes(ctx context.Context, req *MsgPinCodes) (*MsgPinCodesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method PinCodes not implemented") -} - -func (*UnimplementedMsgServer) UnpinCodes(ctx context.Context, req *MsgUnpinCodes) (*MsgUnpinCodesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method UnpinCodes not implemented") -} - -func (*UnimplementedMsgServer) StoreAndInstantiateContract(ctx context.Context, req *MsgStoreAndInstantiateContract) (*MsgStoreAndInstantiateContractResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method StoreAndInstantiateContract not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_StoreCode_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgStoreCode) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).StoreCode(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Msg/StoreCode", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).StoreCode(ctx, req.(*MsgStoreCode)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_InstantiateContract_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgInstantiateContract) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).InstantiateContract(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Msg/InstantiateContract", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).InstantiateContract(ctx, req.(*MsgInstantiateContract)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_InstantiateContract2_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgInstantiateContract2) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).InstantiateContract2(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Msg/InstantiateContract2", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).InstantiateContract2(ctx, req.(*MsgInstantiateContract2)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_ExecuteContract_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgExecuteContract) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).ExecuteContract(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Msg/ExecuteContract", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).ExecuteContract(ctx, req.(*MsgExecuteContract)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_MigrateContract_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgMigrateContract) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).MigrateContract(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Msg/MigrateContract", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).MigrateContract(ctx, req.(*MsgMigrateContract)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_UpdateAdmin_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgUpdateAdmin) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).UpdateAdmin(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Msg/UpdateAdmin", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).UpdateAdmin(ctx, req.(*MsgUpdateAdmin)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_ClearAdmin_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgClearAdmin) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).ClearAdmin(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Msg/ClearAdmin", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).ClearAdmin(ctx, req.(*MsgClearAdmin)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_UpdateInstantiateConfig_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgUpdateInstantiateConfig) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).UpdateInstantiateConfig(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Msg/UpdateInstantiateConfig", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).UpdateInstantiateConfig(ctx, req.(*MsgUpdateInstantiateConfig)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_UpdateParams_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgUpdateParams) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).UpdateParams(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Msg/UpdateParams", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).UpdateParams(ctx, req.(*MsgUpdateParams)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_SudoContract_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgSudoContract) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).SudoContract(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Msg/SudoContract", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).SudoContract(ctx, req.(*MsgSudoContract)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_PinCodes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgPinCodes) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).PinCodes(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Msg/PinCodes", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).PinCodes(ctx, req.(*MsgPinCodes)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_UnpinCodes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgUnpinCodes) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).UnpinCodes(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Msg/UnpinCodes", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).UnpinCodes(ctx, req.(*MsgUnpinCodes)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_StoreAndInstantiateContract_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgStoreAndInstantiateContract) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).StoreAndInstantiateContract(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Msg/StoreAndInstantiateContract", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).StoreAndInstantiateContract(ctx, req.(*MsgStoreAndInstantiateContract)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "cosmwasm.wasm.v1.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "StoreCode", - Handler: _Msg_StoreCode_Handler, - }, - { - MethodName: "InstantiateContract", - Handler: _Msg_InstantiateContract_Handler, - }, - { - MethodName: "InstantiateContract2", - Handler: _Msg_InstantiateContract2_Handler, - }, - { - MethodName: "ExecuteContract", - Handler: _Msg_ExecuteContract_Handler, - }, - { - MethodName: "MigrateContract", - Handler: _Msg_MigrateContract_Handler, - }, - { - MethodName: "UpdateAdmin", - Handler: _Msg_UpdateAdmin_Handler, - }, - { - MethodName: "ClearAdmin", - Handler: _Msg_ClearAdmin_Handler, - }, - { - MethodName: "UpdateInstantiateConfig", - Handler: _Msg_UpdateInstantiateConfig_Handler, - }, - { - MethodName: "UpdateParams", - Handler: _Msg_UpdateParams_Handler, - }, - { - MethodName: "SudoContract", - Handler: _Msg_SudoContract_Handler, - }, - { - MethodName: "PinCodes", - Handler: _Msg_PinCodes_Handler, - }, - { - MethodName: "UnpinCodes", - Handler: _Msg_UnpinCodes_Handler, - }, - { - MethodName: "StoreAndInstantiateContract", - Handler: _Msg_StoreAndInstantiateContract_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "cosmwasm/wasm/v1/tx.proto", -} - -func (m *MsgStoreCode) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgStoreCode) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgStoreCode) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.InstantiatePermission != nil { - { - size, err := m.InstantiatePermission.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - } - if len(m.WASMByteCode) > 0 { - i -= len(m.WASMByteCode) - copy(dAtA[i:], m.WASMByteCode) - i = encodeVarintTx(dAtA, i, uint64(len(m.WASMByteCode))) - i-- - dAtA[i] = 0x12 - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgStoreCodeResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgStoreCodeResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgStoreCodeResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Checksum) > 0 { - i -= len(m.Checksum) - copy(dAtA[i:], m.Checksum) - i = encodeVarintTx(dAtA, i, uint64(len(m.Checksum))) - i-- - dAtA[i] = 0x12 - } - if m.CodeID != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.CodeID)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *MsgInstantiateContract) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgInstantiateContract) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgInstantiateContract) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Funds) > 0 { - for iNdEx := len(m.Funds) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Funds[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - } - } - if len(m.Msg) > 0 { - i -= len(m.Msg) - copy(dAtA[i:], m.Msg) - i = encodeVarintTx(dAtA, i, uint64(len(m.Msg))) - i-- - dAtA[i] = 0x2a - } - if len(m.Label) > 0 { - i -= len(m.Label) - copy(dAtA[i:], m.Label) - i = encodeVarintTx(dAtA, i, uint64(len(m.Label))) - i-- - dAtA[i] = 0x22 - } - if m.CodeID != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.CodeID)) - i-- - dAtA[i] = 0x18 - } - if len(m.Admin) > 0 { - i -= len(m.Admin) - copy(dAtA[i:], m.Admin) - i = encodeVarintTx(dAtA, i, uint64(len(m.Admin))) - i-- - dAtA[i] = 0x12 - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgInstantiateContractResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgInstantiateContractResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgInstantiateContractResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Data) > 0 { - i -= len(m.Data) - copy(dAtA[i:], m.Data) - i = encodeVarintTx(dAtA, i, uint64(len(m.Data))) - i-- - dAtA[i] = 0x12 - } - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintTx(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgInstantiateContract2) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgInstantiateContract2) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgInstantiateContract2) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.FixMsg { - i-- - if m.FixMsg { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x40 - } - if len(m.Salt) > 0 { - i -= len(m.Salt) - copy(dAtA[i:], m.Salt) - i = encodeVarintTx(dAtA, i, uint64(len(m.Salt))) - i-- - dAtA[i] = 0x3a - } - if len(m.Funds) > 0 { - for iNdEx := len(m.Funds) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Funds[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - } - } - if len(m.Msg) > 0 { - i -= len(m.Msg) - copy(dAtA[i:], m.Msg) - i = encodeVarintTx(dAtA, i, uint64(len(m.Msg))) - i-- - dAtA[i] = 0x2a - } - if len(m.Label) > 0 { - i -= len(m.Label) - copy(dAtA[i:], m.Label) - i = encodeVarintTx(dAtA, i, uint64(len(m.Label))) - i-- - dAtA[i] = 0x22 - } - if m.CodeID != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.CodeID)) - i-- - dAtA[i] = 0x18 - } - if len(m.Admin) > 0 { - i -= len(m.Admin) - copy(dAtA[i:], m.Admin) - i = encodeVarintTx(dAtA, i, uint64(len(m.Admin))) - i-- - dAtA[i] = 0x12 - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgInstantiateContract2Response) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgInstantiateContract2Response) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgInstantiateContract2Response) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Data) > 0 { - i -= len(m.Data) - copy(dAtA[i:], m.Data) - i = encodeVarintTx(dAtA, i, uint64(len(m.Data))) - i-- - dAtA[i] = 0x12 - } - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintTx(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgExecuteContract) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgExecuteContract) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgExecuteContract) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Funds) > 0 { - for iNdEx := len(m.Funds) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Funds[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - } - } - if len(m.Msg) > 0 { - i -= len(m.Msg) - copy(dAtA[i:], m.Msg) - i = encodeVarintTx(dAtA, i, uint64(len(m.Msg))) - i-- - dAtA[i] = 0x1a - } - if len(m.Contract) > 0 { - i -= len(m.Contract) - copy(dAtA[i:], m.Contract) - i = encodeVarintTx(dAtA, i, uint64(len(m.Contract))) - i-- - dAtA[i] = 0x12 - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgExecuteContractResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgExecuteContractResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgExecuteContractResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Data) > 0 { - i -= len(m.Data) - copy(dAtA[i:], m.Data) - i = encodeVarintTx(dAtA, i, uint64(len(m.Data))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgMigrateContract) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgMigrateContract) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgMigrateContract) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Msg) > 0 { - i -= len(m.Msg) - copy(dAtA[i:], m.Msg) - i = encodeVarintTx(dAtA, i, uint64(len(m.Msg))) - i-- - dAtA[i] = 0x22 - } - if m.CodeID != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.CodeID)) - i-- - dAtA[i] = 0x18 - } - if len(m.Contract) > 0 { - i -= len(m.Contract) - copy(dAtA[i:], m.Contract) - i = encodeVarintTx(dAtA, i, uint64(len(m.Contract))) - i-- - dAtA[i] = 0x12 - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgMigrateContractResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgMigrateContractResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgMigrateContractResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Data) > 0 { - i -= len(m.Data) - copy(dAtA[i:], m.Data) - i = encodeVarintTx(dAtA, i, uint64(len(m.Data))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgUpdateAdmin) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgUpdateAdmin) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgUpdateAdmin) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Contract) > 0 { - i -= len(m.Contract) - copy(dAtA[i:], m.Contract) - i = encodeVarintTx(dAtA, i, uint64(len(m.Contract))) - i-- - dAtA[i] = 0x1a - } - if len(m.NewAdmin) > 0 { - i -= len(m.NewAdmin) - copy(dAtA[i:], m.NewAdmin) - i = encodeVarintTx(dAtA, i, uint64(len(m.NewAdmin))) - i-- - dAtA[i] = 0x12 - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgUpdateAdminResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgUpdateAdminResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgUpdateAdminResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgClearAdmin) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgClearAdmin) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgClearAdmin) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Contract) > 0 { - i -= len(m.Contract) - copy(dAtA[i:], m.Contract) - i = encodeVarintTx(dAtA, i, uint64(len(m.Contract))) - i-- - dAtA[i] = 0x1a - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgClearAdminResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgClearAdminResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgClearAdminResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgUpdateInstantiateConfig) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgUpdateInstantiateConfig) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgUpdateInstantiateConfig) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.NewInstantiatePermission != nil { - { - size, err := m.NewInstantiatePermission.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - if m.CodeID != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.CodeID)) - i-- - dAtA[i] = 0x10 - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgUpdateInstantiateConfigResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgUpdateInstantiateConfigResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgUpdateInstantiateConfigResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgUpdateParams) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgUpdateParams) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgUpdateParams) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Authority) > 0 { - i -= len(m.Authority) - copy(dAtA[i:], m.Authority) - i = encodeVarintTx(dAtA, i, uint64(len(m.Authority))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgUpdateParamsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgUpdateParamsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgUpdateParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgSudoContract) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgSudoContract) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgSudoContract) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Msg) > 0 { - i -= len(m.Msg) - copy(dAtA[i:], m.Msg) - i = encodeVarintTx(dAtA, i, uint64(len(m.Msg))) - i-- - dAtA[i] = 0x1a - } - if len(m.Contract) > 0 { - i -= len(m.Contract) - copy(dAtA[i:], m.Contract) - i = encodeVarintTx(dAtA, i, uint64(len(m.Contract))) - i-- - dAtA[i] = 0x12 - } - if len(m.Authority) > 0 { - i -= len(m.Authority) - copy(dAtA[i:], m.Authority) - i = encodeVarintTx(dAtA, i, uint64(len(m.Authority))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgSudoContractResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgSudoContractResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgSudoContractResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Data) > 0 { - i -= len(m.Data) - copy(dAtA[i:], m.Data) - i = encodeVarintTx(dAtA, i, uint64(len(m.Data))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgPinCodes) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgPinCodes) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgPinCodes) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.CodeIDs) > 0 { - dAtA5 := make([]byte, len(m.CodeIDs)*10) - var j4 int - for _, num := range m.CodeIDs { - for num >= 1<<7 { - dAtA5[j4] = uint8(uint64(num)&0x7f | 0x80) - num >>= 7 - j4++ - } - dAtA5[j4] = uint8(num) - j4++ - } - i -= j4 - copy(dAtA[i:], dAtA5[:j4]) - i = encodeVarintTx(dAtA, i, uint64(j4)) - i-- - dAtA[i] = 0x12 - } - if len(m.Authority) > 0 { - i -= len(m.Authority) - copy(dAtA[i:], m.Authority) - i = encodeVarintTx(dAtA, i, uint64(len(m.Authority))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgPinCodesResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgPinCodesResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgPinCodesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgUnpinCodes) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgUnpinCodes) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgUnpinCodes) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.CodeIDs) > 0 { - dAtA7 := make([]byte, len(m.CodeIDs)*10) - var j6 int - for _, num := range m.CodeIDs { - for num >= 1<<7 { - dAtA7[j6] = uint8(uint64(num)&0x7f | 0x80) - num >>= 7 - j6++ - } - dAtA7[j6] = uint8(num) - j6++ - } - i -= j6 - copy(dAtA[i:], dAtA7[:j6]) - i = encodeVarintTx(dAtA, i, uint64(j6)) - i-- - dAtA[i] = 0x12 - } - if len(m.Authority) > 0 { - i -= len(m.Authority) - copy(dAtA[i:], m.Authority) - i = encodeVarintTx(dAtA, i, uint64(len(m.Authority))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgUnpinCodesResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgUnpinCodesResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgUnpinCodesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgStoreAndInstantiateContract) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgStoreAndInstantiateContract) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgStoreAndInstantiateContract) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.CodeHash) > 0 { - i -= len(m.CodeHash) - copy(dAtA[i:], m.CodeHash) - i = encodeVarintTx(dAtA, i, uint64(len(m.CodeHash))) - i-- - dAtA[i] = 0x62 - } - if len(m.Builder) > 0 { - i -= len(m.Builder) - copy(dAtA[i:], m.Builder) - i = encodeVarintTx(dAtA, i, uint64(len(m.Builder))) - i-- - dAtA[i] = 0x5a - } - if len(m.Source) > 0 { - i -= len(m.Source) - copy(dAtA[i:], m.Source) - i = encodeVarintTx(dAtA, i, uint64(len(m.Source))) - i-- - dAtA[i] = 0x52 - } - if len(m.Funds) > 0 { - for iNdEx := len(m.Funds) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Funds[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x4a - } - } - if len(m.Msg) > 0 { - i -= len(m.Msg) - copy(dAtA[i:], m.Msg) - i = encodeVarintTx(dAtA, i, uint64(len(m.Msg))) - i-- - dAtA[i] = 0x42 - } - if len(m.Label) > 0 { - i -= len(m.Label) - copy(dAtA[i:], m.Label) - i = encodeVarintTx(dAtA, i, uint64(len(m.Label))) - i-- - dAtA[i] = 0x3a - } - if len(m.Admin) > 0 { - i -= len(m.Admin) - copy(dAtA[i:], m.Admin) - i = encodeVarintTx(dAtA, i, uint64(len(m.Admin))) - i-- - dAtA[i] = 0x32 - } - if m.UnpinCode { - i-- - if m.UnpinCode { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x28 - } - if m.InstantiatePermission != nil { - { - size, err := m.InstantiatePermission.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - if len(m.WASMByteCode) > 0 { - i -= len(m.WASMByteCode) - copy(dAtA[i:], m.WASMByteCode) - i = encodeVarintTx(dAtA, i, uint64(len(m.WASMByteCode))) - i-- - dAtA[i] = 0x1a - } - if len(m.Authority) > 0 { - i -= len(m.Authority) - copy(dAtA[i:], m.Authority) - i = encodeVarintTx(dAtA, i, uint64(len(m.Authority))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgStoreAndInstantiateContractResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgStoreAndInstantiateContractResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgStoreAndInstantiateContractResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Data) > 0 { - i -= len(m.Data) - copy(dAtA[i:], m.Data) - i = encodeVarintTx(dAtA, i, uint64(len(m.Data))) - i-- - dAtA[i] = 0x12 - } - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintTx(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintTx(dAtA []byte, offset int, v uint64) int { - offset -= sovTx(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} - -func (m *MsgStoreCode) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.WASMByteCode) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if m.InstantiatePermission != nil { - l = m.InstantiatePermission.Size() - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgStoreCodeResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.CodeID != 0 { - n += 1 + sovTx(uint64(m.CodeID)) - } - l = len(m.Checksum) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgInstantiateContract) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Admin) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if m.CodeID != 0 { - n += 1 + sovTx(uint64(m.CodeID)) - } - l = len(m.Label) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Msg) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.Funds) > 0 { - for _, e := range m.Funds { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgInstantiateContractResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Data) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgInstantiateContract2) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Admin) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if m.CodeID != 0 { - n += 1 + sovTx(uint64(m.CodeID)) - } - l = len(m.Label) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Msg) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.Funds) > 0 { - for _, e := range m.Funds { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - l = len(m.Salt) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if m.FixMsg { - n += 2 - } - return n -} - -func (m *MsgInstantiateContract2Response) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Data) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgExecuteContract) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Contract) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Msg) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.Funds) > 0 { - for _, e := range m.Funds { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgExecuteContractResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Data) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgMigrateContract) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Contract) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if m.CodeID != 0 { - n += 1 + sovTx(uint64(m.CodeID)) - } - l = len(m.Msg) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgMigrateContractResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Data) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgUpdateAdmin) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.NewAdmin) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Contract) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgUpdateAdminResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgClearAdmin) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Contract) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgClearAdminResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgUpdateInstantiateConfig) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if m.CodeID != 0 { - n += 1 + sovTx(uint64(m.CodeID)) - } - if m.NewInstantiatePermission != nil { - l = m.NewInstantiatePermission.Size() - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgUpdateInstantiateConfigResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgUpdateParams) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Authority) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Params.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgUpdateParamsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgSudoContract) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Authority) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Contract) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Msg) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgSudoContractResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Data) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgPinCodes) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Authority) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.CodeIDs) > 0 { - l = 0 - for _, e := range m.CodeIDs { - l += sovTx(uint64(e)) - } - n += 1 + sovTx(uint64(l)) + l - } - return n -} - -func (m *MsgPinCodesResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgUnpinCodes) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Authority) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.CodeIDs) > 0 { - l = 0 - for _, e := range m.CodeIDs { - l += sovTx(uint64(e)) - } - n += 1 + sovTx(uint64(l)) + l - } - return n -} - -func (m *MsgUnpinCodesResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgStoreAndInstantiateContract) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Authority) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.WASMByteCode) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if m.InstantiatePermission != nil { - l = m.InstantiatePermission.Size() - n += 1 + l + sovTx(uint64(l)) - } - if m.UnpinCode { - n += 2 - } - l = len(m.Admin) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Label) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Msg) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.Funds) > 0 { - for _, e := range m.Funds { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - l = len(m.Source) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Builder) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.CodeHash) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgStoreAndInstantiateContractResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Data) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func sovTx(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} - -func sozTx(x uint64) (n int) { - return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} - -func (m *MsgStoreCode) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgStoreCode: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgStoreCode: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field WASMByteCode", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.WASMByteCode = append(m.WASMByteCode[:0], dAtA[iNdEx:postIndex]...) - if m.WASMByteCode == nil { - m.WASMByteCode = []byte{} - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field InstantiatePermission", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.InstantiatePermission == nil { - m.InstantiatePermission = &AccessConfig{} - } - if err := m.InstantiatePermission.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgStoreCodeResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgStoreCodeResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgStoreCodeResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) - } - m.CodeID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CodeID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Checksum", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Checksum = append(m.Checksum[:0], dAtA[iNdEx:postIndex]...) - if m.Checksum == nil { - m.Checksum = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgInstantiateContract) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgInstantiateContract: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgInstantiateContract: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Admin", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Admin = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) - } - m.CodeID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CodeID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Label", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Label = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Msg = append(m.Msg[:0], dAtA[iNdEx:postIndex]...) - if m.Msg == nil { - m.Msg = []byte{} - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Funds", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Funds = append(m.Funds, types.Coin{}) - if err := m.Funds[len(m.Funds)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgInstantiateContractResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgInstantiateContractResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgInstantiateContractResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) - if m.Data == nil { - m.Data = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgInstantiateContract2) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgInstantiateContract2: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgInstantiateContract2: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Admin", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Admin = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) - } - m.CodeID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CodeID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Label", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Label = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Msg = append(m.Msg[:0], dAtA[iNdEx:postIndex]...) - if m.Msg == nil { - m.Msg = []byte{} - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Funds", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Funds = append(m.Funds, types.Coin{}) - if err := m.Funds[len(m.Funds)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Salt", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Salt = append(m.Salt[:0], dAtA[iNdEx:postIndex]...) - if m.Salt == nil { - m.Salt = []byte{} - } - iNdEx = postIndex - case 8: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field FixMsg", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.FixMsg = bool(v != 0) - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgInstantiateContract2Response) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgInstantiateContract2Response: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgInstantiateContract2Response: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) - if m.Data == nil { - m.Data = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgExecuteContract) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgExecuteContract: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgExecuteContract: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Contract", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Contract = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Msg = append(m.Msg[:0], dAtA[iNdEx:postIndex]...) - if m.Msg == nil { - m.Msg = []byte{} - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Funds", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Funds = append(m.Funds, types.Coin{}) - if err := m.Funds[len(m.Funds)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgExecuteContractResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgExecuteContractResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgExecuteContractResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) - if m.Data == nil { - m.Data = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgMigrateContract) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgMigrateContract: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgMigrateContract: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Contract", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Contract = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) - } - m.CodeID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CodeID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Msg = append(m.Msg[:0], dAtA[iNdEx:postIndex]...) - if m.Msg == nil { - m.Msg = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgMigrateContractResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgMigrateContractResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgMigrateContractResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) - if m.Data == nil { - m.Data = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgUpdateAdmin) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgUpdateAdmin: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgUpdateAdmin: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NewAdmin", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.NewAdmin = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Contract", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Contract = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgUpdateAdminResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgUpdateAdminResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgUpdateAdminResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgClearAdmin) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgClearAdmin: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgClearAdmin: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Contract", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Contract = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgClearAdminResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgClearAdminResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgClearAdminResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgUpdateInstantiateConfig) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgUpdateInstantiateConfig: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgUpdateInstantiateConfig: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) - } - m.CodeID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CodeID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NewInstantiatePermission", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.NewInstantiatePermission == nil { - m.NewInstantiatePermission = &AccessConfig{} - } - if err := m.NewInstantiatePermission.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgUpdateInstantiateConfigResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgUpdateInstantiateConfigResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgUpdateInstantiateConfigResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgUpdateParams) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgUpdateParams: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgUpdateParams: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Authority = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgUpdateParamsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgUpdateParamsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgUpdateParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgSudoContract) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgSudoContract: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgSudoContract: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Authority = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Contract", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Contract = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Msg = append(m.Msg[:0], dAtA[iNdEx:postIndex]...) - if m.Msg == nil { - m.Msg = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgSudoContractResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgSudoContractResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgSudoContractResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) - if m.Data == nil { - m.Data = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgPinCodes) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgPinCodes: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgPinCodes: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Authority = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType == 0 { - var v uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.CodeIDs = append(m.CodeIDs, v) - } else if wireType == 2 { - var packedLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - packedLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if packedLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + packedLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - var elementCount int - var count int - for _, integer := range dAtA[iNdEx:postIndex] { - if integer < 128 { - count++ - } - } - elementCount = count - if elementCount != 0 && len(m.CodeIDs) == 0 { - m.CodeIDs = make([]uint64, 0, elementCount) - } - for iNdEx < postIndex { - var v uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.CodeIDs = append(m.CodeIDs, v) - } - } else { - return fmt.Errorf("proto: wrong wireType = %d for field CodeIDs", wireType) - } - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgPinCodesResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgPinCodesResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgPinCodesResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgUnpinCodes) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgUnpinCodes: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgUnpinCodes: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Authority = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType == 0 { - var v uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.CodeIDs = append(m.CodeIDs, v) - } else if wireType == 2 { - var packedLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - packedLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if packedLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + packedLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - var elementCount int - var count int - for _, integer := range dAtA[iNdEx:postIndex] { - if integer < 128 { - count++ - } - } - elementCount = count - if elementCount != 0 && len(m.CodeIDs) == 0 { - m.CodeIDs = make([]uint64, 0, elementCount) - } - for iNdEx < postIndex { - var v uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.CodeIDs = append(m.CodeIDs, v) - } - } else { - return fmt.Errorf("proto: wrong wireType = %d for field CodeIDs", wireType) - } - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgUnpinCodesResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgUnpinCodesResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgUnpinCodesResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgStoreAndInstantiateContract) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgStoreAndInstantiateContract: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgStoreAndInstantiateContract: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Authority = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field WASMByteCode", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.WASMByteCode = append(m.WASMByteCode[:0], dAtA[iNdEx:postIndex]...) - if m.WASMByteCode == nil { - m.WASMByteCode = []byte{} - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field InstantiatePermission", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.InstantiatePermission == nil { - m.InstantiatePermission = &AccessConfig{} - } - if err := m.InstantiatePermission.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field UnpinCode", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.UnpinCode = bool(v != 0) - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Admin", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Admin = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Label", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Label = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Msg = append(m.Msg[:0], dAtA[iNdEx:postIndex]...) - if m.Msg == nil { - m.Msg = []byte{} - } - iNdEx = postIndex - case 9: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Funds", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Funds = append(m.Funds, types.Coin{}) - if err := m.Funds[len(m.Funds)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 10: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Source", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Source = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 11: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Builder", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Builder = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 12: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeHash", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CodeHash = append(m.CodeHash[:0], dAtA[iNdEx:postIndex]...) - if m.CodeHash == nil { - m.CodeHash = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgStoreAndInstantiateContractResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgStoreAndInstantiateContractResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgStoreAndInstantiateContractResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) - if m.Data == nil { - m.Data = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func skipTx(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthTx - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTx - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTx - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/wasm/types/tx_test.go b/x/wasm/types/tx_test.go deleted file mode 100644 index 355beae..0000000 --- a/x/wasm/types/tx_test.go +++ /dev/null @@ -1,1139 +0,0 @@ -package types - -import ( - "bytes" - "strings" - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -const firstCodeID = 1 - -func TestStoreCodeValidation(t *testing.T) { - bad, err := sdk.AccAddressFromHexUnsafe("012345") - require.NoError(t, err) - badAddress := bad.String() - // proper address size - goodAddress := sdk.AccAddress(make([]byte, ContractAddrLen)).String() - sdk.GetConfig().SetAddressVerifier(VerifyAddressLen()) - cases := map[string]struct { - msg MsgStoreCode - valid bool - }{ - "empty": { - msg: MsgStoreCode{}, - valid: false, - }, - "correct minimal": { - msg: MsgStoreCode{ - Sender: goodAddress, - WASMByteCode: []byte("foo"), - }, - valid: true, - }, - "missing code": { - msg: MsgStoreCode{ - Sender: goodAddress, - }, - valid: false, - }, - "bad sender minimal": { - msg: MsgStoreCode{ - Sender: badAddress, - WASMByteCode: []byte("foo"), - }, - valid: false, - }, - "correct maximal": { - msg: MsgStoreCode{ - Sender: goodAddress, - WASMByteCode: []byte("foo"), - }, - valid: true, - }, - "invalid InstantiatePermission": { - msg: MsgStoreCode{ - Sender: goodAddress, - WASMByteCode: []byte("foo"), - InstantiatePermission: &AccessConfig{Permission: AccessTypeOnlyAddress, Address: badAddress}, - }, - valid: false, - }, - } - - for name, tc := range cases { - t.Run(name, func(t *testing.T) { - err := tc.msg.ValidateBasic() - if tc.valid { - assert.NoError(t, err) - } else { - assert.Error(t, err) - } - }) - } -} - -func TestInstantiateContractValidation(t *testing.T) { - bad, err := sdk.AccAddressFromHexUnsafe("012345") - require.NoError(t, err) - badAddress := bad.String() - // proper address size - goodAddress := sdk.AccAddress(make([]byte, 20)).String() - sdk.GetConfig().SetAddressVerifier(VerifyAddressLen()) - - cases := map[string]struct { - msg MsgInstantiateContract - valid bool - }{ - "empty": { - msg: MsgInstantiateContract{}, - valid: false, - }, - "correct minimal": { - msg: MsgInstantiateContract{ - Sender: goodAddress, - CodeID: firstCodeID, - Label: "foo", - Msg: []byte("{}"), - }, - valid: true, - }, - "missing code": { - msg: MsgInstantiateContract{ - Sender: goodAddress, - Label: "foo", - Msg: []byte("{}"), - }, - valid: false, - }, - "missing label": { - msg: MsgInstantiateContract{ - Sender: goodAddress, - Msg: []byte("{}"), - }, - valid: false, - }, - "label too long": { - msg: MsgInstantiateContract{ - Sender: goodAddress, - Label: strings.Repeat("food", 33), - }, - valid: false, - }, - "bad sender minimal": { - msg: MsgInstantiateContract{ - Sender: badAddress, - CodeID: firstCodeID, - Label: "foo", - Msg: []byte("{}"), - }, - valid: false, - }, - "correct maximal": { - msg: MsgInstantiateContract{ - Sender: goodAddress, - CodeID: firstCodeID, - Label: "foo", - Msg: []byte(`{"some": "data"}`), - Funds: sdk.Coins{sdk.Coin{Denom: "foobar", Amount: sdk.NewInt(200)}}, - }, - valid: true, - }, - "negative funds": { - msg: MsgInstantiateContract{ - Sender: goodAddress, - CodeID: firstCodeID, - Label: "foo", - Msg: []byte(`{"some": "data"}`), - // we cannot use sdk.NewCoin() constructors as they panic on creating invalid data (before we can test) - Funds: sdk.Coins{sdk.Coin{Denom: "foobar", Amount: sdk.NewInt(-200)}}, - }, - valid: false, - }, - "non json init msg": { - msg: MsgInstantiateContract{ - Sender: goodAddress, - CodeID: firstCodeID, - Label: "foo", - Msg: []byte("invalid-json"), - }, - valid: false, - }, - "empty init msg": { - msg: MsgInstantiateContract{ - Sender: goodAddress, - CodeID: firstCodeID, - Label: "foo", - }, - valid: false, - }, - } - - for name, tc := range cases { - t.Run(name, func(t *testing.T) { - err := tc.msg.ValidateBasic() - if tc.valid { - assert.NoError(t, err) - } else { - assert.Error(t, err) - } - }) - } -} - -func TestInstantiateContract2Validation(t *testing.T) { - bad, err := sdk.AccAddressFromHexUnsafe("012345") - require.NoError(t, err) - badAddress := bad.String() - // proper address size - goodAddress := sdk.AccAddress(make([]byte, 20)).String() - sdk.GetConfig().SetAddressVerifier(VerifyAddressLen()) - - cases := map[string]struct { - msg MsgInstantiateContract2 - valid bool - }{ - "empty": { - msg: MsgInstantiateContract2{}, - valid: false, - }, - "correct minimal": { - msg: MsgInstantiateContract2{ - Sender: goodAddress, - CodeID: firstCodeID, - Label: "foo", - Msg: []byte("{}"), - Salt: []byte{0}, - }, - valid: true, - }, - "missing code": { - msg: MsgInstantiateContract2{ - Sender: goodAddress, - Label: "foo", - Msg: []byte("{}"), - Salt: []byte{0}, - }, - valid: false, - }, - "missing label": { - msg: MsgInstantiateContract2{ - Sender: goodAddress, - Msg: []byte("{}"), - Salt: []byte{0}, - }, - valid: false, - }, - "label too long": { - msg: MsgInstantiateContract2{ - Sender: goodAddress, - Label: strings.Repeat("food", 33), - Salt: []byte{0}, - }, - valid: false, - }, - "bad sender minimal": { - msg: MsgInstantiateContract2{ - Sender: badAddress, - CodeID: firstCodeID, - Label: "foo", - Msg: []byte("{}"), - Salt: []byte{0}, - }, - valid: false, - }, - "correct maximal": { - msg: MsgInstantiateContract2{ - Sender: goodAddress, - CodeID: firstCodeID, - Label: strings.Repeat("a", MaxLabelSize), - Msg: []byte(`{"some": "data"}`), - Funds: sdk.Coins{sdk.Coin{Denom: "foobar", Amount: sdk.NewInt(200)}}, - Salt: bytes.Repeat([]byte{0}, MaxSaltSize), - FixMsg: true, - }, - valid: true, - }, - "negative funds": { - msg: MsgInstantiateContract2{ - Sender: goodAddress, - CodeID: firstCodeID, - Label: "foo", - Msg: []byte(`{"some": "data"}`), - // we cannot use sdk.NewCoin() constructors as they panic on creating invalid data (before we can test) - Funds: sdk.Coins{sdk.Coin{Denom: "foobar", Amount: sdk.NewInt(-200)}}, - Salt: []byte{0}, - }, - valid: false, - }, - "non json init msg": { - msg: MsgInstantiateContract2{ - Sender: goodAddress, - CodeID: firstCodeID, - Label: "foo", - Msg: []byte("invalid-json"), - Salt: []byte{0}, - }, - valid: false, - }, - "empty init msg": { - msg: MsgInstantiateContract2{ - Sender: goodAddress, - CodeID: firstCodeID, - Label: "foo", - Salt: []byte{0}, - }, - valid: false, - }, - "empty salt": { - msg: MsgInstantiateContract2{ - Sender: goodAddress, - CodeID: firstCodeID, - Label: "foo", - Msg: []byte(`{"some": "data"}`), - }, - valid: false, - }, - "salt too long": { - msg: MsgInstantiateContract2{ - Sender: goodAddress, - CodeID: firstCodeID, - Label: "foo", - Msg: []byte(`{"some": "data"}`), - Salt: bytes.Repeat([]byte{0}, 65), - }, - valid: false, - }, - } - for name, tc := range cases { - t.Run(name, func(t *testing.T) { - err := tc.msg.ValidateBasic() - if tc.valid { - assert.NoError(t, err) - } else { - assert.Error(t, err) - } - }) - } -} - -func TestExecuteContractValidation(t *testing.T) { - bad, err := sdk.AccAddressFromHexUnsafe("012345") - require.NoError(t, err) - badAddress := bad.String() - // proper address size - goodAddress := sdk.AccAddress(make([]byte, 20)).String() - - cases := map[string]struct { - msg MsgExecuteContract - valid bool - }{ - "empty": { - msg: MsgExecuteContract{}, - valid: false, - }, - "correct minimal": { - msg: MsgExecuteContract{ - Sender: goodAddress, - Contract: goodAddress, - Msg: []byte("{}"), - }, - valid: true, - }, - "correct all": { - msg: MsgExecuteContract{ - Sender: goodAddress, - Contract: goodAddress, - Msg: []byte(`{"some": "data"}`), - Funds: sdk.Coins{sdk.Coin{Denom: "foobar", Amount: sdk.NewInt(200)}}, - }, - valid: true, - }, - "bad sender": { - msg: MsgExecuteContract{ - Sender: badAddress, - Contract: goodAddress, - Msg: []byte(`{"some": "data"}`), - }, - valid: false, - }, - "empty sender": { - msg: MsgExecuteContract{ - Contract: goodAddress, - Msg: []byte(`{"some": "data"}`), - }, - valid: false, - }, - "bad contract": { - msg: MsgExecuteContract{ - Sender: goodAddress, - Contract: badAddress, - Msg: []byte(`{"some": "data"}`), - }, - valid: false, - }, - "empty contract": { - msg: MsgExecuteContract{ - Sender: goodAddress, - Msg: []byte(`{"some": "data"}`), - }, - valid: false, - }, - "negative funds": { - msg: MsgExecuteContract{ - Sender: goodAddress, - Contract: goodAddress, - Msg: []byte(`{"some": "data"}`), - Funds: sdk.Coins{sdk.Coin{Denom: "foobar", Amount: sdk.NewInt(-1)}}, - }, - valid: false, - }, - "duplicate funds": { - msg: MsgExecuteContract{ - Sender: goodAddress, - Contract: goodAddress, - Msg: []byte(`{"some": "data"}`), - Funds: sdk.Coins{sdk.Coin{Denom: "foobar", Amount: sdk.NewInt(1)}, sdk.Coin{Denom: "foobar", Amount: sdk.NewInt(1)}}, - }, - valid: false, - }, - "non json msg": { - msg: MsgExecuteContract{ - Sender: goodAddress, - Contract: goodAddress, - Msg: []byte("invalid-json"), - }, - valid: false, - }, - "empty msg": { - msg: MsgExecuteContract{ - Sender: goodAddress, - Contract: goodAddress, - }, - valid: false, - }, - } - - for name, tc := range cases { - t.Run(name, func(t *testing.T) { - err := tc.msg.ValidateBasic() - if tc.valid { - assert.NoError(t, err) - } else { - assert.Error(t, err) - } - }) - } -} - -func TestMsgUpdateAdministrator(t *testing.T) { - bad, err := sdk.AccAddressFromHexUnsafe("012345") - require.NoError(t, err) - badAddress := bad.String() - // proper address size - goodAddress := sdk.AccAddress(make([]byte, 20)).String() - otherGoodAddress := sdk.AccAddress(bytes.Repeat([]byte{0x1}, 20)).String() - anotherGoodAddress := sdk.AccAddress(bytes.Repeat([]byte{0x2}, 20)).String() - - specs := map[string]struct { - src MsgUpdateAdmin - expErr bool - }{ - "all good": { - src: MsgUpdateAdmin{ - Sender: goodAddress, - NewAdmin: otherGoodAddress, - Contract: anotherGoodAddress, - }, - }, - "new admin required": { - src: MsgUpdateAdmin{ - Sender: goodAddress, - Contract: anotherGoodAddress, - }, - expErr: true, - }, - "bad sender": { - src: MsgUpdateAdmin{ - Sender: badAddress, - NewAdmin: otherGoodAddress, - Contract: anotherGoodAddress, - }, - expErr: true, - }, - "bad new admin": { - src: MsgUpdateAdmin{ - Sender: goodAddress, - NewAdmin: badAddress, - Contract: anotherGoodAddress, - }, - expErr: true, - }, - "bad contract addr": { - src: MsgUpdateAdmin{ - Sender: goodAddress, - NewAdmin: otherGoodAddress, - Contract: badAddress, - }, - expErr: true, - }, - "new admin same as old admin": { - src: MsgUpdateAdmin{ - Sender: goodAddress, - NewAdmin: goodAddress, - Contract: anotherGoodAddress, - }, - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - return - } - require.NoError(t, err) - }) - } -} - -func TestMsgClearAdministrator(t *testing.T) { - bad, err := sdk.AccAddressFromHexUnsafe("012345") - require.NoError(t, err) - badAddress := bad.String() - // proper address size - goodAddress := sdk.AccAddress(make([]byte, 20)).String() - anotherGoodAddress := sdk.AccAddress(bytes.Repeat([]byte{0x2}, 20)).String() - - specs := map[string]struct { - src MsgClearAdmin - expErr bool - }{ - "all good": { - src: MsgClearAdmin{ - Sender: goodAddress, - Contract: anotherGoodAddress, - }, - }, - "bad sender": { - src: MsgClearAdmin{ - Sender: badAddress, - Contract: anotherGoodAddress, - }, - expErr: true, - }, - "bad contract addr": { - src: MsgClearAdmin{ - Sender: goodAddress, - Contract: badAddress, - }, - expErr: true, - }, - "contract missing": { - src: MsgClearAdmin{ - Sender: goodAddress, - }, - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - return - } - require.NoError(t, err) - }) - } -} - -func TestMsgMigrateContract(t *testing.T) { - bad, err := sdk.AccAddressFromHexUnsafe("012345") - require.NoError(t, err) - badAddress := bad.String() - // proper address size - goodAddress := sdk.AccAddress(make([]byte, 20)).String() - anotherGoodAddress := sdk.AccAddress(bytes.Repeat([]byte{0x2}, 20)).String() - - specs := map[string]struct { - src MsgMigrateContract - expErr bool - }{ - "all good": { - src: MsgMigrateContract{ - Sender: goodAddress, - Contract: anotherGoodAddress, - CodeID: firstCodeID, - Msg: []byte("{}"), - }, - }, - "bad sender": { - src: MsgMigrateContract{ - Sender: badAddress, - Contract: anotherGoodAddress, - CodeID: firstCodeID, - }, - expErr: true, - }, - "empty sender": { - src: MsgMigrateContract{ - Contract: anotherGoodAddress, - CodeID: firstCodeID, - }, - expErr: true, - }, - "empty code": { - src: MsgMigrateContract{ - Sender: goodAddress, - Contract: anotherGoodAddress, - }, - expErr: true, - }, - "bad contract addr": { - src: MsgMigrateContract{ - Sender: goodAddress, - Contract: badAddress, - CodeID: firstCodeID, - }, - expErr: true, - }, - "empty contract addr": { - src: MsgMigrateContract{ - Sender: goodAddress, - CodeID: firstCodeID, - }, - expErr: true, - }, - "non json migrateMsg": { - src: MsgMigrateContract{ - Sender: goodAddress, - Contract: anotherGoodAddress, - CodeID: firstCodeID, - Msg: []byte("invalid json"), - }, - expErr: true, - }, - "empty migrateMsg": { - src: MsgMigrateContract{ - Sender: goodAddress, - Contract: anotherGoodAddress, - CodeID: firstCodeID, - }, - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - return - } - require.NoError(t, err) - }) - } -} - -func TestMsgJsonSignBytes(t *testing.T) { - const myInnerMsg = `{"foo":"bar"}` - specs := map[string]struct { - src legacytx.LegacyMsg - exp string - }{ - "MsgInstantiateContract": { - src: &MsgInstantiateContract{Msg: RawContractMessage(myInnerMsg)}, - exp: ` -{ - "type":"wasm/MsgInstantiateContract", - "value": {"msg": {"foo":"bar"}, "funds":[]} -}`, - }, - "MsgExecuteContract": { - src: &MsgExecuteContract{Msg: RawContractMessage(myInnerMsg)}, - exp: ` -{ - "type":"wasm/MsgExecuteContract", - "value": {"msg": {"foo":"bar"}, "funds":[]} -}`, - }, - "MsgMigrateContract": { - src: &MsgMigrateContract{Msg: RawContractMessage(myInnerMsg)}, - exp: ` -{ - "type":"wasm/MsgMigrateContract", - "value": {"msg": {"foo":"bar"}} -}`, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - bz := spec.src.GetSignBytes() - assert.JSONEq(t, spec.exp, string(bz), "raw: %s", string(bz)) - }) - } -} - -func TestMsgUpdateInstantiateConfig(t *testing.T) { - bad, err := sdk.AccAddressFromHexUnsafe("012345") - require.NoError(t, err) - badAddress := bad.String() - // proper address size - goodAddress := sdk.AccAddress(make([]byte, 20)).String() - anotherGoodAddress := sdk.AccAddress(bytes.Repeat([]byte{0x2}, 20)).String() - - specs := map[string]struct { - src MsgUpdateInstantiateConfig - expErr bool - }{ - "all good": { - src: MsgUpdateInstantiateConfig{ - Sender: goodAddress, - CodeID: 1, - NewInstantiatePermission: &AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{anotherGoodAddress}}, - }, - }, - "retained AccessTypeOnlyAddress": { - src: MsgUpdateInstantiateConfig{ - Sender: goodAddress, - CodeID: 1, - NewInstantiatePermission: &AccessConfig{Permission: AccessTypeOnlyAddress, Address: anotherGoodAddress}, - }, - expErr: true, - }, - "bad sender": { - src: MsgUpdateInstantiateConfig{ - Sender: badAddress, - CodeID: 1, - NewInstantiatePermission: &AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{anotherGoodAddress}}, - }, - expErr: true, - }, - "invalid NewInstantiatePermission": { - src: MsgUpdateInstantiateConfig{ - Sender: goodAddress, - CodeID: 1, - NewInstantiatePermission: &AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{badAddress}}, - }, - expErr: true, - }, - "missing code id": { - src: MsgUpdateInstantiateConfig{ - Sender: goodAddress, - NewInstantiatePermission: &AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{anotherGoodAddress}}, - }, - expErr: true, - }, - "missing NewInstantiatePermission": { - src: MsgUpdateInstantiateConfig{ - Sender: goodAddress, - CodeID: 1, - }, - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - return - } - require.NoError(t, err) - }) - } -} - -func TestMsgUpdateParamsValidation(t *testing.T) { - bad, err := sdk.AccAddressFromHexUnsafe("012345") - require.NoError(t, err) - badAddress := bad.String() - // proper address size - goodAddress := sdk.AccAddress(make([]byte, 20)).String() - - specs := map[string]struct { - src MsgUpdateParams - expErr bool - }{ - "all good": { - src: MsgUpdateParams{ - Authority: goodAddress, - Params: DefaultParams(), - }, - }, - "bad authority": { - src: MsgUpdateParams{ - Authority: badAddress, - Params: DefaultParams(), - }, - expErr: true, - }, - "empty authority": { - src: MsgUpdateParams{ - Params: DefaultParams(), - }, - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - return - } - require.NoError(t, err) - }) - } -} - -func TestMsgPinCodesValidation(t *testing.T) { - bad, err := sdk.AccAddressFromHexUnsafe("012345") - require.NoError(t, err) - badAddress := bad.String() - // proper address size - goodAddress := sdk.AccAddress(make([]byte, 20)).String() - - specs := map[string]struct { - src MsgPinCodes - expErr bool - }{ - "all good": { - src: MsgPinCodes{ - Authority: goodAddress, - CodeIDs: []uint64{1}, - }, - }, - "bad authority": { - src: MsgPinCodes{ - Authority: badAddress, - CodeIDs: []uint64{1}, - }, - expErr: true, - }, - "empty authority": { - src: MsgPinCodes{ - CodeIDs: []uint64{1}, - }, - expErr: true, - }, - "empty code ids": { - src: MsgPinCodes{ - Authority: goodAddress, - }, - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - return - } - require.NoError(t, err) - }) - } -} - -func TestMsgUnpinCodesValidation(t *testing.T) { - bad, err := sdk.AccAddressFromHexUnsafe("012345") - require.NoError(t, err) - badAddress := bad.String() - // proper address size - goodAddress := sdk.AccAddress(make([]byte, 20)).String() - - specs := map[string]struct { - src MsgUnpinCodes - expErr bool - }{ - "all good": { - src: MsgUnpinCodes{ - Authority: goodAddress, - CodeIDs: []uint64{1}, - }, - }, - "bad authority": { - src: MsgUnpinCodes{ - Authority: badAddress, - CodeIDs: []uint64{1}, - }, - expErr: true, - }, - "empty authority": { - src: MsgUnpinCodes{ - CodeIDs: []uint64{1}, - }, - expErr: true, - }, - "empty code ids": { - src: MsgUnpinCodes{ - Authority: goodAddress, - }, - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - return - } - require.NoError(t, err) - }) - } -} - -func TestMsgSudoContractValidation(t *testing.T) { - bad, err := sdk.AccAddressFromHexUnsafe("012345") - require.NoError(t, err) - badAddress := bad.String() - // proper address size - goodAddress := sdk.AccAddress(make([]byte, 20)).String() - anotherGoodAddress := sdk.AccAddress(bytes.Repeat([]byte{0x2}, 20)).String() - - specs := map[string]struct { - src MsgSudoContract - expErr bool - }{ - "all good": { - src: MsgSudoContract{ - Authority: goodAddress, - Contract: anotherGoodAddress, - Msg: []byte("{}"), - }, - }, - "bad authority": { - src: MsgSudoContract{ - Authority: badAddress, - Contract: anotherGoodAddress, - Msg: []byte("{}"), - }, - expErr: true, - }, - "empty authority": { - src: MsgSudoContract{ - Contract: anotherGoodAddress, - Msg: []byte("{}"), - }, - expErr: true, - }, - "bad contract addr": { - src: MsgSudoContract{ - Authority: goodAddress, - Contract: badAddress, - Msg: []byte("{}"), - }, - expErr: true, - }, - "empty contract addr": { - src: MsgSudoContract{ - Authority: goodAddress, - Msg: []byte("{}"), - }, - expErr: true, - }, - "non json sudoMsg": { - src: MsgSudoContract{ - Authority: goodAddress, - Contract: anotherGoodAddress, - Msg: []byte("invalid json"), - }, - expErr: true, - }, - "empty sudoMsg": { - src: MsgSudoContract{ - Authority: goodAddress, - Contract: anotherGoodAddress, - }, - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - return - } - require.NoError(t, err) - }) - } -} - -func TestMsgStoreAndInstantiateContractValidation(t *testing.T) { - bad, err := sdk.AccAddressFromHexUnsafe("012345") - require.NoError(t, err) - badAddress := bad.String() - // proper address size - goodAddress := sdk.AccAddress(make([]byte, 20)).String() - sdk.GetConfig().SetAddressVerifier(VerifyAddressLen()) - - cases := map[string]struct { - msg MsgStoreAndInstantiateContract - valid bool - }{ - "empty": { - msg: MsgStoreAndInstantiateContract{}, - valid: false, - }, - "correct minimal": { - msg: MsgStoreAndInstantiateContract{ - Authority: goodAddress, - Label: "foo", - Msg: []byte("{}"), - WASMByteCode: []byte("foo"), - }, - valid: true, - }, - "missing byte code": { - msg: MsgStoreAndInstantiateContract{ - Authority: goodAddress, - Label: "foo", - Msg: []byte("{}"), - }, - valid: false, - }, - "missing label": { - msg: MsgStoreAndInstantiateContract{ - Authority: goodAddress, - Msg: []byte("{}"), - WASMByteCode: []byte("foo"), - }, - valid: false, - }, - "label too long": { - msg: MsgStoreAndInstantiateContract{ - Authority: goodAddress, - Label: strings.Repeat("food", 33), - Msg: []byte("{}"), - WASMByteCode: []byte("foo"), - }, - valid: false, - }, - "bad sender minimal": { - msg: MsgStoreAndInstantiateContract{ - Authority: badAddress, - Label: "foo", - Msg: []byte("{}"), - WASMByteCode: []byte("foo"), - }, - valid: false, - }, - "bad admin": { - msg: MsgStoreAndInstantiateContract{ - Authority: goodAddress, - Label: "foo", - Msg: []byte("{}"), - WASMByteCode: []byte("foo"), - Admin: badAddress, - }, - valid: false, - }, - "correct maximal": { - msg: MsgStoreAndInstantiateContract{ - Authority: goodAddress, - Label: "foo", - Msg: []byte(`{"some": "data"}`), - Funds: sdk.Coins{sdk.Coin{Denom: "foobar", Amount: sdk.NewInt(200)}}, - WASMByteCode: []byte("foo"), - InstantiatePermission: &AllowEverybody, - UnpinCode: true, - Admin: goodAddress, - Source: "http://source.com", - Builder: "builder", - CodeHash: []byte("{}"), - }, - valid: true, - }, - "invalid source": { - msg: MsgStoreAndInstantiateContract{ - Authority: goodAddress, - Label: "foo", - Msg: []byte("{}"), - WASMByteCode: []byte("foo"), - Admin: goodAddress, - Source: "source", - }, - valid: false, - }, - "empty builder": { - msg: MsgStoreAndInstantiateContract{ - Authority: goodAddress, - Label: "foo", - Msg: []byte("{}"), - WASMByteCode: []byte("foo"), - Admin: goodAddress, - Source: "http://source.com", - }, - valid: false, - }, - "empty code hash": { - msg: MsgStoreAndInstantiateContract{ - Authority: goodAddress, - Label: "foo", - Msg: []byte("{}"), - WASMByteCode: []byte("foo"), - Admin: goodAddress, - Source: "http://source.com", - Builder: "builder", - }, - valid: false, - }, - "negative funds": { - msg: MsgStoreAndInstantiateContract{ - Authority: goodAddress, - Label: "foo", - Msg: []byte(`{"some": "data"}`), - // we cannot use sdk.NewCoin() constructors as they panic on creating invalid data (before we can test) - Funds: sdk.Coins{sdk.Coin{Denom: "foobar", Amount: sdk.NewInt(-200)}}, - WASMByteCode: []byte("foo"), - }, - valid: false, - }, - "non json init msg": { - msg: MsgStoreAndInstantiateContract{ - Authority: goodAddress, - Label: "foo", - Msg: []byte("invalid-json"), - WASMByteCode: []byte("foo"), - }, - valid: false, - }, - "empty init msg": { - msg: MsgStoreAndInstantiateContract{ - Authority: goodAddress, - Label: "foo", - WASMByteCode: []byte("foo"), - }, - valid: false, - }, - "invalid InstantiatePermission": { - msg: MsgStoreAndInstantiateContract{ - Authority: goodAddress, - WASMByteCode: []byte("foo"), - Label: "foo", - Msg: []byte(`{"some": "data"}`), - InstantiatePermission: &AccessConfig{Permission: AccessTypeOnlyAddress, Address: badAddress}, - }, - valid: false, - }, - } - - for name, tc := range cases { - t.Run(name, func(t *testing.T) { - err := tc.msg.ValidateBasic() - if tc.valid { - assert.NoError(t, err) - } else { - assert.Error(t, err) - } - }) - } -} diff --git a/x/wasm/types/types.go b/x/wasm/types/types.go deleted file mode 100644 index ffec304..0000000 --- a/x/wasm/types/types.go +++ /dev/null @@ -1,437 +0,0 @@ -package types - -import ( - "fmt" - "reflect" - - errorsmod "cosmossdk.io/errors" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/gogoproto/proto" -) - -const ( - defaultMemoryCacheSize uint32 = 100 // in MiB - defaultSmartQueryGasLimit uint64 = 3_000_000 - defaultContractDebugMode = false - - // ContractAddrLen defines a valid address length for contracts - ContractAddrLen = 32 - // SDKAddrLen defines a valid address length that was used in sdk address generation - SDKAddrLen = 20 -) - -func (m Model) ValidateBasic() error { - if len(m.Key) == 0 { - return errorsmod.Wrap(ErrEmpty, "key") - } - return nil -} - -func (c CodeInfo) ValidateBasic() error { - if len(c.CodeHash) == 0 { - return errorsmod.Wrap(ErrEmpty, "code hash") - } - if _, err := sdk.AccAddressFromBech32(c.Creator); err != nil { - return errorsmod.Wrap(err, "creator") - } - if err := c.InstantiateConfig.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "instantiate config") - } - return nil -} - -// NewCodeInfo fills a new CodeInfo struct -func NewCodeInfo(codeHash []byte, creator sdk.AccAddress, instantiatePermission AccessConfig) CodeInfo { - return CodeInfo{ - CodeHash: codeHash, - Creator: creator.String(), - InstantiateConfig: instantiatePermission, - } -} - -var AllCodeHistoryTypes = []ContractCodeHistoryOperationType{ContractCodeHistoryOperationTypeGenesis, ContractCodeHistoryOperationTypeInit, ContractCodeHistoryOperationTypeMigrate} - -// NewContractInfo creates a new instance of a given WASM contract info -func NewContractInfo(codeID uint64, creator, admin sdk.AccAddress, label string, createdAt *AbsoluteTxPosition) ContractInfo { - var adminAddr string - if !admin.Empty() { - adminAddr = admin.String() - } - return ContractInfo{ - CodeID: codeID, - Creator: creator.String(), - Admin: adminAddr, - Label: label, - Created: createdAt, - } -} - -// validatable is an optional interface that can be implemented by an ContractInfoExtension to enable validation -type validatable interface { - ValidateBasic() error -} - -// ValidateBasic does syntax checks on the data. If an extension is set and has the `ValidateBasic() error` method, then -// the method is called as well. It is recommend to implement `ValidateBasic` so that the data is verified in the setter -// but also in the genesis import process. -func (c *ContractInfo) ValidateBasic() error { - if c.CodeID == 0 { - return errorsmod.Wrap(ErrEmpty, "code id") - } - if _, err := sdk.AccAddressFromBech32(c.Creator); err != nil { - return errorsmod.Wrap(err, "creator") - } - if len(c.Admin) != 0 { - if _, err := sdk.AccAddressFromBech32(c.Admin); err != nil { - return errorsmod.Wrap(err, "admin") - } - } - if err := ValidateLabel(c.Label); err != nil { - return errorsmod.Wrap(err, "label") - } - if c.Extension == nil { - return nil - } - - e, ok := c.Extension.GetCachedValue().(validatable) - if !ok { - return nil - } - if err := e.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "extension") - } - return nil -} - -// SetExtension set new extension data. Calls `ValidateBasic() error` on non nil values when method is implemented by -// the extension. -func (c *ContractInfo) SetExtension(ext ContractInfoExtension) error { - if ext == nil { - c.Extension = nil - return nil - } - if e, ok := ext.(validatable); ok { - if err := e.ValidateBasic(); err != nil { - return err - } - } - codecAny, err := codectypes.NewAnyWithValue(ext) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrPackAny, err.Error()) - } - - c.Extension = codecAny - return nil -} - -// ReadExtension copies the extension value to the pointer passed as argument so that there is no need to cast -// For example with a custom extension of type `MyContractDetails` it will look as following: -// -// var d MyContractDetails -// if err := info.ReadExtension(&d); err != nil { -// return nil, errorsmod.Wrap(err, "extension") -// } -func (c *ContractInfo) ReadExtension(e ContractInfoExtension) error { - rv := reflect.ValueOf(e) - if rv.Kind() != reflect.Ptr || rv.IsNil() { - return errorsmod.Wrap(sdkerrors.ErrInvalidType, "not a pointer") - } - if c.Extension == nil { - return nil - } - - cached := c.Extension.GetCachedValue() - elem := reflect.ValueOf(cached).Elem() - if !elem.Type().AssignableTo(rv.Elem().Type()) { - return errorsmod.Wrapf(sdkerrors.ErrInvalidType, "extension is of type %s but argument of %s", elem.Type(), rv.Elem().Type()) - } - rv.Elem().Set(elem) - return nil -} - -func (c ContractInfo) InitialHistory(initMsg []byte) ContractCodeHistoryEntry { - return ContractCodeHistoryEntry{ - Operation: ContractCodeHistoryOperationTypeInit, - CodeID: c.CodeID, - Updated: c.Created, - Msg: initMsg, - } -} - -func (c *ContractInfo) AddMigration(ctx sdk.Context, codeID uint64, msg []byte) ContractCodeHistoryEntry { - h := ContractCodeHistoryEntry{ - Operation: ContractCodeHistoryOperationTypeMigrate, - CodeID: codeID, - Updated: NewAbsoluteTxPosition(ctx), - Msg: msg, - } - c.CodeID = codeID - return h -} - -// AdminAddr convert into sdk.AccAddress or nil when not set -func (c *ContractInfo) AdminAddr() sdk.AccAddress { - if c.Admin == "" { - return nil - } - admin, err := sdk.AccAddressFromBech32(c.Admin) - if err != nil { // should never happen - panic(err.Error()) - } - return admin -} - -// ContractInfoExtension defines the extension point for custom data to be stored with a contract info -type ContractInfoExtension interface { - proto.Message - String() string -} - -var _ codectypes.UnpackInterfacesMessage = &ContractInfo{} - -// UnpackInterfaces implements codectypes.UnpackInterfaces -func (c *ContractInfo) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { - var details ContractInfoExtension - if err := unpacker.UnpackAny(c.Extension, &details); err != nil { - return err - } - return codectypes.UnpackInterfaces(details, unpacker) -} - -// NewAbsoluteTxPosition gets a block position from the context -func NewAbsoluteTxPosition(ctx sdk.Context) *AbsoluteTxPosition { - // we must safely handle nil gas meters - var index uint64 - meter := ctx.BlockGasMeter() - if meter != nil { - index = meter.GasConsumed() - } - height := ctx.BlockHeight() - if height < 0 { - panic(fmt.Sprintf("unsupported height: %d", height)) - } - return &AbsoluteTxPosition{ - BlockHeight: uint64(height), - TxIndex: index, - } -} - -// LessThan can be used to sort -func (a *AbsoluteTxPosition) LessThan(b *AbsoluteTxPosition) bool { - if a == nil { - return true - } - if b == nil { - return false - } - return a.BlockHeight < b.BlockHeight || (a.BlockHeight == b.BlockHeight && a.TxIndex < b.TxIndex) -} - -// AbsoluteTxPositionLen number of elements in byte representation -const AbsoluteTxPositionLen = 16 - -// Bytes encodes the object into a 16 byte representation with big endian block height and tx index. -func (a *AbsoluteTxPosition) Bytes() []byte { - if a == nil { - panic("object must not be nil") - } - r := make([]byte, AbsoluteTxPositionLen) - copy(r[0:], sdk.Uint64ToBigEndian(a.BlockHeight)) - copy(r[8:], sdk.Uint64ToBigEndian(a.TxIndex)) - return r -} - -// ValidateBasic syntax checks -func (c ContractCodeHistoryEntry) ValidateBasic() error { - var found bool - for _, v := range AllCodeHistoryTypes { - if c.Operation == v { - found = true - break - } - } - if !found { - return ErrInvalid.Wrap("operation") - } - if c.CodeID == 0 { - return ErrEmpty.Wrap("code id") - } - if c.Updated == nil { - return ErrEmpty.Wrap("updated") - } - return errorsmod.Wrap(c.Msg.ValidateBasic(), "msg") -} - -// NewEnv initializes the environment for a contract instance -func NewEnv(ctx sdk.Context, contractAddr sdk.AccAddress) wasmvmtypes.Env { - // safety checks before casting below - if ctx.BlockHeight() < 0 { - panic("Block height must never be negative") - } - nano := ctx.BlockTime().UnixNano() - if nano < 1 { - panic("Block (unix) time must never be empty or negative ") - } - - env := wasmvmtypes.Env{ - Block: wasmvmtypes.BlockInfo{ - Height: uint64(ctx.BlockHeight()), - Time: uint64(nano), - ChainID: ctx.ChainID(), - }, - Contract: wasmvmtypes.ContractInfo{ - Address: contractAddr.String(), - }, - } - if txCounter, ok := TXCounter(ctx); ok { - env.Transaction = &wasmvmtypes.TransactionInfo{Index: txCounter} - } - return env -} - -// NewInfo initializes the MessageInfo for a contract instance -func NewInfo(creator sdk.AccAddress, deposit sdk.Coins) wasmvmtypes.MessageInfo { - return wasmvmtypes.MessageInfo{ - Sender: creator.String(), - Funds: NewWasmCoins(deposit), - } -} - -// NewWasmCoins translates between Cosmos SDK coins and Wasm coins -func NewWasmCoins(cosmosCoins sdk.Coins) (wasmCoins []wasmvmtypes.Coin) { - for _, coin := range cosmosCoins { - wasmCoin := wasmvmtypes.Coin{ - Denom: coin.Denom, - Amount: coin.Amount.String(), - } - wasmCoins = append(wasmCoins, wasmCoin) - } - return wasmCoins -} - -// WasmConfig is the extra config required for wasm -type WasmConfig struct { - // SimulationGasLimit is the max gas to be used in a tx simulation call. - // When not set the consensus max block gas is used instead - SimulationGasLimit *uint64 `mapstructure:"simulation_gas_limit"` - // SmartQueryGasLimit is the max gas to be used in a smart query contract call - SmartQueryGasLimit uint64 `mapstructure:"query_gas_limit"` - // MemoryCacheSize in MiB not bytes - MemoryCacheSize uint32 `mapstructure:"memory_cache_size"` - // ContractDebugMode log what contract print - ContractDebugMode bool -} - -// DefaultWasmConfig returns the default settings for WasmConfig -func DefaultWasmConfig() WasmConfig { - return WasmConfig{ - SmartQueryGasLimit: defaultSmartQueryGasLimit, - MemoryCacheSize: defaultMemoryCacheSize, - ContractDebugMode: defaultContractDebugMode, - } -} - -// DefaultConfigTemplate toml snippet with default values for app.toml -func DefaultConfigTemplate() string { - return ConfigTemplate(DefaultWasmConfig()) -} - -// ConfigTemplate toml snippet for app.toml -func ConfigTemplate(c WasmConfig) string { - simGasLimit := `# simulation_gas_limit =` - if c.SimulationGasLimit != nil { - simGasLimit = fmt.Sprintf(`simulation_gas_limit = %d`, *c.SimulationGasLimit) - } - - return fmt.Sprintf(` -[wasm] -# Smart query gas limit is the max gas to be used in a smart query contract call -query_gas_limit = %d - -# in-memory cache for Wasm contracts. Set to 0 to disable. -# The value is in MiB not bytes -memory_cache_size = %d - -# Simulation gas limit is the max gas to be used in a tx simulation call. -# When not set the consensus max block gas is used instead -%s -`, c.SmartQueryGasLimit, c.MemoryCacheSize, simGasLimit) -} - -// VerifyAddressLen ensures that the address matches the expected length -func VerifyAddressLen() func(addr []byte) error { - return func(addr []byte) error { - if len(addr) != ContractAddrLen && len(addr) != SDKAddrLen { - return sdkerrors.ErrInvalidAddress - } - return nil - } -} - -// IsSubset will return true if the caller is the same as the superset, -// or if the caller is more restrictive than the superset. -func (a AccessType) IsSubset(superSet AccessType) bool { - switch superSet { - case AccessTypeEverybody: - // Everything is a subset of this - return a != AccessTypeUnspecified - case AccessTypeNobody: - // Only an exact match is a subset of this - return a == AccessTypeNobody - case AccessTypeOnlyAddress, AccessTypeAnyOfAddresses: - // Nobody or address(es) - return a == AccessTypeNobody || a == AccessTypeOnlyAddress || a == AccessTypeAnyOfAddresses - default: - return false - } -} - -// IsSubset will return true if the caller is the same as the superset, -// or if the caller is more restrictive than the superset. -func (a AccessConfig) IsSubset(superSet AccessConfig) bool { - switch superSet.Permission { - case AccessTypeOnlyAddress: - // An exact match or nobody - return a.Permission == AccessTypeNobody || (a.Permission == AccessTypeOnlyAddress && a.Address == superSet.Address) || - (a.Permission == AccessTypeAnyOfAddresses && isSubset([]string{superSet.Address}, a.Addresses)) - case AccessTypeAnyOfAddresses: - // An exact match or nobody - return a.Permission == AccessTypeNobody || (a.Permission == AccessTypeOnlyAddress && isSubset(superSet.Addresses, []string{a.Address})) || - a.Permission == AccessTypeAnyOfAddresses && isSubset(superSet.Addresses, a.Addresses) - case AccessTypeUnspecified: - return false - default: - return a.Permission.IsSubset(superSet.Permission) - } -} - -// return true when all elements in sub are also part of super -func isSubset(super, sub []string) bool { - if len(sub) == 0 { - return true - } - var matches int - for _, o := range sub { - for _, s := range super { - if o == s { - matches++ - break - } - } - } - return matches == len(sub) -} - -// AllAuthorizedAddresses returns the list of authorized addresses. Can be empty. -func (a AccessConfig) AllAuthorizedAddresses() []string { - switch a.Permission { - case AccessTypeAnyOfAddresses: - return a.Addresses - case AccessTypeOnlyAddress: - return []string{a.Address} - } - return []string{} -} diff --git a/x/wasm/types/types.pb.go b/x/wasm/types/types.pb.go deleted file mode 100644 index 2336b67..0000000 --- a/x/wasm/types/types.pb.go +++ /dev/null @@ -1,2548 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmwasm/wasm/v1/types.proto - -package types - -import ( - bytes "bytes" - fmt "fmt" - io "io" - math "math" - math_bits "math/bits" - - github_com_cometbft_cometbft_libs_bytes "github.com/cometbft/cometbft/libs/bytes" - _ "github.com/cosmos/cosmos-proto" - types "github.com/cosmos/cosmos-sdk/codec/types" - _ "github.com/cosmos/cosmos-sdk/types/tx/amino" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = proto.Marshal - _ = fmt.Errorf - _ = math.Inf -) - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// AccessType permission types -type AccessType int32 - -const ( - // AccessTypeUnspecified placeholder for empty value - AccessTypeUnspecified AccessType = 0 - // AccessTypeNobody forbidden - AccessTypeNobody AccessType = 1 - // AccessTypeOnlyAddress restricted to a single address - // Deprecated: use AccessTypeAnyOfAddresses instead - AccessTypeOnlyAddress AccessType = 2 - // AccessTypeEverybody unrestricted - AccessTypeEverybody AccessType = 3 - // AccessTypeAnyOfAddresses allow any of the addresses - AccessTypeAnyOfAddresses AccessType = 4 -) - -var AccessType_name = map[int32]string{ - 0: "ACCESS_TYPE_UNSPECIFIED", - 1: "ACCESS_TYPE_NOBODY", - 2: "ACCESS_TYPE_ONLY_ADDRESS", - 3: "ACCESS_TYPE_EVERYBODY", - 4: "ACCESS_TYPE_ANY_OF_ADDRESSES", -} - -var AccessType_value = map[string]int32{ - "ACCESS_TYPE_UNSPECIFIED": 0, - "ACCESS_TYPE_NOBODY": 1, - "ACCESS_TYPE_ONLY_ADDRESS": 2, - "ACCESS_TYPE_EVERYBODY": 3, - "ACCESS_TYPE_ANY_OF_ADDRESSES": 4, -} - -func (AccessType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_e6155d98fa173e02, []int{0} -} - -// ContractCodeHistoryOperationType actions that caused a code change -type ContractCodeHistoryOperationType int32 - -const ( - // ContractCodeHistoryOperationTypeUnspecified placeholder for empty value - ContractCodeHistoryOperationTypeUnspecified ContractCodeHistoryOperationType = 0 - // ContractCodeHistoryOperationTypeInit on chain contract instantiation - ContractCodeHistoryOperationTypeInit ContractCodeHistoryOperationType = 1 - // ContractCodeHistoryOperationTypeMigrate code migration - ContractCodeHistoryOperationTypeMigrate ContractCodeHistoryOperationType = 2 - // ContractCodeHistoryOperationTypeGenesis based on genesis data - ContractCodeHistoryOperationTypeGenesis ContractCodeHistoryOperationType = 3 -) - -var ContractCodeHistoryOperationType_name = map[int32]string{ - 0: "CONTRACT_CODE_HISTORY_OPERATION_TYPE_UNSPECIFIED", - 1: "CONTRACT_CODE_HISTORY_OPERATION_TYPE_INIT", - 2: "CONTRACT_CODE_HISTORY_OPERATION_TYPE_MIGRATE", - 3: "CONTRACT_CODE_HISTORY_OPERATION_TYPE_GENESIS", -} - -var ContractCodeHistoryOperationType_value = map[string]int32{ - "CONTRACT_CODE_HISTORY_OPERATION_TYPE_UNSPECIFIED": 0, - "CONTRACT_CODE_HISTORY_OPERATION_TYPE_INIT": 1, - "CONTRACT_CODE_HISTORY_OPERATION_TYPE_MIGRATE": 2, - "CONTRACT_CODE_HISTORY_OPERATION_TYPE_GENESIS": 3, -} - -func (x ContractCodeHistoryOperationType) String() string { - return proto.EnumName(ContractCodeHistoryOperationType_name, int32(x)) -} - -func (ContractCodeHistoryOperationType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_e6155d98fa173e02, []int{1} -} - -// AccessTypeParam -type AccessTypeParam struct { - Value AccessType `protobuf:"varint,1,opt,name=value,proto3,enum=cosmwasm.wasm.v1.AccessType" json:"value,omitempty" yaml:"value"` -} - -func (m *AccessTypeParam) Reset() { *m = AccessTypeParam{} } -func (m *AccessTypeParam) String() string { return proto.CompactTextString(m) } -func (*AccessTypeParam) ProtoMessage() {} -func (*AccessTypeParam) Descriptor() ([]byte, []int) { - return fileDescriptor_e6155d98fa173e02, []int{0} -} - -func (m *AccessTypeParam) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *AccessTypeParam) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AccessTypeParam.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *AccessTypeParam) XXX_Merge(src proto.Message) { - xxx_messageInfo_AccessTypeParam.Merge(m, src) -} - -func (m *AccessTypeParam) XXX_Size() int { - return m.Size() -} - -func (m *AccessTypeParam) XXX_DiscardUnknown() { - xxx_messageInfo_AccessTypeParam.DiscardUnknown(m) -} - -var xxx_messageInfo_AccessTypeParam proto.InternalMessageInfo - -// AccessConfig access control type. -type AccessConfig struct { - Permission AccessType `protobuf:"varint,1,opt,name=permission,proto3,enum=cosmwasm.wasm.v1.AccessType" json:"permission,omitempty" yaml:"permission"` - // Address - // Deprecated: replaced by addresses - Address string `protobuf:"bytes,2,opt,name=address,proto3" json:"address,omitempty" yaml:"address"` - Addresses []string `protobuf:"bytes,3,rep,name=addresses,proto3" json:"addresses,omitempty" yaml:"addresses"` -} - -func (m *AccessConfig) Reset() { *m = AccessConfig{} } -func (m *AccessConfig) String() string { return proto.CompactTextString(m) } -func (*AccessConfig) ProtoMessage() {} -func (*AccessConfig) Descriptor() ([]byte, []int) { - return fileDescriptor_e6155d98fa173e02, []int{1} -} - -func (m *AccessConfig) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *AccessConfig) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AccessConfig.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *AccessConfig) XXX_Merge(src proto.Message) { - xxx_messageInfo_AccessConfig.Merge(m, src) -} - -func (m *AccessConfig) XXX_Size() int { - return m.Size() -} - -func (m *AccessConfig) XXX_DiscardUnknown() { - xxx_messageInfo_AccessConfig.DiscardUnknown(m) -} - -var xxx_messageInfo_AccessConfig proto.InternalMessageInfo - -// Params defines the set of wasm parameters. -type Params struct { - CodeUploadAccess AccessConfig `protobuf:"bytes,1,opt,name=code_upload_access,json=codeUploadAccess,proto3" json:"code_upload_access" yaml:"code_upload_access"` - InstantiateDefaultPermission AccessType `protobuf:"varint,2,opt,name=instantiate_default_permission,json=instantiateDefaultPermission,proto3,enum=cosmwasm.wasm.v1.AccessType" json:"instantiate_default_permission,omitempty" yaml:"instantiate_default_permission"` -} - -func (m *Params) Reset() { *m = Params{} } -func (*Params) ProtoMessage() {} -func (*Params) Descriptor() ([]byte, []int) { - return fileDescriptor_e6155d98fa173e02, []int{2} -} - -func (m *Params) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *Params) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Params.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *Params) XXX_Merge(src proto.Message) { - xxx_messageInfo_Params.Merge(m, src) -} - -func (m *Params) XXX_Size() int { - return m.Size() -} - -func (m *Params) XXX_DiscardUnknown() { - xxx_messageInfo_Params.DiscardUnknown(m) -} - -var xxx_messageInfo_Params proto.InternalMessageInfo - -// CodeInfo is data for the uploaded contract WASM code -type CodeInfo struct { - // CodeHash is the unique identifier created by wasmvm - CodeHash []byte `protobuf:"bytes,1,opt,name=code_hash,json=codeHash,proto3" json:"code_hash,omitempty"` - // Creator address who initially stored the code - Creator string `protobuf:"bytes,2,opt,name=creator,proto3" json:"creator,omitempty"` - // InstantiateConfig access control to apply on contract creation, optional - InstantiateConfig AccessConfig `protobuf:"bytes,5,opt,name=instantiate_config,json=instantiateConfig,proto3" json:"instantiate_config"` -} - -func (m *CodeInfo) Reset() { *m = CodeInfo{} } -func (m *CodeInfo) String() string { return proto.CompactTextString(m) } -func (*CodeInfo) ProtoMessage() {} -func (*CodeInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_e6155d98fa173e02, []int{3} -} - -func (m *CodeInfo) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *CodeInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CodeInfo.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *CodeInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_CodeInfo.Merge(m, src) -} - -func (m *CodeInfo) XXX_Size() int { - return m.Size() -} - -func (m *CodeInfo) XXX_DiscardUnknown() { - xxx_messageInfo_CodeInfo.DiscardUnknown(m) -} - -var xxx_messageInfo_CodeInfo proto.InternalMessageInfo - -// ContractInfo stores a WASM contract instance -type ContractInfo struct { - // CodeID is the reference to the stored Wasm code - CodeID uint64 `protobuf:"varint,1,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` - // Creator address who initially instantiated the contract - Creator string `protobuf:"bytes,2,opt,name=creator,proto3" json:"creator,omitempty"` - // Admin is an optional address that can execute migrations - Admin string `protobuf:"bytes,3,opt,name=admin,proto3" json:"admin,omitempty"` - // Label is optional metadata to be stored with a contract instance. - Label string `protobuf:"bytes,4,opt,name=label,proto3" json:"label,omitempty"` - // Created Tx position when the contract was instantiated. - Created *AbsoluteTxPosition `protobuf:"bytes,5,opt,name=created,proto3" json:"created,omitempty"` - IBCPortID string `protobuf:"bytes,6,opt,name=ibc_port_id,json=ibcPortId,proto3" json:"ibc_port_id,omitempty"` - // Extension is an extension point to store custom metadata within the - // persistence model. - Extension *types.Any `protobuf:"bytes,7,opt,name=extension,proto3" json:"extension,omitempty"` -} - -func (m *ContractInfo) Reset() { *m = ContractInfo{} } -func (m *ContractInfo) String() string { return proto.CompactTextString(m) } -func (*ContractInfo) ProtoMessage() {} -func (*ContractInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_e6155d98fa173e02, []int{4} -} - -func (m *ContractInfo) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *ContractInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ContractInfo.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *ContractInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_ContractInfo.Merge(m, src) -} - -func (m *ContractInfo) XXX_Size() int { - return m.Size() -} - -func (m *ContractInfo) XXX_DiscardUnknown() { - xxx_messageInfo_ContractInfo.DiscardUnknown(m) -} - -var xxx_messageInfo_ContractInfo proto.InternalMessageInfo - -// ContractCodeHistoryEntry metadata to a contract. -type ContractCodeHistoryEntry struct { - Operation ContractCodeHistoryOperationType `protobuf:"varint,1,opt,name=operation,proto3,enum=cosmwasm.wasm.v1.ContractCodeHistoryOperationType" json:"operation,omitempty"` - // CodeID is the reference to the stored WASM code - CodeID uint64 `protobuf:"varint,2,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` - // Updated Tx position when the operation was executed. - Updated *AbsoluteTxPosition `protobuf:"bytes,3,opt,name=updated,proto3" json:"updated,omitempty"` - Msg RawContractMessage `protobuf:"bytes,4,opt,name=msg,proto3,casttype=RawContractMessage" json:"msg,omitempty"` -} - -func (m *ContractCodeHistoryEntry) Reset() { *m = ContractCodeHistoryEntry{} } -func (m *ContractCodeHistoryEntry) String() string { return proto.CompactTextString(m) } -func (*ContractCodeHistoryEntry) ProtoMessage() {} -func (*ContractCodeHistoryEntry) Descriptor() ([]byte, []int) { - return fileDescriptor_e6155d98fa173e02, []int{5} -} - -func (m *ContractCodeHistoryEntry) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *ContractCodeHistoryEntry) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ContractCodeHistoryEntry.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *ContractCodeHistoryEntry) XXX_Merge(src proto.Message) { - xxx_messageInfo_ContractCodeHistoryEntry.Merge(m, src) -} - -func (m *ContractCodeHistoryEntry) XXX_Size() int { - return m.Size() -} - -func (m *ContractCodeHistoryEntry) XXX_DiscardUnknown() { - xxx_messageInfo_ContractCodeHistoryEntry.DiscardUnknown(m) -} - -var xxx_messageInfo_ContractCodeHistoryEntry proto.InternalMessageInfo - -// AbsoluteTxPosition is a unique transaction position that allows for global -// ordering of transactions. -type AbsoluteTxPosition struct { - // BlockHeight is the block the contract was created at - BlockHeight uint64 `protobuf:"varint,1,opt,name=block_height,json=blockHeight,proto3" json:"block_height,omitempty"` - // TxIndex is a monotonic counter within the block (actual transaction index, - // or gas consumed) - TxIndex uint64 `protobuf:"varint,2,opt,name=tx_index,json=txIndex,proto3" json:"tx_index,omitempty"` -} - -func (m *AbsoluteTxPosition) Reset() { *m = AbsoluteTxPosition{} } -func (m *AbsoluteTxPosition) String() string { return proto.CompactTextString(m) } -func (*AbsoluteTxPosition) ProtoMessage() {} -func (*AbsoluteTxPosition) Descriptor() ([]byte, []int) { - return fileDescriptor_e6155d98fa173e02, []int{6} -} - -func (m *AbsoluteTxPosition) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *AbsoluteTxPosition) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AbsoluteTxPosition.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *AbsoluteTxPosition) XXX_Merge(src proto.Message) { - xxx_messageInfo_AbsoluteTxPosition.Merge(m, src) -} - -func (m *AbsoluteTxPosition) XXX_Size() int { - return m.Size() -} - -func (m *AbsoluteTxPosition) XXX_DiscardUnknown() { - xxx_messageInfo_AbsoluteTxPosition.DiscardUnknown(m) -} - -var xxx_messageInfo_AbsoluteTxPosition proto.InternalMessageInfo - -// Model is a struct that holds a KV pair -type Model struct { - // hex-encode key to read it better (this is often ascii) - Key github_com_cometbft_cometbft_libs_bytes.HexBytes `protobuf:"bytes,1,opt,name=key,proto3,casttype=github.com/cometbft/cometbft/libs/bytes.HexBytes" json:"key,omitempty"` - // base64-encode raw value - Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` -} - -func (m *Model) Reset() { *m = Model{} } -func (m *Model) String() string { return proto.CompactTextString(m) } -func (*Model) ProtoMessage() {} -func (*Model) Descriptor() ([]byte, []int) { - return fileDescriptor_e6155d98fa173e02, []int{7} -} - -func (m *Model) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *Model) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Model.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *Model) XXX_Merge(src proto.Message) { - xxx_messageInfo_Model.Merge(m, src) -} - -func (m *Model) XXX_Size() int { - return m.Size() -} - -func (m *Model) XXX_DiscardUnknown() { - xxx_messageInfo_Model.DiscardUnknown(m) -} - -var xxx_messageInfo_Model proto.InternalMessageInfo - -func init() { - proto.RegisterEnum("cosmwasm.wasm.v1.AccessType", AccessType_name, AccessType_value) - proto.RegisterEnum("cosmwasm.wasm.v1.ContractCodeHistoryOperationType", ContractCodeHistoryOperationType_name, ContractCodeHistoryOperationType_value) - proto.RegisterType((*AccessTypeParam)(nil), "cosmwasm.wasm.v1.AccessTypeParam") - proto.RegisterType((*AccessConfig)(nil), "cosmwasm.wasm.v1.AccessConfig") - proto.RegisterType((*Params)(nil), "cosmwasm.wasm.v1.Params") - proto.RegisterType((*CodeInfo)(nil), "cosmwasm.wasm.v1.CodeInfo") - proto.RegisterType((*ContractInfo)(nil), "cosmwasm.wasm.v1.ContractInfo") - proto.RegisterType((*ContractCodeHistoryEntry)(nil), "cosmwasm.wasm.v1.ContractCodeHistoryEntry") - proto.RegisterType((*AbsoluteTxPosition)(nil), "cosmwasm.wasm.v1.AbsoluteTxPosition") - proto.RegisterType((*Model)(nil), "cosmwasm.wasm.v1.Model") -} - -func init() { proto.RegisterFile("cosmwasm/wasm/v1/types.proto", fileDescriptor_e6155d98fa173e02) } - -var fileDescriptor_e6155d98fa173e02 = []byte{ - // 1205 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x56, 0xcd, 0x8f, 0xdb, 0x44, - 0x14, 0x8f, 0x93, 0xec, 0x47, 0xa6, 0x4b, 0x71, 0x87, 0x2d, 0xcd, 0x86, 0x55, 0x12, 0x4c, 0x29, - 0xdb, 0x6d, 0x37, 0x69, 0x17, 0x04, 0x52, 0x0f, 0x95, 0xf2, 0xe1, 0x76, 0x5d, 0xb1, 0x71, 0x34, - 0x49, 0x81, 0x45, 0x2a, 0x96, 0x63, 0x4f, 0xb2, 0x56, 0x13, 0x4f, 0xe4, 0x99, 0x6c, 0xe3, 0xff, - 0x00, 0x45, 0x42, 0xe2, 0xc0, 0x81, 0x4b, 0x24, 0x24, 0x10, 0x94, 0x1b, 0x07, 0xfe, 0x88, 0x0a, - 0x24, 0xd4, 0x23, 0xa7, 0x08, 0xb6, 0x07, 0x38, 0xe7, 0x58, 0x2e, 0xc8, 0x33, 0x49, 0x6d, 0xfa, - 0xb5, 0xe1, 0x62, 0xcd, 0xbc, 0xf7, 0x7e, 0xbf, 0xf7, 0xde, 0x6f, 0x66, 0x9e, 0x0c, 0x36, 0x2d, - 0x42, 0x7b, 0xf7, 0x4c, 0xda, 0x2b, 0xf2, 0xcf, 0xd1, 0xd5, 0x22, 0xf3, 0xfb, 0x98, 0x16, 0xfa, - 0x1e, 0x61, 0x04, 0xca, 0x73, 0x6f, 0x81, 0x7f, 0x8e, 0xae, 0x66, 0x36, 0x02, 0x0b, 0xa1, 0x06, - 0xf7, 0x17, 0xc5, 0x46, 0x04, 0x67, 0xd6, 0x3b, 0xa4, 0x43, 0x84, 0x3d, 0x58, 0xcd, 0xac, 0x1b, - 0x1d, 0x42, 0x3a, 0x5d, 0x5c, 0xe4, 0xbb, 0xd6, 0xa0, 0x5d, 0x34, 0x5d, 0x7f, 0xe6, 0x3a, 0x63, - 0xf6, 0x1c, 0x97, 0x14, 0xf9, 0x57, 0x98, 0x94, 0x3b, 0xe0, 0xd5, 0x92, 0x65, 0x61, 0x4a, 0x9b, - 0x7e, 0x1f, 0xd7, 0x4d, 0xcf, 0xec, 0xc1, 0x2a, 0x58, 0x3a, 0x32, 0xbb, 0x03, 0x9c, 0x96, 0xf2, - 0xd2, 0xd6, 0xe9, 0xdd, 0xcd, 0xc2, 0xd3, 0x35, 0x15, 0x42, 0x44, 0x59, 0x9e, 0x4e, 0x72, 0x6b, - 0xbe, 0xd9, 0xeb, 0x5e, 0x53, 0x38, 0x48, 0x41, 0x02, 0x7c, 0x2d, 0xf9, 0xf5, 0x37, 0x39, 0x49, - 0xf9, 0x55, 0x02, 0x6b, 0x22, 0xba, 0x42, 0xdc, 0xb6, 0xd3, 0x81, 0x0d, 0x00, 0xfa, 0xd8, 0xeb, - 0x39, 0x94, 0x3a, 0xc4, 0x5d, 0x28, 0xc3, 0xd9, 0xe9, 0x24, 0x77, 0x46, 0x64, 0x08, 0x91, 0x0a, - 0x8a, 0xd0, 0xc0, 0xcb, 0x60, 0xc5, 0xb4, 0x6d, 0x0f, 0x53, 0x9a, 0x8e, 0xe7, 0xa5, 0xad, 0x54, - 0x19, 0x4e, 0x27, 0xb9, 0xd3, 0x02, 0x33, 0x73, 0x28, 0x68, 0x1e, 0x02, 0x77, 0x41, 0x6a, 0xb6, - 0xc4, 0x34, 0x9d, 0xc8, 0x27, 0xb6, 0x52, 0xe5, 0xf5, 0xe9, 0x24, 0x27, 0xff, 0x27, 0x1e, 0x53, - 0x05, 0x85, 0x61, 0xb3, 0x6e, 0xbe, 0x8a, 0x83, 0x65, 0xae, 0x11, 0x85, 0x0c, 0x40, 0x8b, 0xd8, - 0xd8, 0x18, 0xf4, 0xbb, 0xc4, 0xb4, 0x0d, 0x93, 0xd7, 0xcb, 0xfb, 0x39, 0xb5, 0x9b, 0x7d, 0x51, - 0x3f, 0x42, 0x83, 0xf2, 0x85, 0x07, 0x93, 0x5c, 0x6c, 0x3a, 0xc9, 0x6d, 0x88, 0x8c, 0xcf, 0xf2, - 0x28, 0xf7, 0xff, 0xfa, 0x69, 0x5b, 0x42, 0x72, 0xe0, 0xb9, 0xcd, 0x1d, 0x02, 0x0f, 0xbf, 0x90, - 0x40, 0xd6, 0x71, 0x29, 0x33, 0x5d, 0xe6, 0x98, 0x0c, 0x1b, 0x36, 0x6e, 0x9b, 0x83, 0x2e, 0x33, - 0x22, 0x92, 0xc6, 0x17, 0x90, 0xf4, 0xe2, 0x74, 0x92, 0x7b, 0x5b, 0x24, 0x7f, 0x39, 0x9b, 0x82, - 0x36, 0x23, 0x01, 0x55, 0xe1, 0xaf, 0x3f, 0x71, 0x73, 0x59, 0x62, 0xca, 0x0f, 0x12, 0x58, 0xad, - 0x10, 0x1b, 0x6b, 0x6e, 0x9b, 0xc0, 0x37, 0x40, 0x8a, 0x37, 0x74, 0x68, 0xd2, 0x43, 0xae, 0xc7, - 0x1a, 0x5a, 0x0d, 0x0c, 0x7b, 0x26, 0x3d, 0x84, 0x69, 0xb0, 0x62, 0x79, 0xd8, 0x64, 0xc4, 0x13, - 0x07, 0x85, 0xe6, 0x5b, 0xf8, 0x09, 0x80, 0xd1, 0x52, 0x2c, 0xae, 0x54, 0x7a, 0x69, 0x21, 0x3d, - 0x53, 0x81, 0x9e, 0x42, 0xb2, 0x33, 0x11, 0x12, 0xe1, 0xbd, 0x95, 0x5c, 0x4d, 0xc8, 0xc9, 0x5b, - 0xc9, 0xd5, 0xa4, 0xbc, 0xa4, 0xfc, 0x16, 0x07, 0x6b, 0x15, 0xe2, 0x32, 0xcf, 0xb4, 0x18, 0xaf, - 0xf6, 0x2d, 0xb0, 0xc2, 0xab, 0x75, 0x6c, 0x5e, 0x6b, 0xb2, 0x0c, 0x8e, 0x27, 0xb9, 0x65, 0xde, - 0x4c, 0x15, 0x2d, 0x07, 0x2e, 0xcd, 0x7e, 0x49, 0xd5, 0xeb, 0x60, 0xc9, 0xb4, 0x7b, 0x8e, 0x9b, - 0x4e, 0x70, 0xbb, 0xd8, 0x04, 0xd6, 0xae, 0xd9, 0xc2, 0xdd, 0x74, 0x52, 0x58, 0xf9, 0x06, 0x5e, - 0x9f, 0xb1, 0x60, 0x7b, 0xd6, 0xd6, 0xf9, 0xe7, 0xb4, 0xd5, 0xa2, 0xa4, 0x3b, 0x60, 0xb8, 0x39, - 0xac, 0x13, 0xea, 0x30, 0x87, 0xb8, 0x68, 0x0e, 0x82, 0x3b, 0xe0, 0x94, 0xd3, 0xb2, 0x8c, 0x3e, - 0xf1, 0x58, 0x50, 0xee, 0x32, 0xbf, 0xe8, 0xaf, 0x1c, 0x4f, 0x72, 0x29, 0xad, 0x5c, 0xa9, 0x13, - 0x8f, 0x69, 0x55, 0x94, 0x72, 0x5a, 0x16, 0x5f, 0xda, 0xf0, 0x33, 0x90, 0xc2, 0x43, 0x86, 0x5d, - 0x7e, 0x29, 0x56, 0x78, 0xc2, 0xf5, 0x82, 0x18, 0x0d, 0x85, 0xf9, 0x68, 0x28, 0x94, 0x5c, 0xbf, - 0xbc, 0xfd, 0xcb, 0xcf, 0x3b, 0x17, 0x9e, 0xa9, 0x24, 0xaa, 0x92, 0x3a, 0xe7, 0x41, 0x21, 0xe5, - 0xb5, 0xe4, 0xdf, 0xc1, 0x8b, 0xf8, 0x47, 0x02, 0xe9, 0x79, 0x68, 0xa0, 0xda, 0x9e, 0x43, 0x19, - 0xf1, 0x7c, 0xd5, 0x65, 0x9e, 0x0f, 0xeb, 0x20, 0x45, 0xfa, 0xd8, 0x33, 0x59, 0xf8, 0xd4, 0x77, - 0x0b, 0x2f, 0xcc, 0x14, 0x81, 0xeb, 0x73, 0x54, 0x70, 0x5b, 0x51, 0x48, 0x12, 0x3d, 0xae, 0xf8, - 0x0b, 0x8f, 0xeb, 0x3a, 0x58, 0x19, 0xf4, 0x6d, 0x2e, 0x74, 0xe2, 0xff, 0x08, 0x3d, 0x03, 0xc1, - 0x2d, 0x90, 0xe8, 0xd1, 0x0e, 0x3f, 0xbc, 0xb5, 0xf2, 0xeb, 0x8f, 0x27, 0x39, 0x88, 0xcc, 0x7b, - 0xf3, 0x2a, 0xf7, 0x31, 0xa5, 0x66, 0x07, 0xa3, 0x20, 0x44, 0x41, 0x00, 0x3e, 0x4b, 0x04, 0xdf, - 0x04, 0x6b, 0xad, 0x2e, 0xb1, 0xee, 0x1a, 0x87, 0xd8, 0xe9, 0x1c, 0x32, 0x71, 0xb1, 0xd0, 0x29, - 0x6e, 0xdb, 0xe3, 0x26, 0xb8, 0x01, 0x56, 0xd9, 0xd0, 0x70, 0x5c, 0x1b, 0x0f, 0x45, 0x23, 0x68, - 0x85, 0x0d, 0xb5, 0x60, 0xab, 0x60, 0xb0, 0xb4, 0x4f, 0x6c, 0xdc, 0x85, 0x37, 0x40, 0xe2, 0x2e, - 0xf6, 0xc5, 0x13, 0x2a, 0xbf, 0xf7, 0x78, 0x92, 0xbb, 0xd2, 0x71, 0xd8, 0xe1, 0xa0, 0x55, 0xb0, - 0x48, 0xaf, 0x68, 0x91, 0x1e, 0x66, 0xad, 0x36, 0x0b, 0x17, 0x5d, 0xa7, 0x45, 0x8b, 0x2d, 0x9f, - 0x61, 0x5a, 0xd8, 0xc3, 0xc3, 0x72, 0xb0, 0x40, 0x01, 0x41, 0x70, 0x1b, 0xc5, 0x38, 0x8f, 0xf3, - 0xc7, 0x28, 0x36, 0xdb, 0x3f, 0xc6, 0x01, 0x08, 0x27, 0x02, 0x7c, 0x1f, 0x9c, 0x2b, 0x55, 0x2a, - 0x6a, 0xa3, 0x61, 0x34, 0x0f, 0xea, 0xaa, 0x71, 0xbb, 0xd6, 0xa8, 0xab, 0x15, 0xed, 0x86, 0xa6, - 0x56, 0xe5, 0x58, 0x66, 0x63, 0x34, 0xce, 0x9f, 0x0d, 0x83, 0x6f, 0xbb, 0xb4, 0x8f, 0x2d, 0xa7, - 0xed, 0x60, 0x1b, 0x5e, 0x06, 0x30, 0x8a, 0xab, 0xe9, 0x65, 0xbd, 0x7a, 0x20, 0x4b, 0x99, 0xf5, - 0xd1, 0x38, 0x2f, 0x87, 0x90, 0x1a, 0x69, 0x11, 0xdb, 0x87, 0x1f, 0x80, 0x74, 0x34, 0x5a, 0xaf, - 0x7d, 0x78, 0x60, 0x94, 0xaa, 0x55, 0xa4, 0x36, 0x1a, 0x72, 0xfc, 0xe9, 0x34, 0xba, 0xdb, 0xf5, - 0x4b, 0x4f, 0x46, 0xf6, 0xd9, 0x28, 0x50, 0xfd, 0x48, 0x45, 0x07, 0x3c, 0x53, 0x22, 0x73, 0x6e, - 0x34, 0xce, 0xbf, 0x16, 0xa2, 0xd4, 0x23, 0xec, 0xf9, 0x3c, 0xd9, 0x75, 0xb0, 0x19, 0xc5, 0x94, - 0x6a, 0x07, 0x86, 0x7e, 0x63, 0x9e, 0x4e, 0x6d, 0xc8, 0xc9, 0xcc, 0xe6, 0x68, 0x9c, 0x4f, 0x87, - 0xd0, 0x92, 0xeb, 0xeb, 0xed, 0xd2, 0x7c, 0xe4, 0x67, 0x56, 0x3f, 0xff, 0x36, 0x1b, 0xbb, 0xff, - 0x5d, 0x36, 0xb6, 0xfd, 0x7d, 0x02, 0xe4, 0x4f, 0xba, 0xa5, 0x10, 0x83, 0x2b, 0x15, 0xbd, 0xd6, - 0x44, 0xa5, 0x4a, 0xd3, 0xa8, 0xe8, 0x55, 0xd5, 0xd8, 0xd3, 0x1a, 0x4d, 0x1d, 0x1d, 0x18, 0x7a, - 0x5d, 0x45, 0xa5, 0xa6, 0xa6, 0xd7, 0x9e, 0x27, 0x6d, 0x71, 0x34, 0xce, 0x5f, 0x3a, 0x89, 0x3b, - 0x2a, 0xf8, 0xc7, 0xe0, 0xe2, 0x42, 0x69, 0xb4, 0x9a, 0xd6, 0x94, 0xa5, 0xcc, 0xd6, 0x68, 0x9c, - 0x3f, 0x7f, 0x12, 0xbf, 0xe6, 0x3a, 0x0c, 0xde, 0x01, 0x97, 0x17, 0x22, 0xde, 0xd7, 0x6e, 0xa2, - 0x52, 0x53, 0x95, 0xe3, 0x99, 0x4b, 0xa3, 0x71, 0xfe, 0x9d, 0x93, 0xb8, 0xf7, 0x9d, 0x8e, 0x67, - 0x32, 0xbc, 0x30, 0xfd, 0x4d, 0xb5, 0xa6, 0x36, 0xb4, 0x86, 0x9c, 0x58, 0x8c, 0xfe, 0x26, 0x76, - 0x31, 0x75, 0x68, 0x26, 0x19, 0x1c, 0x56, 0x59, 0x7f, 0xf0, 0x67, 0x36, 0x76, 0xff, 0x38, 0x2b, - 0x3d, 0x38, 0xce, 0x4a, 0x0f, 0x8f, 0xb3, 0xd2, 0x1f, 0xc7, 0x59, 0xe9, 0xcb, 0x47, 0xd9, 0xd8, - 0xc3, 0x47, 0xd9, 0xd8, 0xef, 0x8f, 0xb2, 0xb1, 0x4f, 0x77, 0x22, 0x6f, 0x88, 0x61, 0xaf, 0xef, - 0x62, 0x76, 0x8f, 0x78, 0x77, 0xf9, 0x7a, 0xc7, 0x22, 0x1e, 0x2e, 0x0e, 0xc5, 0x7f, 0x19, 0xff, - 0x29, 0x6b, 0x2d, 0xf3, 0x49, 0xf9, 0xee, 0xbf, 0x01, 0x00, 0x00, 0xff, 0xff, 0xef, 0xa9, 0x45, - 0x98, 0xb5, 0x09, 0x00, 0x00, -} - -func (this *AccessTypeParam) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*AccessTypeParam) - if !ok { - that2, ok := that.(AccessTypeParam) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Value != that1.Value { - return false - } - return true -} - -func (this *AccessConfig) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*AccessConfig) - if !ok { - that2, ok := that.(AccessConfig) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Permission != that1.Permission { - return false - } - if this.Address != that1.Address { - return false - } - if len(this.Addresses) != len(that1.Addresses) { - return false - } - for i := range this.Addresses { - if this.Addresses[i] != that1.Addresses[i] { - return false - } - } - return true -} - -func (this *Params) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*Params) - if !ok { - that2, ok := that.(Params) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if !this.CodeUploadAccess.Equal(&that1.CodeUploadAccess) { - return false - } - if this.InstantiateDefaultPermission != that1.InstantiateDefaultPermission { - return false - } - return true -} - -func (this *CodeInfo) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*CodeInfo) - if !ok { - that2, ok := that.(CodeInfo) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if !bytes.Equal(this.CodeHash, that1.CodeHash) { - return false - } - if this.Creator != that1.Creator { - return false - } - if !this.InstantiateConfig.Equal(&that1.InstantiateConfig) { - return false - } - return true -} - -func (this *ContractInfo) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*ContractInfo) - if !ok { - that2, ok := that.(ContractInfo) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.CodeID != that1.CodeID { - return false - } - if this.Creator != that1.Creator { - return false - } - if this.Admin != that1.Admin { - return false - } - if this.Label != that1.Label { - return false - } - if !this.Created.Equal(that1.Created) { - return false - } - if this.IBCPortID != that1.IBCPortID { - return false - } - if !this.Extension.Equal(that1.Extension) { - return false - } - return true -} - -func (this *ContractCodeHistoryEntry) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*ContractCodeHistoryEntry) - if !ok { - that2, ok := that.(ContractCodeHistoryEntry) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Operation != that1.Operation { - return false - } - if this.CodeID != that1.CodeID { - return false - } - if !this.Updated.Equal(that1.Updated) { - return false - } - if !bytes.Equal(this.Msg, that1.Msg) { - return false - } - return true -} - -func (this *AbsoluteTxPosition) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*AbsoluteTxPosition) - if !ok { - that2, ok := that.(AbsoluteTxPosition) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.BlockHeight != that1.BlockHeight { - return false - } - if this.TxIndex != that1.TxIndex { - return false - } - return true -} - -func (this *Model) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*Model) - if !ok { - that2, ok := that.(Model) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if !bytes.Equal(this.Key, that1.Key) { - return false - } - if !bytes.Equal(this.Value, that1.Value) { - return false - } - return true -} - -func (m *AccessTypeParam) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *AccessTypeParam) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AccessTypeParam) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Value != 0 { - i = encodeVarintTypes(dAtA, i, uint64(m.Value)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *AccessConfig) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *AccessConfig) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AccessConfig) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Addresses) > 0 { - for iNdEx := len(m.Addresses) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.Addresses[iNdEx]) - copy(dAtA[i:], m.Addresses[iNdEx]) - i = encodeVarintTypes(dAtA, i, uint64(len(m.Addresses[iNdEx]))) - i-- - dAtA[i] = 0x1a - } - } - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintTypes(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0x12 - } - if m.Permission != 0 { - i = encodeVarintTypes(dAtA, i, uint64(m.Permission)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *Params) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Params) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.InstantiateDefaultPermission != 0 { - i = encodeVarintTypes(dAtA, i, uint64(m.InstantiateDefaultPermission)) - i-- - dAtA[i] = 0x10 - } - { - size, err := m.CodeUploadAccess.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTypes(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *CodeInfo) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *CodeInfo) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CodeInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.InstantiateConfig.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTypes(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - if len(m.Creator) > 0 { - i -= len(m.Creator) - copy(dAtA[i:], m.Creator) - i = encodeVarintTypes(dAtA, i, uint64(len(m.Creator))) - i-- - dAtA[i] = 0x12 - } - if len(m.CodeHash) > 0 { - i -= len(m.CodeHash) - copy(dAtA[i:], m.CodeHash) - i = encodeVarintTypes(dAtA, i, uint64(len(m.CodeHash))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *ContractInfo) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *ContractInfo) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ContractInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Extension != nil { - { - size, err := m.Extension.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTypes(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - } - if len(m.IBCPortID) > 0 { - i -= len(m.IBCPortID) - copy(dAtA[i:], m.IBCPortID) - i = encodeVarintTypes(dAtA, i, uint64(len(m.IBCPortID))) - i-- - dAtA[i] = 0x32 - } - if m.Created != nil { - { - size, err := m.Created.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTypes(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - } - if len(m.Label) > 0 { - i -= len(m.Label) - copy(dAtA[i:], m.Label) - i = encodeVarintTypes(dAtA, i, uint64(len(m.Label))) - i-- - dAtA[i] = 0x22 - } - if len(m.Admin) > 0 { - i -= len(m.Admin) - copy(dAtA[i:], m.Admin) - i = encodeVarintTypes(dAtA, i, uint64(len(m.Admin))) - i-- - dAtA[i] = 0x1a - } - if len(m.Creator) > 0 { - i -= len(m.Creator) - copy(dAtA[i:], m.Creator) - i = encodeVarintTypes(dAtA, i, uint64(len(m.Creator))) - i-- - dAtA[i] = 0x12 - } - if m.CodeID != 0 { - i = encodeVarintTypes(dAtA, i, uint64(m.CodeID)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *ContractCodeHistoryEntry) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *ContractCodeHistoryEntry) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ContractCodeHistoryEntry) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Msg) > 0 { - i -= len(m.Msg) - copy(dAtA[i:], m.Msg) - i = encodeVarintTypes(dAtA, i, uint64(len(m.Msg))) - i-- - dAtA[i] = 0x22 - } - if m.Updated != nil { - { - size, err := m.Updated.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTypes(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - if m.CodeID != 0 { - i = encodeVarintTypes(dAtA, i, uint64(m.CodeID)) - i-- - dAtA[i] = 0x10 - } - if m.Operation != 0 { - i = encodeVarintTypes(dAtA, i, uint64(m.Operation)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *AbsoluteTxPosition) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *AbsoluteTxPosition) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AbsoluteTxPosition) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.TxIndex != 0 { - i = encodeVarintTypes(dAtA, i, uint64(m.TxIndex)) - i-- - dAtA[i] = 0x10 - } - if m.BlockHeight != 0 { - i = encodeVarintTypes(dAtA, i, uint64(m.BlockHeight)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *Model) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Model) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Model) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Value) > 0 { - i -= len(m.Value) - copy(dAtA[i:], m.Value) - i = encodeVarintTypes(dAtA, i, uint64(len(m.Value))) - i-- - dAtA[i] = 0x12 - } - if len(m.Key) > 0 { - i -= len(m.Key) - copy(dAtA[i:], m.Key) - i = encodeVarintTypes(dAtA, i, uint64(len(m.Key))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintTypes(dAtA []byte, offset int, v uint64) int { - offset -= sovTypes(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} - -func (m *AccessTypeParam) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Value != 0 { - n += 1 + sovTypes(uint64(m.Value)) - } - return n -} - -func (m *AccessConfig) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Permission != 0 { - n += 1 + sovTypes(uint64(m.Permission)) - } - l = len(m.Address) - if l > 0 { - n += 1 + l + sovTypes(uint64(l)) - } - if len(m.Addresses) > 0 { - for _, s := range m.Addresses { - l = len(s) - n += 1 + l + sovTypes(uint64(l)) - } - } - return n -} - -func (m *Params) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.CodeUploadAccess.Size() - n += 1 + l + sovTypes(uint64(l)) - if m.InstantiateDefaultPermission != 0 { - n += 1 + sovTypes(uint64(m.InstantiateDefaultPermission)) - } - return n -} - -func (m *CodeInfo) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.CodeHash) - if l > 0 { - n += 1 + l + sovTypes(uint64(l)) - } - l = len(m.Creator) - if l > 0 { - n += 1 + l + sovTypes(uint64(l)) - } - l = m.InstantiateConfig.Size() - n += 1 + l + sovTypes(uint64(l)) - return n -} - -func (m *ContractInfo) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.CodeID != 0 { - n += 1 + sovTypes(uint64(m.CodeID)) - } - l = len(m.Creator) - if l > 0 { - n += 1 + l + sovTypes(uint64(l)) - } - l = len(m.Admin) - if l > 0 { - n += 1 + l + sovTypes(uint64(l)) - } - l = len(m.Label) - if l > 0 { - n += 1 + l + sovTypes(uint64(l)) - } - if m.Created != nil { - l = m.Created.Size() - n += 1 + l + sovTypes(uint64(l)) - } - l = len(m.IBCPortID) - if l > 0 { - n += 1 + l + sovTypes(uint64(l)) - } - if m.Extension != nil { - l = m.Extension.Size() - n += 1 + l + sovTypes(uint64(l)) - } - return n -} - -func (m *ContractCodeHistoryEntry) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Operation != 0 { - n += 1 + sovTypes(uint64(m.Operation)) - } - if m.CodeID != 0 { - n += 1 + sovTypes(uint64(m.CodeID)) - } - if m.Updated != nil { - l = m.Updated.Size() - n += 1 + l + sovTypes(uint64(l)) - } - l = len(m.Msg) - if l > 0 { - n += 1 + l + sovTypes(uint64(l)) - } - return n -} - -func (m *AbsoluteTxPosition) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.BlockHeight != 0 { - n += 1 + sovTypes(uint64(m.BlockHeight)) - } - if m.TxIndex != 0 { - n += 1 + sovTypes(uint64(m.TxIndex)) - } - return n -} - -func (m *Model) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Key) - if l > 0 { - n += 1 + l + sovTypes(uint64(l)) - } - l = len(m.Value) - if l > 0 { - n += 1 + l + sovTypes(uint64(l)) - } - return n -} - -func sovTypes(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} - -func sozTypes(x uint64) (n int) { - return sovTypes(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} - -func (m *AccessTypeParam) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: AccessTypeParam: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AccessTypeParam: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - m.Value = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Value |= AccessType(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipTypes(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTypes - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *AccessConfig) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: AccessConfig: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AccessConfig: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Permission", wireType) - } - m.Permission = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Permission |= AccessType(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTypes - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Addresses", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTypes - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Addresses = append(m.Addresses, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTypes(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTypes - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *Params) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Params: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Params: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeUploadAccess", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTypes - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.CodeUploadAccess.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field InstantiateDefaultPermission", wireType) - } - m.InstantiateDefaultPermission = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.InstantiateDefaultPermission |= AccessType(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipTypes(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTypes - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *CodeInfo) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CodeInfo: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CodeInfo: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeHash", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTypes - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CodeHash = append(m.CodeHash[:0], dAtA[iNdEx:postIndex]...) - if m.CodeHash == nil { - m.CodeHash = []byte{} - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Creator", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTypes - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Creator = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field InstantiateConfig", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTypes - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.InstantiateConfig.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTypes(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTypes - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *ContractInfo) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: ContractInfo: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ContractInfo: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) - } - m.CodeID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CodeID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Creator", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTypes - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Creator = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Admin", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTypes - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Admin = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Label", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTypes - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Label = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Created", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTypes - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Created == nil { - m.Created = &AbsoluteTxPosition{} - } - if err := m.Created.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IBCPortID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTypes - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.IBCPortID = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Extension", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTypes - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Extension == nil { - m.Extension = &types.Any{} - } - if err := m.Extension.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTypes(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTypes - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *ContractCodeHistoryEntry) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: ContractCodeHistoryEntry: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ContractCodeHistoryEntry: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Operation", wireType) - } - m.Operation = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Operation |= ContractCodeHistoryOperationType(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) - } - m.CodeID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CodeID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Updated", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTypes - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Updated == nil { - m.Updated = &AbsoluteTxPosition{} - } - if err := m.Updated.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTypes - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Msg = append(m.Msg[:0], dAtA[iNdEx:postIndex]...) - if m.Msg == nil { - m.Msg = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTypes(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTypes - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *AbsoluteTxPosition) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: AbsoluteTxPosition: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AbsoluteTxPosition: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field BlockHeight", wireType) - } - m.BlockHeight = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.BlockHeight |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TxIndex", wireType) - } - m.TxIndex = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.TxIndex |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipTypes(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTypes - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *Model) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Model: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Model: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTypes - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Key = append(m.Key[:0], dAtA[iNdEx:postIndex]...) - if m.Key == nil { - m.Key = []byte{} - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTypes - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Value = append(m.Value[:0], dAtA[iNdEx:postIndex]...) - if m.Value == nil { - m.Value = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTypes(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTypes - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func skipTypes(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTypes - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTypes - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTypes - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthTypes - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTypes - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTypes - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTypes = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTypes = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTypes = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/wasm/types/types_test.go b/x/wasm/types/types_test.go deleted file mode 100644 index 3221c00..0000000 --- a/x/wasm/types/types_test.go +++ /dev/null @@ -1,751 +0,0 @@ -package types - -import ( - "bytes" - "context" - "strings" - "testing" - "time" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/cometbft/cometbft/libs/rand" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestContractInfoValidateBasic(t *testing.T) { - specs := map[string]struct { - srcMutator func(*ContractInfo) - expError bool - }{ - "all good": {srcMutator: func(_ *ContractInfo) {}}, - "code id empty": { - srcMutator: func(c *ContractInfo) { c.CodeID = 0 }, - expError: true, - }, - "creator empty": { - srcMutator: func(c *ContractInfo) { c.Creator = "" }, - expError: true, - }, - "creator not an address": { - srcMutator: func(c *ContractInfo) { c.Creator = invalidAddress }, - expError: true, - }, - "admin empty": { - srcMutator: func(c *ContractInfo) { c.Admin = "" }, - expError: false, - }, - "admin not an address": { - srcMutator: func(c *ContractInfo) { c.Admin = invalidAddress }, - expError: true, - }, - "label empty": { - srcMutator: func(c *ContractInfo) { c.Label = "" }, - expError: true, - }, - "label exceeds limit": { - srcMutator: func(c *ContractInfo) { c.Label = strings.Repeat("a", MaxLabelSize+1) }, - expError: true, - }, - "invalid extension": { - srcMutator: func(c *ContractInfo) { - // any protobuf type with ValidateBasic method - codecAny, err := codectypes.NewAnyWithValue(&v1beta1.TextProposal{}) - - require.NoError(t, err) - c.Extension = codecAny - }, - expError: true, - }, - "not validatable extension": { - srcMutator: func(c *ContractInfo) { - // any protobuf type with ValidateBasic method - codecAny, err := codectypes.NewAnyWithValue(&v1beta1.Proposal{}) - - require.NoError(t, err) - c.Extension = codecAny - }, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - state := ContractInfoFixture(spec.srcMutator) - got := state.ValidateBasic() - if spec.expError { - require.Error(t, got) - return - } - require.NoError(t, got) - }) - } -} - -func TestCodeInfoValidateBasic(t *testing.T) { - specs := map[string]struct { - srcMutator func(*CodeInfo) - expError bool - }{ - "all good": {srcMutator: func(_ *CodeInfo) {}}, - "code hash empty": { - srcMutator: func(c *CodeInfo) { c.CodeHash = []byte{} }, - expError: true, - }, - "code hash nil": { - srcMutator: func(c *CodeInfo) { c.CodeHash = nil }, - expError: true, - }, - "creator empty": { - srcMutator: func(c *CodeInfo) { c.Creator = "" }, - expError: true, - }, - "creator not an address": { - srcMutator: func(c *CodeInfo) { c.Creator = invalidAddress }, - expError: true, - }, - "Instantiate config invalid": { - srcMutator: func(c *CodeInfo) { c.InstantiateConfig = AccessConfig{} }, - expError: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - state := CodeInfoFixture(spec.srcMutator) - got := state.ValidateBasic() - if spec.expError { - require.Error(t, got) - return - } - require.NoError(t, got) - }) - } -} - -func TestContractInfoSetExtension(t *testing.T) { - anyTime := time.Now().UTC() - aNestedProtobufExt := func() ContractInfoExtension { - // using gov proposal here as a random protobuf types as it contains an Any type inside for nested unpacking - myExtension, err := v1beta1.NewProposal(&v1beta1.TextProposal{Title: "bar"}, 1, anyTime, anyTime) - require.NoError(t, err) - myExtension.TotalDeposit = nil - return &myExtension - } - - specs := map[string]struct { - src ContractInfoExtension - expErr bool - expNil bool - }{ - "all good with any proto extension": { - src: aNestedProtobufExt(), - }, - "nil allowed": { - src: nil, - expNil: true, - }, - "validated and accepted": { - src: &v1beta1.TextProposal{Title: "bar", Description: "set"}, - }, - "validated and rejected": { - src: &v1beta1.TextProposal{Title: "bar"}, - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - var c ContractInfo - gotErr := c.SetExtension(spec.src) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - if spec.expNil { - return - } - require.NotNil(t, c.Extension) - assert.NotNil(t, c.Extension.GetCachedValue()) - }) - } -} - -func TestContractInfoMarshalUnmarshal(t *testing.T) { - var myAddr sdk.AccAddress = rand.Bytes(ContractAddrLen) - var myOtherAddr sdk.AccAddress = rand.Bytes(ContractAddrLen) - anyPos := AbsoluteTxPosition{BlockHeight: 1, TxIndex: 2} - - anyTime := time.Now().UTC() - // using gov proposal here as a random protobuf types as it contains an Any type inside for nested unpacking - myExtension, err := v1beta1.NewProposal(&v1beta1.TextProposal{Title: "bar"}, 1, anyTime, anyTime) - require.NoError(t, err) - myExtension.TotalDeposit = nil - - src := NewContractInfo(1, myAddr, myOtherAddr, "bar", &anyPos) - err = src.SetExtension(&myExtension) - require.NoError(t, err) - - interfaceRegistry := codectypes.NewInterfaceRegistry() - marshaler := codec.NewProtoCodec(interfaceRegistry) - RegisterInterfaces(interfaceRegistry) - // register proposal as extension type - interfaceRegistry.RegisterImplementations( - (*ContractInfoExtension)(nil), - &v1beta1.Proposal{}, - ) - // register gov types for nested Anys - v1beta1.RegisterInterfaces(interfaceRegistry) - - // when encode - bz, err := marshaler.Marshal(&src) - require.NoError(t, err) - // and decode - var dest ContractInfo - err = marshaler.Unmarshal(bz, &dest) - // then - require.NoError(t, err) - assert.Equal(t, src, dest) - // and sanity check nested any - var destExt v1beta1.Proposal - require.NoError(t, dest.ReadExtension(&destExt)) - assert.Equal(t, destExt.GetTitle(), "bar") -} - -func TestContractInfoReadExtension(t *testing.T) { - anyTime := time.Now().UTC() - myExtension, err := v1beta1.NewProposal(&v1beta1.TextProposal{Title: "foo"}, 1, anyTime, anyTime) - require.NoError(t, err) - type TestExtensionAsStruct struct { - ContractInfoExtension - } - - specs := map[string]struct { - setup func(*ContractInfo) - param func() ContractInfoExtension - expVal ContractInfoExtension - expErr bool - }{ - "all good": { - setup: func(i *ContractInfo) { - err = i.SetExtension(&myExtension) - require.NoError(t, err) - }, - param: func() ContractInfoExtension { - return &v1beta1.Proposal{} - }, - expVal: &myExtension, - }, - "no extension set": { - setup: func(i *ContractInfo) { - }, - param: func() ContractInfoExtension { - return &v1beta1.Proposal{} - }, - expVal: &v1beta1.Proposal{}, - }, - "nil argument value": { - setup: func(i *ContractInfo) { - err = i.SetExtension(&myExtension) - require.NoError(t, err) - }, - param: func() ContractInfoExtension { - return nil - }, - expErr: true, - }, - "non matching types": { - setup: func(i *ContractInfo) { - err = i.SetExtension(&myExtension) - require.NoError(t, err) - }, - param: func() ContractInfoExtension { - return &v1beta1.TextProposal{} - }, - expErr: true, - }, - "not a pointer argument": { - setup: func(i *ContractInfo) { - }, - param: func() ContractInfoExtension { - return TestExtensionAsStruct{} - }, - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - var c ContractInfo - spec.setup(&c) - // when - - gotValue := spec.param() - gotErr := c.ReadExtension(gotValue) - - // then - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - assert.Equal(t, spec.expVal, gotValue) - }) - } -} - -func TestNewEnv(t *testing.T) { - myTime := time.Unix(0, 1619700924259075000) - t.Logf("++ unix: %d", myTime.UnixNano()) - var myContractAddr sdk.AccAddress = randBytes(ContractAddrLen) - specs := map[string]struct { - srcCtx sdk.Context - exp wasmvmtypes.Env - }{ - "all good with tx counter": { - srcCtx: WithTXCounter(sdk.Context{}.WithBlockHeight(1).WithBlockTime(myTime).WithChainID("testing").WithContext(context.Background()), 0), - exp: wasmvmtypes.Env{ - Block: wasmvmtypes.BlockInfo{ - Height: 1, - Time: 1619700924259075000, - ChainID: "testing", - }, - Contract: wasmvmtypes.ContractInfo{ - Address: myContractAddr.String(), - }, - Transaction: &wasmvmtypes.TransactionInfo{Index: 0}, - }, - }, - "without tx counter": { - srcCtx: sdk.Context{}.WithBlockHeight(1).WithBlockTime(myTime).WithChainID("testing").WithContext(context.Background()), - exp: wasmvmtypes.Env{ - Block: wasmvmtypes.BlockInfo{ - Height: 1, - Time: 1619700924259075000, - ChainID: "testing", - }, - Contract: wasmvmtypes.ContractInfo{ - Address: myContractAddr.String(), - }, - }, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - assert.Equal(t, spec.exp, NewEnv(spec.srcCtx, myContractAddr)) - }) - } -} - -func TestVerifyAddressLen(t *testing.T) { - specs := map[string]struct { - src []byte - expErr bool - }{ - "valid contract address": { - src: bytes.Repeat([]byte{1}, 32), - }, - "valid legacy address": { - src: bytes.Repeat([]byte{1}, 20), - }, - "address too short for legacy": { - src: bytes.Repeat([]byte{1}, 19), - expErr: true, - }, - "address too short for contract": { - src: bytes.Repeat([]byte{1}, 31), - expErr: true, - }, - "address too long for legacy": { - src: bytes.Repeat([]byte{1}, 21), - expErr: true, - }, - "address too long for contract": { - src: bytes.Repeat([]byte{1}, 33), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - gotErr := VerifyAddressLen()(spec.src) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - }) - } -} - -func TestAccessConfigSubset(t *testing.T) { - // read - // <, <= is subset of - // !< is not subset of - specs := map[string]struct { - check AccessConfig - superSet AccessConfig - isSubSet bool - }{ - // nobody - "nobody <= nobody": { - superSet: AccessConfig{Permission: AccessTypeNobody}, - check: AccessConfig{Permission: AccessTypeNobody}, - isSubSet: true, - }, - "only !< nobody": { - superSet: AccessConfig{Permission: AccessTypeNobody}, - check: AccessConfig{Permission: AccessTypeOnlyAddress, Address: "foobar"}, - isSubSet: false, - }, - "anyOf !< nobody": { - superSet: AccessConfig{Permission: AccessTypeNobody}, - check: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"foobar"}}, - isSubSet: false, - }, - "everybody !< nobody ": { - superSet: AccessConfig{Permission: AccessTypeNobody}, - check: AccessConfig{Permission: AccessTypeEverybody}, - isSubSet: false, - }, - "unspecified !< nobody": { - superSet: AccessConfig{Permission: AccessTypeNobody}, - check: AccessConfig{Permission: AccessTypeUnspecified}, - isSubSet: false, - }, - // only - "nobody < only": { - superSet: AccessConfig{Permission: AccessTypeOnlyAddress, Address: "owner"}, - check: AccessConfig{Permission: AccessTypeNobody}, - isSubSet: true, - }, - "only <= only(same)": { - superSet: AccessConfig{Permission: AccessTypeOnlyAddress, Address: "owner"}, - check: AccessConfig{Permission: AccessTypeOnlyAddress, Address: "owner"}, - isSubSet: true, - }, - "only !< only(other)": { - superSet: AccessConfig{Permission: AccessTypeOnlyAddress, Address: "owner"}, - check: AccessConfig{Permission: AccessTypeOnlyAddress, Address: "other"}, - isSubSet: false, - }, - "anyOf(same) <= only": { - superSet: AccessConfig{Permission: AccessTypeOnlyAddress, Address: "owner"}, - check: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"owner"}}, - isSubSet: true, - }, - "anyOf(other) !< only": { - superSet: AccessConfig{Permission: AccessTypeOnlyAddress, Address: "owner"}, - check: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"foobar"}}, - isSubSet: false, - }, - "anyOf(same, other) !< only": { - superSet: AccessConfig{Permission: AccessTypeOnlyAddress, Address: "owner"}, - check: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"owner", "foobar"}}, - isSubSet: false, - }, - "everybody !< only": { - superSet: AccessConfig{Permission: AccessTypeOnlyAddress, Address: "owner"}, - check: AccessConfig{Permission: AccessTypeEverybody}, - isSubSet: false, - }, - "unspecified !<= only": { - superSet: AccessConfig{Permission: AccessTypeOnlyAddress, Address: "owner"}, - check: AccessConfig{Permission: AccessTypeUnspecified}, - isSubSet: false, - }, - - // any of - "nobody < anyOf": { - superSet: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"owner"}}, - check: AccessConfig{Permission: AccessTypeNobody}, - isSubSet: true, - }, - "only(same) < anyOf(same)": { - superSet: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"owner"}}, - check: AccessConfig{Permission: AccessTypeOnlyAddress, Address: "owner"}, - isSubSet: true, - }, - "only(same) < anyOf(same, other)": { - superSet: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"owner", "other"}}, - check: AccessConfig{Permission: AccessTypeOnlyAddress, Address: "owner"}, - isSubSet: true, - }, - "only(other) !< anyOf": { - superSet: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"owner"}}, - check: AccessConfig{Permission: AccessTypeOnlyAddress, Address: "other"}, - isSubSet: false, - }, - "anyOf < anyOf": { - superSet: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"owner"}}, - check: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"owner"}}, - isSubSet: true, - }, - "anyOf(multiple) < anyOf(multiple)": { - superSet: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"owner", "other"}}, - check: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"owner", "other"}}, - isSubSet: true, - }, - "anyOf(multiple, other) !< anyOf(multiple)": { - superSet: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"owner", "other", "foo"}}, - check: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"owner", "other", "bar"}}, - isSubSet: false, - }, - "anyOf(multiple) !< anyOf": { - superSet: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"owner"}}, - check: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"owner", "other"}}, - isSubSet: false, - }, - "everybody !< anyOf": { - superSet: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"owner"}}, - check: AccessConfig{Permission: AccessTypeEverybody}, - isSubSet: false, - }, - "unspecified !< anyOf ": { - superSet: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"owner"}}, - check: AccessConfig{Permission: AccessTypeUnspecified}, - isSubSet: false, - }, - // everybody - "nobody < everybody": { - superSet: AccessConfig{Permission: AccessTypeEverybody}, - check: AccessConfig{Permission: AccessTypeNobody}, - isSubSet: true, - }, - "only < everybody": { - superSet: AccessConfig{Permission: AccessTypeEverybody}, - check: AccessConfig{Permission: AccessTypeOnlyAddress, Address: "foobar"}, - isSubSet: true, - }, - "anyOf < everybody": { - superSet: AccessConfig{Permission: AccessTypeEverybody}, - check: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"foobar"}}, - isSubSet: true, - }, - "everybody <= everybody": { - superSet: AccessConfig{Permission: AccessTypeEverybody}, - check: AccessConfig{Permission: AccessTypeEverybody}, - isSubSet: true, - }, - "unspecified !< everybody ": { - superSet: AccessConfig{Permission: AccessTypeEverybody}, - check: AccessConfig{Permission: AccessTypeUnspecified}, - isSubSet: false, - }, - // unspecified - "nobody !< unspecified": { - superSet: AccessConfig{Permission: AccessTypeUnspecified}, - check: AccessConfig{Permission: AccessTypeNobody}, - isSubSet: false, - }, - "only !< unspecified": { - superSet: AccessConfig{Permission: AccessTypeUnspecified}, - check: AccessConfig{Permission: AccessTypeOnlyAddress, Address: "foobar"}, - isSubSet: false, - }, - "anyOf !< unspecified": { - superSet: AccessConfig{Permission: AccessTypeUnspecified}, - check: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"foobar"}}, - isSubSet: false, - }, - "everybody !< unspecified": { - superSet: AccessConfig{Permission: AccessTypeUnspecified}, - check: AccessConfig{Permission: AccessTypeEverybody}, - isSubSet: false, - }, - "unspecified !< unspecified ": { - superSet: AccessConfig{Permission: AccessTypeUnspecified}, - check: AccessConfig{Permission: AccessTypeUnspecified}, - isSubSet: false, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - subset := spec.check.IsSubset(spec.superSet) - require.Equal(t, spec.isSubSet, subset) - }) - } -} - -func TestAccessTypeSubset(t *testing.T) { - specs := map[string]struct { - check AccessType - superSet AccessType - isSubSet bool - }{ - // nobody - "nobody <= nobody": { - superSet: AccessTypeNobody, - check: AccessTypeNobody, - isSubSet: true, - }, - "only !< nobody": { - superSet: AccessTypeNobody, - check: AccessTypeOnlyAddress, - isSubSet: false, - }, - "any !< nobody": { - superSet: AccessTypeNobody, - check: AccessTypeAnyOfAddresses, - isSubSet: false, - }, - "everybody !< nobody": { - superSet: AccessTypeNobody, - check: AccessTypeEverybody, - isSubSet: false, - }, - "unspecified !< nobody": { - superSet: AccessTypeNobody, - check: AccessTypeUnspecified, - isSubSet: false, - }, - // only - "nobody < only": { - superSet: AccessTypeOnlyAddress, - check: AccessTypeNobody, - isSubSet: true, - }, - "only <= only": { - superSet: AccessTypeOnlyAddress, - check: AccessTypeOnlyAddress, - isSubSet: true, - }, - "anyOf !< only": { - superSet: AccessTypeOnlyAddress, - check: AccessTypeAnyOfAddresses, - isSubSet: true, - }, - "everybody !< only": { - superSet: AccessTypeOnlyAddress, - check: AccessTypeEverybody, - isSubSet: false, - }, - "unspecified !< only": { - superSet: AccessTypeOnlyAddress, - check: AccessTypeUnspecified, - isSubSet: false, - }, - // any of - "nobody < anyOf": { - superSet: AccessTypeAnyOfAddresses, - check: AccessTypeNobody, - isSubSet: true, - }, - "only <= anyOf": { - superSet: AccessTypeAnyOfAddresses, - check: AccessTypeOnlyAddress, - isSubSet: true, - }, - "anyOf <= anyOf": { - superSet: AccessTypeAnyOfAddresses, - check: AccessTypeAnyOfAddresses, - isSubSet: true, - }, - "everybody !< anyOf": { - superSet: AccessTypeAnyOfAddresses, - check: AccessTypeEverybody, - isSubSet: false, - }, - "unspecified !< anyOf": { - superSet: AccessTypeAnyOfAddresses, - check: AccessTypeUnspecified, - isSubSet: false, - }, - // everybody - "nobody < everybody": { - superSet: AccessTypeEverybody, - check: AccessTypeNobody, - isSubSet: true, - }, - "only < everybody": { - superSet: AccessTypeEverybody, - check: AccessTypeOnlyAddress, - isSubSet: true, - }, - "anyOf < everybody": { - superSet: AccessTypeEverybody, - check: AccessTypeAnyOfAddresses, - isSubSet: true, - }, - "everybody <= everybody": { - superSet: AccessTypeEverybody, - check: AccessTypeEverybody, - isSubSet: true, - }, - "unspecified !< everybody": { - superSet: AccessTypeEverybody, - check: AccessTypeUnspecified, - isSubSet: false, - }, - // unspecified - "nobody !< unspecified": { - superSet: AccessTypeUnspecified, - check: AccessTypeNobody, - isSubSet: false, - }, - "only !< unspecified": { - superSet: AccessTypeUnspecified, - check: AccessTypeOnlyAddress, - isSubSet: false, - }, - "anyOf !< unspecified": { - superSet: AccessTypeUnspecified, - check: AccessTypeAnyOfAddresses, - isSubSet: false, - }, - "everybody !< unspecified": { - superSet: AccessTypeUnspecified, - check: AccessTypeEverybody, - isSubSet: false, - }, - "unspecified !< unspecified": { - superSet: AccessTypeUnspecified, - check: AccessTypeUnspecified, - isSubSet: false, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - subset := spec.check.IsSubset(spec.superSet) - require.Equal(t, spec.isSubSet, subset) - }) - } -} - -func TestContractCodeHistoryEntryValidation(t *testing.T) { - specs := map[string]struct { - src ContractCodeHistoryEntry - expErr bool - }{ - "all good": { - src: ContractCodeHistoryEntryFixture(), - }, - "unknown operation": { - src: ContractCodeHistoryEntryFixture(func(entry *ContractCodeHistoryEntry) { - entry.Operation = 0 - }), - expErr: true, - }, - "empty code id": { - src: ContractCodeHistoryEntryFixture(func(entry *ContractCodeHistoryEntry) { - entry.CodeID = 0 - }), - expErr: true, - }, - "empty updated": { - src: ContractCodeHistoryEntryFixture(func(entry *ContractCodeHistoryEntry) { - entry.Updated = nil - }), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - gotErr := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - }) - } -} diff --git a/x/wasm/types/validation.go b/x/wasm/types/validation.go deleted file mode 100644 index d3e678b..0000000 --- a/x/wasm/types/validation.go +++ /dev/null @@ -1,79 +0,0 @@ -package types - -import ( - "fmt" - "net/url" - - errorsmod "cosmossdk.io/errors" - "github.com/docker/distribution/reference" -) - -// MaxSaltSize is the longest salt that can be used when instantiating a contract -const MaxSaltSize = 64 - -var ( - // MaxLabelSize is the longest label that can be used when instantiating a contract - MaxLabelSize = 128 // extension point for chains to customize via compile flag. - - // MaxWasmSize is the largest a compiled contract code can be when storing code on chain - MaxWasmSize = 800 * 1024 // extension point for chains to customize via compile flag. - - // MaxProposalWasmSize is the largest a gov proposal compiled contract code can be when storing code on chain - MaxProposalWasmSize = 3 * 1024 * 1024 // extension point for chains to customize via compile flag. -) - -func validateWasmCode(s []byte, maxSize int) error { - if len(s) == 0 { - return errorsmod.Wrap(ErrEmpty, "is required") - } - if len(s) > maxSize { - return errorsmod.Wrapf(ErrLimit, "cannot be longer than %d bytes", maxSize) - } - return nil -} - -// ValidateLabel ensure label constraints -func ValidateLabel(label string) error { - if label == "" { - return errorsmod.Wrap(ErrEmpty, "is required") - } - if len(label) > MaxLabelSize { - return ErrLimit.Wrapf("cannot be longer than %d characters", MaxLabelSize) - } - return nil -} - -// ValidateSalt ensure salt constraints -func ValidateSalt(salt []byte) error { - switch n := len(salt); { - case n == 0: - return errorsmod.Wrap(ErrEmpty, "is required") - case n > MaxSaltSize: - return ErrLimit.Wrapf("cannot be longer than %d characters", MaxSaltSize) - } - return nil -} - -// ValidateVerificationInfo ensure source, builder and checksum constraints -func ValidateVerificationInfo(source, builder string, codeHash []byte) error { - // if any set require others to be set - if len(source) != 0 || len(builder) != 0 || codeHash != nil { - if source == "" { - return fmt.Errorf("source is required") - } - if _, err := url.ParseRequestURI(source); err != nil { - return fmt.Errorf("source: %s", err) - } - if builder == "" { - return fmt.Errorf("builder is required") - } - if _, err := reference.ParseDockerRef(builder); err != nil { - return fmt.Errorf("builder: %s", err) - } - if codeHash == nil { - return fmt.Errorf("code hash is required") - } - // code hash checksum match validation is done in the keeper, ungzipping consumes gas - } - return nil -} diff --git a/x/wasm/types/wasmer_engine.go b/x/wasm/types/wasmer_engine.go deleted file mode 100644 index 9b2efde..0000000 --- a/x/wasm/types/wasmer_engine.go +++ /dev/null @@ -1,277 +0,0 @@ -package types - -import ( - wasmvm "github.com/CosmWasm/wasmvm" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// DefaultMaxQueryStackSize maximum size of the stack of contract instances doing queries -const DefaultMaxQueryStackSize uint32 = 10 - -// WasmerEngine defines the WASM contract runtime engine. -type WasmerEngine interface { - // Create will compile the wasm code, and store the resulting pre-compile - // as well as the original code. Both can be referenced later via CodeID - // This must be done one time for given code, after which it can be - // instatitated many times, and each instance called many times. - // - // For example, the code for all ERC-20 contracts should be the same. - // This function stores the code for that contract only once, but it can - // be instantiated with custom inputs in the future. - Create(code wasmvm.WasmCode) (wasmvm.Checksum, error) - - // AnalyzeCode will statically analyze the code. - // Currently just reports if it exposes all IBC entry points. - AnalyzeCode(checksum wasmvm.Checksum) (*wasmvmtypes.AnalysisReport, error) - - // Instantiate will create a new contract based on the given codeID. - // We can set the initMsg (contract "genesis") here, and it then receives - // an account and address and can be invoked (Execute) many times. - // - // Storage should be set with a PrefixedKVStore that this code can safely access. - // - // Under the hood, we may recompile the wasm, use a cached native compile, or even use a cached instance - // for performance. - Instantiate( - checksum wasmvm.Checksum, - env wasmvmtypes.Env, - info wasmvmtypes.MessageInfo, - initMsg []byte, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.Response, uint64, error) - - // Execute calls a given contract. Since the only difference between contracts with the same CodeID is the - // data in their local storage, and their address in the outside world, we need no ContractID here. - // (That is a detail for the external, sdk-facing, side). - // - // The caller is responsible for passing the correct `store` (which must have been initialized exactly once), - // and setting the env with relevant info on this instance (address, balance, etc) - Execute( - code wasmvm.Checksum, - env wasmvmtypes.Env, - info wasmvmtypes.MessageInfo, - executeMsg []byte, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.Response, uint64, error) - - // Query allows a client to execute a contract-specific query. If the result is not empty, it should be - // valid json-encoded data to return to the client. - // The meaning of path and data can be determined by the code. Path is the suffix of the abci.QueryRequest.Path - Query( - code wasmvm.Checksum, - env wasmvmtypes.Env, - queryMsg []byte, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) ([]byte, uint64, error) - - // Migrate will migrate an existing contract to a new code binary. - // This takes storage of the data from the original contract and the CodeID of the new contract that should - // replace it. This allows it to run a migration step if needed, or return an error if unable to migrate - // the given data. - // - // MigrateMsg has some data on how to perform the migration. - Migrate( - checksum wasmvm.Checksum, - env wasmvmtypes.Env, - migrateMsg []byte, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.Response, uint64, error) - - // Sudo runs an existing contract in read/write mode (like Execute), but is never exposed to external callers - // (either transactions or government proposals), but can only be called by other native Go modules directly. - // - // This allows a contract to expose custom "super user" functions or priviledged operations that can be - // deeply integrated with native modules. - Sudo( - checksum wasmvm.Checksum, - env wasmvmtypes.Env, - sudoMsg []byte, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.Response, uint64, error) - - // Reply is called on the original dispatching contract after running a submessage - Reply( - checksum wasmvm.Checksum, - env wasmvmtypes.Env, - reply wasmvmtypes.Reply, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.Response, uint64, error) - - // GetCode will load the original wasm code for the given code id. - // This will only succeed if that code id was previously returned from - // a call to Create. - // - // This can be used so that the (short) code id (hash) is stored in the iavl tree - // and the larger binary blobs (wasm and pre-compiles) are all managed by the - // rust library - GetCode(code wasmvm.Checksum) (wasmvm.WasmCode, error) - - // Cleanup should be called when no longer using this to free resources on the rust-side - Cleanup() - - // IBCChannelOpen is available on IBC-enabled contracts and is a hook to call into - // during the handshake phase - IBCChannelOpen( - checksum wasmvm.Checksum, - env wasmvmtypes.Env, - channel wasmvmtypes.IBCChannelOpenMsg, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.IBC3ChannelOpenResponse, uint64, error) - - // IBCChannelConnect is available on IBC-enabled contracts and is a hook to call into - // during the handshake phase - IBCChannelConnect( - checksum wasmvm.Checksum, - env wasmvmtypes.Env, - channel wasmvmtypes.IBCChannelConnectMsg, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.IBCBasicResponse, uint64, error) - - // IBCChannelClose is available on IBC-enabled contracts and is a hook to call into - // at the end of the channel lifetime - IBCChannelClose( - checksum wasmvm.Checksum, - env wasmvmtypes.Env, - channel wasmvmtypes.IBCChannelCloseMsg, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.IBCBasicResponse, uint64, error) - - // IBCPacketReceive is available on IBC-enabled contracts and is called when an incoming - // packet is received on a channel belonging to this contract - IBCPacketReceive( - checksum wasmvm.Checksum, - env wasmvmtypes.Env, - packet wasmvmtypes.IBCPacketReceiveMsg, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.IBCReceiveResult, uint64, error) - - // IBCPacketAck is available on IBC-enabled contracts and is called when an - // the response for an outgoing packet (previously sent by this contract) - // is received - IBCPacketAck( - checksum wasmvm.Checksum, - env wasmvmtypes.Env, - ack wasmvmtypes.IBCPacketAckMsg, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.IBCBasicResponse, uint64, error) - - // IBCPacketTimeout is available on IBC-enabled contracts and is called when an - // outgoing packet (previously sent by this contract) will probably never be executed. - // Usually handled like ack returning an error - IBCPacketTimeout( - checksum wasmvm.Checksum, - env wasmvmtypes.Env, - packet wasmvmtypes.IBCPacketTimeoutMsg, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.IBCBasicResponse, uint64, error) - - // Pin pins a code to an in-memory cache, such that is - // always loaded quickly when executed. - // Pin is idempotent. - Pin(checksum wasmvm.Checksum) error - - // Unpin removes the guarantee of a contract to be pinned (see Pin). - // After calling this, the code may or may not remain in memory depending on - // the implementor's choice. - // Unpin is idempotent. - Unpin(checksum wasmvm.Checksum) error - - // GetMetrics some internal metrics for monitoring purposes. - GetMetrics() (*wasmvmtypes.Metrics, error) -} - -var _ wasmvm.KVStore = &StoreAdapter{} - -// StoreAdapter adapter to bridge SDK store impl to wasmvm -type StoreAdapter struct { - parent sdk.KVStore -} - -// NewStoreAdapter constructor -func NewStoreAdapter(s sdk.KVStore) *StoreAdapter { - if s == nil { - panic("store must not be nil") - } - return &StoreAdapter{parent: s} -} - -func (s StoreAdapter) Get(key []byte) []byte { - return s.parent.Get(key) -} - -func (s StoreAdapter) Set(key, value []byte) { - s.parent.Set(key, value) -} - -func (s StoreAdapter) Delete(key []byte) { - s.parent.Delete(key) -} - -func (s StoreAdapter) Iterator(start, end []byte) wasmvmtypes.Iterator { - return s.parent.Iterator(start, end) -} - -func (s StoreAdapter) ReverseIterator(start, end []byte) wasmvmtypes.Iterator { - return s.parent.ReverseIterator(start, end) -}