├── .github └── workflows │ ├── pr.yml │ └── tests.yml ├── .gitignore ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE ├── MIGRATING.md ├── Makefile ├── NOTICE ├── README.md ├── contracts ├── ibc_transfer │ ├── .cargo │ │ └── config │ ├── Cargo.toml │ ├── README.md │ ├── schema │ │ ├── execute_msg.json │ │ └── instantiate_msg.json │ └── src │ │ ├── bin │ │ └── ibc_transfer_schema.rs │ │ ├── contract.rs │ │ ├── lib.rs │ │ ├── msg.rs │ │ └── state.rs ├── neutron_interchain_queries │ ├── .cargo │ │ └── config │ ├── Cargo.toml │ ├── Makefile │ ├── README.md │ ├── schema │ │ ├── execute_msg.json │ │ ├── instantiate_msg.json │ │ └── query_msg.json │ └── src │ │ ├── bin │ │ └── neutron_interchain_queries_schema.rs │ │ ├── contract.rs │ │ ├── lib.rs │ │ ├── msg.rs │ │ ├── state.rs │ │ └── testing │ │ ├── mock_querier.rs │ │ ├── mod.rs │ │ └── tests.rs └── neutron_interchain_txs │ ├── .cargo │ └── config │ ├── Cargo.toml │ ├── Makefile │ ├── README.md │ ├── schema │ ├── execute_msg.json │ ├── instantiate_msg.json │ ├── migrate_msg.json │ ├── query_msg.json │ └── sudo_msg.json │ └── src │ ├── bin │ └── neutron_interchain_txs_schema.rs │ ├── contract.rs │ ├── lib.rs │ ├── msg.rs │ ├── storage.rs │ └── testing │ ├── mod.rs │ └── tests.rs ├── packages └── neutron-sdk │ ├── .cargo │ └── config │ ├── Cargo.toml │ ├── README.md │ ├── schema │ └── neutron_msg.json │ └── src │ ├── bin │ └── neutron_sdk_schema.rs │ ├── bindings │ ├── mod.rs │ └── msg.rs │ ├── errors │ ├── error.rs │ └── mod.rs │ ├── interchain_queries │ ├── helpers.rs │ ├── mod.rs │ ├── queries.rs │ ├── types.rs │ ├── v045 │ │ ├── helpers.rs │ │ ├── mod.rs │ │ ├── queries.rs │ │ ├── register_queries.rs │ │ ├── testing.rs │ │ └── types.rs │ └── v047 │ │ ├── mod.rs │ │ ├── queries.rs │ │ ├── register_queries.rs │ │ ├── testing.rs │ │ └── types.rs │ ├── interchain_txs │ ├── helpers.rs │ ├── mod.rs │ ├── v045 │ │ ├── helpers.rs │ │ └── mod.rs │ └── v047 │ │ ├── helpers.rs │ │ └── mod.rs │ ├── lib.rs │ └── sudo │ ├── mod.rs │ └── msg.rs ├── rust-toolchain.toml ├── rustfmt.toml └── scripts ├── test_ibc_transfer.sh ├── test_icq_wasm_juno_testnet ├── .gitignore ├── README.md ├── config.toml ├── create_juno_connection.sh ├── icq.env └── test_wasm_query.sh ├── test_interchain_txs.sh ├── test_kv_query.sh └── test_tx_query.sh /.github/workflows/pr.yml: -------------------------------------------------------------------------------- 1 | name: PR 2 | 3 | on: 4 | pull_request: 5 | types: [assigned, unassigned, labeled, unlabeled, opened, edited, closed, reopened, synchronize, converted_to_draft, ready_for_review, locked, unlocked, review_requested, review_request_removed] 6 | issue_comment: 7 | types: [created] 8 | pull_request_review: 9 | types: [submitted] 10 | 11 | jobs: 12 | pr_commented: 13 | # This job only runs for pull request comments 14 | name: PR comment 15 | if: ${{ github.event.issue.pull_request }} 16 | runs-on: ubuntu-latest 17 | steps: 18 | - name: Send Notification 19 | uses: appleboy/telegram-action@master 20 | with: 21 | to: ${{ secrets.TELEGRAM_TO }} 22 | token: ${{ secrets.TELEGRAM_TOKEN }} 23 | message: | 24 | User @${{ github.actor }} commented PR #${{ github.event.issue.number }} "${{ github.event.issue.title }}" (${{ github.event.issue.pull_request.html_url }}) 25 | 26 | pull_requests_and_review: 27 | name: Pull request action or review 28 | if: ${{ !github.event.issue.pull_request }} 29 | runs-on: ubuntu-latest 30 | steps: 31 | - name: Send Notification 32 | uses: appleboy/telegram-action@master 33 | with: 34 | to: ${{ secrets.TELEGRAM_TO }} 35 | token: ${{ secrets.TELEGRAM_TOKEN }} 36 | message: | 37 | User @${{ github.actor }} updated PR #${{ github.event.number }} "${{ github.event.pull_request.title }}", action "${{ github.event.action }}" (${{ github.event.pull_request.html_url }}) 38 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | branches: 4 | - '**' 5 | 6 | name: tests 7 | 8 | jobs: 9 | clippy: 10 | name: Actions - clippy 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v1 14 | with: 15 | fetch-depth: 1 16 | - uses: actions-rs/toolchain@v1 17 | with: 18 | toolchain: 1.78.0 19 | components: clippy 20 | profile: minimal 21 | override: true 22 | - run: cargo fetch --verbose 23 | - run: cargo clippy --all --all-targets -- -D warnings 24 | 25 | rustfmt: 26 | name: Actions - rustfmt 27 | runs-on: ubuntu-latest 28 | steps: 29 | - uses: actions/checkout@v1 30 | with: 31 | fetch-depth: 1 32 | - uses: actions-rs/toolchain@v1 33 | with: 34 | toolchain: 1.78.0 35 | components: rustfmt 36 | profile: minimal 37 | override: true 38 | - run: cargo fmt -- --check 39 | 40 | unit-test: 41 | name: Actions - unit test 42 | runs-on: ${{ matrix.os }} 43 | strategy: 44 | matrix: 45 | os: [macOS-latest, ubuntu-latest] 46 | steps: 47 | - uses: actions/checkout@v1 48 | with: 49 | fetch-depth: 1 50 | - uses: actions-rs/toolchain@v1 51 | with: 52 | toolchain: 1.78.0 53 | profile: minimal 54 | - run: cargo fetch --verbose 55 | - run: cargo build 56 | - run: cargo test --verbose --all 57 | env: 58 | RUST_BACKTRACE: 1 59 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Build results 2 | target/ 3 | /artifacts/checksums_intermediate.txt 4 | artifacts/ 5 | Cargo.lock 6 | 7 | /deployment_scripts/node_modules 8 | 9 | # Cargo+Git helper file (https://github.com/rust-lang/cargo/blob/0.44.1/src/cargo/sources/git/utils.rs#L320-L327) 10 | .cargo-ok 11 | 12 | # Text file backups 13 | **/*.rs.bk 14 | 15 | # macOS 16 | .DS_Store 17 | 18 | # IDEs 19 | *.iml 20 | .idea 21 | .mutagen.yml 22 | .vscode -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## 0.11.0 4 | 5 | ### Improvements 6 | * Rust 1.78; 7 | * Cosmwasm optimizer 0.16; 8 | * [CosmWasm STD is upgraded to v2.0](https://github.com/neutron-org/neutron-sdk/pull/147); 9 | * ICQ balances query is [improved](https://github.com/neutron-org/neutron-sdk/pull/130) to support a list of denoms to query balances of; 10 | 11 | ### Added 12 | * [Proto types generation](https://github.com/neutron-org/neutron-sdk/pull/125); for Stargate queries and messages; 13 | * [ICQ for proposal voters](https://github.com/neutron-org/neutron-sdk/pull/129); 14 | * `MsgRegisterInterchainAccountResponse` binding response [is added](https://github.com/neutron-org/neutron-sdk/pull/138), so now contracts are able to catch `channel_id` and `port_id` directly in a reply handler of `MsgRegisterInterchainAccount`; 15 | * [Bindings](https://github.com/neutron-org/neutron-sdk/pull/141) for Slinky Oracle and MarketMap; 16 | * `limit_sell_price` [is added](https://github.com/neutron-org/neutron-sdk/pull/143) to `PlaceLimitOrder` DEX message; 17 | 18 | ## 0.10.0 19 | 20 | Bindings for [Neutron Dex module](https://docs.neutron.org/neutron/modules/dex/overview/) is added. 21 | 22 | ### Added 23 | 24 | * feat: cw dex bindings by @swelf19 in https://github.com/neutron-org/neutron-sdk/pull/120 25 | 26 | ## 0.9.0 27 | 28 | Now Neutron-SDK supports ICQ and ICTX helpers for different version of Cosmos-SDK and specifically 0.9.0 release 29 | introduces ICQ and ICTX helpers for Cosmos SDK 0.47. 30 | 31 | So if your contract requires interaction with remote chain that uses Cosmos SDK 0.47 you should use helpers from `v047` 32 | packages. 33 | 34 | ### Added 35 | 36 | * ICQ helpers for Cosmos SDK 0.47 by @pr0n00gler in https://github.com/neutron-org/neutron-sdk/pull/133 37 | * Feat: missing tokenfactory bindings by @pr0n00gler in https://github.com/neutron-org/neutron-sdk/pull/128 38 | * Add grpc option `IncludePoolData` to `QueryUserDeposits` by @sotnikov-s 39 | in https://github.com/neutron-org/neutron-sdk/pull/127 40 | * Add query for validators signing infos and unbonding delegations query by @albertandrejev 41 | in https://github.com/neutron-org/neutron-sdk/pull/122 42 | 43 | ### Fixed 44 | 45 | * NTRN-201 fix potential overflow during delegations reconstruct by @quasisamurai 46 | in https://github.com/neutron-org/neutron-sdk/pull/132 47 | 48 | ### Changed 49 | 50 | * Remove usage of deprecated `data` field in Neutron SDK ICTX helper for SDK 0.47 chains & update SDK 0.45 helper to 51 | backw compat NTRN-223 by @quasisamurai in https://github.com/neutron-org/neutron-sdk/pull/134 52 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | resolver = "2" 3 | members = ["contracts/*", "packages/*"] 4 | 5 | [profile.release] 6 | opt-level = 3 7 | debug = false 8 | rpath = false 9 | lto = true 10 | debug-assertions = false 11 | codegen-units = 1 12 | panic = 'abort' 13 | incremental = false 14 | overflow-checks = true 15 | 16 | [workspace.dependencies] 17 | cosmwasm-std = "2.1.0" 18 | neutron-std = { git = "https://github.com/neutron-org/neutron-std", branch = "main" } 19 | cosmwasm-schema = { version = "2.1.0", default-features = false } 20 | cw2 = "2.0.0" 21 | cw-storage-plus = "2.0.0" 22 | schemars = "0.8.15" 23 | serde = { version = "1.0.188", default-features = false } 24 | serde-json-wasm = "1.0.0" 25 | base64 = "0.21.7" 26 | prost = "0.12.3" 27 | prost-types = "0.12.1" 28 | cosmos-sdk-proto = { version = "0.20.0", default-features = false } 29 | bech32 = "0.9.1" 30 | thiserror = "1.0.49" 31 | protobuf = "~3.3.0" 32 | hex = "0.4.3" 33 | serde_json = { version = "1.0.87" } 34 | tendermint-proto = "0.34.1" 35 | speedate = "0.13.0" 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS -------------------------------------------------------------------------------- /MIGRATING.md: -------------------------------------------------------------------------------- 1 | # Migrating 2 | 3 | This guide explains what is needed to upgrade contracts when migrating over releases of`neutron-sdk`. Note that you can 4 | also view the 5 | [complete CHANGELOG](./CHANGELOG.md) to understand the differences. 6 | 7 | ## 0.10.0 -> 0.11.0 8 | 9 | * Update`neutron-sdk`dependencies in Cargo.toml: 10 | 11 | ``` 12 | [dependencies] 13 | neutron-sdk = "0.11.0" 14 | # ... 15 | ``` 16 | 17 | * Follow [CosmWasm MIGRATING.md instructions ](https://github.com/CosmWasm/cosmwasm/blob/main/MIGRATING.md#15x---20x) to update to v2.0 version of `cosmwasm-std` 18 | 19 | ## 0.9.0 -> 0.10.0 20 | 21 | * Update`neutron-sdk`dependencies in Cargo.toml: 22 | 23 | ``` 24 | [dependencies] 25 | neutron-sdk = "0.10.0" 26 | # ... 27 | ``` 28 | 29 | ## 0.8.0 -> 0.9.0 30 | 31 | * Update`neutron-sdk`dependencies in Cargo.toml: 32 | 33 | ``` 34 | [dependencies] 35 | neutron-sdk = "0.9.0" 36 | # ... 37 | ``` 38 | 39 | * If you want to use ICQ helpers compatible with Cosmos SDK 0.47, you must use helpers from v047 package now (you don't 40 | need to change the code otherwise): 41 | 42 | ```diff 43 | -use neutron_sdk::interchain_queries::v045::queries::{...} 44 | +use neutron_sdk::interchain_queries::v047::queries::{...} 45 | 46 | -use neutron_sdk::interchain_queries::v045::register_queries::{...} 47 | +use neutron_sdk::interchain_queries::v047::register_queries::{...} 48 | 49 | -use neutron_sdk::interchain_queries::v045::types::{...}; 50 | +use neutron_sdk::interchain_queries::v047::types::{...}; 51 | ``` 52 | 53 | * Helper for Interchain transactions module `decode_acknowledgement_response` has been moved 54 | from `neutron_sdk::interchain_txs::helpers` package to respective packages for different Cosmos SDK version (`v045` 55 | and `v047` respectively): 56 | 57 | ```diff 58 | -use neutron_sdk::interchain_txs::helpers::decode_acknowledgement_response; 59 | +use neutron_sdk::interchain_txs::v047::helpers::decode_acknowledgement_response; 60 | ``` 61 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: schema test clippy proto-gen build fmt compile check_contracts 2 | 3 | schema: 4 | @find contracts/* -maxdepth 0 -type d \( ! -name . \) -exec bash -c "cd '{}' && cargo schema" \; 5 | @find packages/neutron-sdk -maxdepth 0 -type d \( ! -name . \) -exec bash -c "cd '{}' && cargo schema" \; 6 | 7 | test: 8 | @cargo test 9 | 10 | clippy: 11 | @cargo clippy --all --all-targets -- -D warnings 12 | 13 | fmt: 14 | @cargo fmt -- --check 15 | 16 | doc: 17 | @cargo doc 18 | 19 | compile: 20 | @docker run --rm -v "$(CURDIR)":/code \ 21 | --mount type=volume,source="$(notdir $(CURDIR))_cache",target=/target \ 22 | --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \ 23 | --platform linux/amd64 \ 24 | cosmwasm/workspace-optimizer:0.16.0 25 | 26 | check_contracts: 27 | @cargo install cosmwasm-check 28 | @cosmwasm-check --available-capabilities iterator,staking,stargate,neutron,cosmwasm_1_1,cosmwasm_1_2,cosmwasm_1_3,cosmwasm_1_4,cosmwasm_2_0 artifacts/*.wasm 29 | 30 | build: schema clippy test fmt doc compile check_contracts 31 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Copyright Neutron 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Neutron Cosmwasm SDK 2 | 3 | This repository contains the source code of Neutron Cosmwasm SDK for interacting with [Neutron blockchain](https://github.com/neutron-org/neutron) 4 | 5 | ## Overview 6 | 7 | ### Neutron SDK 8 | 9 | The Neutron SDK is contained inside `packages` folder and consists of the following subpackages: 10 | 11 | | Package | Reference | Description | 12 | |---------------------------------|--------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------| 13 | | Neutron Interchain Queries | | Queries, messages and helper methods for interacting with Neutron Interchain Queries Module | 14 | | Neutron Interchain Transactions | | Queries, messages and helper methods for interacting with Neutron Interchain Transactions Module | 15 | | Neutron Bindings | | Structures and helper methods for interacting with Neutron blockchain | 16 | | Neutron Sudo | | Structures for Sudo Contract callbacks from Neutron blockchain | 17 | | Neutron Errors | | Structures and helpers for Neutron specific error and result types | 18 | | Neutron Stargate | | Structures and helpers for interacting with Neutron via Stargate | 19 | 20 | ### Example Contracts 21 | 22 | We provide sample contracts that either implement or consume these specifications to both provide examples, and provide a basis for code you can extend for more custom contacts, without worrying about reinventing the wheel each time: 23 | 24 | | Contract | Reference | Description | 25 | |--------------------------------------------------|-------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 26 | | Neutron Interchain Queries Example Contract | | The contract shows how to properly work with [Interchain Queries Module](https://github.com/neutron-org/neutron/tree/master/x/interchainqueries) using [Interchain Queries SDK package](https://github.com/neutron-org/neutron-contracts/tree/main/packages/neutron-sdk/src/interchain_queries) via CosmWasm smart-contract. | 27 | | Neutron Interchain Transactions Example Contract | | The contract shows how to properly work with [Neutron Interchain Transactions Module](https://github.com/neutron-org/neutron/tree/master/x/interchaintxs) using [Interchain Transactions SDK package](https://github.com/neutron-org/neutron-contracts/tree/main/packages/neutron-sdk/src/interchain_txs) via CosmWasm smart-contract. | 28 | | Neutron IBC Transfer Example Contract | | The contract shows how to properly work with [Neutron Sudo Package](https://github.com/neutron-org/neutron-contracts/tree/main/packages/neutron_sudo) to handle a callback from IBC transfer. | 29 | 30 | ## Development 31 | 32 | ### Environment Setup 33 | 34 | - Rust v1.78.0+ 35 | - `wasm32-unknown-unknown` target 36 | - Docker 37 | 38 | 1. Install `rustup` via 39 | 40 | 2. Run the following: 41 | 42 | ```sh 43 | rustup default stable 44 | rustup target add wasm32-unknown-unknown 45 | ``` 46 | 47 | 3. Make sure [Docker](https://www.docker.com/) is installed 48 | 49 | ### Unit Tests 50 | 51 | Each contract contains Rust unit tests embedded within the contract source directories. You can run: 52 | 53 | ```sh 54 | make test 55 | ``` 56 | 57 | ### Generating schema 58 | 59 | ```sh 60 | make schema 61 | ``` 62 | 63 | ### Generating proto files 64 | 65 | Neutron proto files represented as generated Rust code is a part of the Neutron SDK. In case Neutron 66 | proto files have changed there's a command for Rust generated code rebuild. To rebuild the files, 67 | run the following command: 68 | 69 | ```sh 70 | make build-proto 71 | ``` 72 | 73 | ### Production 74 | 75 | For production builds, run the following: 76 | 77 | ```sh 78 | make build 79 | ``` 80 | 81 | This performs several optimizations which can significantly reduce the final size of the contract binaries, which will be available inside the `artifacts/` directory. 82 | 83 | ## Documentation 84 | 85 | Check out our documentation at . 86 | 87 | ## License 88 | 89 | Copyright 2025 Neutron 90 | 91 | Licensed under the Apache License, Version 2.0 (the "License"); 92 | you may not use this file except in compliance with the License. 93 | You may obtain a copy of the License at 94 | 95 | http://www.apache.org/licenses/LICENSE-2.0 96 | 97 | Unless required by applicable law or agreed to in writing, software 98 | distributed under the License is distributed on an "AS IS" BASIS, 99 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 100 | See the License for the specific language governing permissions and 101 | limitations under the License. 102 | -------------------------------------------------------------------------------- /contracts/ibc_transfer/.cargo/config: -------------------------------------------------------------------------------- 1 | [alias] 2 | wasm = "build --release --target wasm32-unknown-unknown" 3 | wasm-debug = "build --target wasm32-unknown-unknown" 4 | unit-test = "test --lib" 5 | integration-test = "test --test integration" 6 | schema = "run --bin ibc_transfer_schema" 7 | -------------------------------------------------------------------------------- /contracts/ibc_transfer/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ibc_transfer" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | 7 | exclude = [ 8 | # Those files are rust-optimizer artifacts. You might want to commit them for convenience but they should not be part of the source code publication. 9 | "contract.wasm", 10 | "hash.txt", 11 | ] 12 | 13 | [lib] 14 | crate-type = ["cdylib", "rlib"] 15 | 16 | [features] 17 | # for quicker tests, cargo test --lib 18 | library = [] 19 | 20 | [dependencies] 21 | cosmwasm-std = { workspace = true, features = ["staking", "stargate"] } 22 | cw2 = { workspace = true } 23 | schemars = { workspace = true } 24 | serde = { workspace = true } 25 | serde-json-wasm = { workspace = true } 26 | cw-storage-plus = { workspace = true, features = ["iterator"]} 27 | cosmwasm-schema = { workspace = true } 28 | neutron-sdk = { path = "../../packages/neutron-sdk", default-features = false } 29 | neutron-std = { workspace = true } 30 | 31 | [dev-dependencies] 32 | cosmwasm-schema = { workspace = true } 33 | -------------------------------------------------------------------------------- /contracts/ibc_transfer/README.md: -------------------------------------------------------------------------------- 1 | # Neutron IBC Transfer Example Contract 2 | 3 | The example contract shows how to use and interact with [IBC Transfer Module](https://docs.neutron.org/neutron/modules/transfer/overview). 4 | 5 | ## IBC transfer contract 6 | 7 | Interacting with counterpart chain via ibc transfer is two phases process. 8 | 1. Send ibc transfer message 9 | 2. Accept and process ibc acknowledgement(sudo_response call) 10 | 11 | ## How to test 12 | 13 | 1. run `make build` in the root folder of `neutron-sdk/` 14 | 2. set up [Localnet](https://docs.neutron.org/neutron/build-and-run/localnet) 15 | 3. cd `scripts/` 16 | 4. `./test_ibc_transfer.sh` (or `NEUTRON_DIR=/path/to/somedir/ ./test_ibc_transfer.sh` if the neutron dir is not `../../neutron/`) 17 | 18 | Checkout logs from Neutron chain: `grep -E '(ibc-transfer|WASMDEBUG)' ../../neutron/data/test-1/test-1.log`. 19 | You will see there debug messages from contract and neutron's ibc-transfer module itself. 20 | 21 | ### Tracing ibc transfer ack(sudo) 22 | long story short, we catch packet_sequence id in the reply handler and passthrough any payload to sudo handler using the seq_id 23 | 24 | 1) ExecuteHandler. We save the payload we want to pass to sudo handler with a "unique-enough" id in the storage 25 | 2) ExecuteHandler. Force submsg to replyOn::success with the msd.id we picked above 26 | 3) ReplyHandler. In the reply handler we parse ibc packet_sequence id and map the payload to the seq_id in the storage 27 | 4) SudoHandler. In the sudo handler we read the payload from the storage with a provided seq_id(in sudo ack packet) 28 | -------------------------------------------------------------------------------- /contracts/ibc_transfer/schema/execute_msg.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json-schema.org/draft-07/schema#", 3 | "title": "ExecuteMsg", 4 | "oneOf": [ 5 | { 6 | "type": "object", 7 | "required": [ 8 | "send" 9 | ], 10 | "properties": { 11 | "send": { 12 | "type": "object", 13 | "required": [ 14 | "amount", 15 | "channel", 16 | "denom", 17 | "to" 18 | ], 19 | "properties": { 20 | "amount": { 21 | "type": "integer", 22 | "format": "uint128", 23 | "minimum": 0.0 24 | }, 25 | "channel": { 26 | "type": "string" 27 | }, 28 | "denom": { 29 | "type": "string" 30 | }, 31 | "timeout_height": { 32 | "type": [ 33 | "integer", 34 | "null" 35 | ], 36 | "format": "uint64", 37 | "minimum": 0.0 38 | }, 39 | "to": { 40 | "type": "string" 41 | } 42 | }, 43 | "additionalProperties": false 44 | } 45 | }, 46 | "additionalProperties": false 47 | } 48 | ] 49 | } 50 | -------------------------------------------------------------------------------- /contracts/ibc_transfer/schema/instantiate_msg.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json-schema.org/draft-07/schema#", 3 | "title": "InstantiateMsg", 4 | "type": "object", 5 | "additionalProperties": false 6 | } 7 | -------------------------------------------------------------------------------- /contracts/ibc_transfer/src/bin/ibc_transfer_schema.rs: -------------------------------------------------------------------------------- 1 | use std::env::current_dir; 2 | use std::fs::create_dir_all; 3 | 4 | use cosmwasm_schema::{export_schema, remove_schemas, schema_for}; 5 | 6 | use ibc_transfer::msg::{ExecuteMsg, InstantiateMsg}; 7 | 8 | fn main() { 9 | let mut out_dir = current_dir().unwrap(); 10 | out_dir.push("schema"); 11 | create_dir_all(&out_dir).unwrap(); 12 | remove_schemas(&out_dir).unwrap(); 13 | 14 | export_schema(&schema_for!(InstantiateMsg), &out_dir); 15 | export_schema(&schema_for!(ExecuteMsg), &out_dir); 16 | } 17 | -------------------------------------------------------------------------------- /contracts/ibc_transfer/src/contract.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | msg::{ExecuteMsg, InstantiateMsg, MigrateMsg}, 3 | state::{ 4 | read_reply_payload, read_sudo_payload, save_reply_payload, save_sudo_payload, 5 | IBC_SUDO_ID_RANGE_END, IBC_SUDO_ID_RANGE_START, 6 | }, 7 | }; 8 | use cosmwasm_std::{ 9 | entry_point, Binary, CosmosMsg, Deps, DepsMut, Env, MessageInfo, Reply, Response, StdError, 10 | StdResult, SubMsg, 11 | }; 12 | use cw2::set_contract_version; 13 | use neutron_sdk::interchain_txs::helpers::{decode_message_response, query_denom_min_ibc_fee}; 14 | use neutron_sdk::sudo::msg::{RequestPacket, TransferSudoMsg}; 15 | use neutron_std::types::cosmos::base::v1beta1::Coin as SDKCoin; 16 | use neutron_std::types::neutron::transfer::{MsgTransfer, MsgTransferResponse}; 17 | use schemars::JsonSchema; 18 | use serde::{Deserialize, Serialize}; 19 | 20 | // Default timeout for IbcTransfer is 10000000 blocks 21 | const DEFAULT_TIMEOUT_HEIGHT: u64 = 10000000; 22 | const FEE_DENOM: &str = "untrn"; 23 | 24 | const CONTRACT_NAME: &str = concat!("crates.io:neutron-sdk__", env!("CARGO_PKG_NAME")); 25 | const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION"); 26 | 27 | #[entry_point] 28 | pub fn instantiate( 29 | deps: DepsMut, 30 | _env: Env, 31 | _info: MessageInfo, 32 | _msg: InstantiateMsg, 33 | ) -> StdResult { 34 | set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?; 35 | Ok(Response::default()) 36 | } 37 | 38 | #[entry_point] 39 | pub fn execute(deps: DepsMut, env: Env, _: MessageInfo, msg: ExecuteMsg) -> StdResult { 40 | match msg { 41 | // NOTE: this is an example contract that shows how to make IBC transfers! 42 | // Please add necessary authorization or other protection mechanisms 43 | // if you intend to send funds over IBC 44 | ExecuteMsg::Send { 45 | channel, 46 | to, 47 | denom, 48 | amount, 49 | timeout_height, 50 | } => execute_send(deps, env, channel, to, denom, amount, timeout_height), 51 | } 52 | } 53 | 54 | // Example of different payload types 55 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 56 | #[serde(rename_all = "snake_case")] 57 | pub struct Type1 { 58 | pub message: String, 59 | } 60 | 61 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 62 | #[serde(rename_all = "snake_case")] 63 | pub struct Type2 { 64 | pub data: String, 65 | } 66 | 67 | // a callback handler for payload of Type1 68 | fn sudo_callback1(deps: Deps, payload: Type1) -> StdResult { 69 | deps.api 70 | .debug(format!("WASMDEBUG: callback1: sudo payload: {:?}", payload).as_str()); 71 | Ok(Response::new()) 72 | } 73 | 74 | // a callback handler for payload of Type2 75 | fn sudo_callback2(deps: Deps, payload: Type2) -> StdResult { 76 | deps.api 77 | .debug(format!("WASMDEBUG: callback2: sudo payload: {:?}", payload).as_str()); 78 | Ok(Response::new()) 79 | } 80 | 81 | // Enum representing payload to process during handling acknowledgement messages in Sudo handler 82 | #[derive(Serialize, Deserialize)] 83 | pub enum SudoPayload { 84 | HandlerPayload1(Type1), 85 | HandlerPayload2(Type2), 86 | } 87 | 88 | // saves payload to process later to the storage and returns a SubmitTX Cosmos SubMsg with necessary reply id 89 | fn msg_with_sudo_callback>, T>( 90 | deps: DepsMut, 91 | msg: C, 92 | payload: SudoPayload, 93 | ) -> StdResult> { 94 | let id = save_reply_payload(deps.storage, payload)?; 95 | Ok(SubMsg::reply_on_success(msg, id)) 96 | } 97 | 98 | // prepare_sudo_payload is called from reply handler 99 | // The method is used to extract sequence id and channel from SubmitTxResponse to process sudo payload defined in msg_with_sudo_callback later in Sudo handler. 100 | // Such flow msg_with_sudo_callback() -> reply() -> prepare_sudo_payload() -> sudo() allows you "attach" some payload to your Transfer message 101 | // and process this payload when an acknowledgement for the SubmitTx message is received in Sudo handler 102 | fn prepare_sudo_payload(mut deps: DepsMut, _env: Env, msg: Reply) -> StdResult { 103 | let payload = read_reply_payload(deps.storage, msg.id)?; 104 | let resp: MsgTransferResponse = decode_message_response( 105 | &msg.result 106 | .into_result() 107 | .map_err(StdError::generic_err)? 108 | .msg_responses[0] // msg_responses must have exactly one Msg response: https://github.com/neutron-org/neutron/blob/28b1d2ce968aaf1866e92d5286487f079eba3370/wasmbinding/message_plugin.go#L307 109 | .clone() 110 | .value 111 | .to_vec(), 112 | ) 113 | .map_err(|e| StdError::generic_err(format!("failed to parse response: {:?}", e)))?; 114 | let seq_id = resp.sequence_id; 115 | let channel_id = resp.channel; 116 | save_sudo_payload(deps.branch().storage, channel_id, seq_id, payload)?; 117 | Ok(Response::new()) 118 | } 119 | 120 | #[entry_point] 121 | pub fn reply(deps: DepsMut, env: Env, msg: Reply) -> StdResult { 122 | match msg.id { 123 | // It's convenient to use range of ID's to handle multiple reply messages 124 | IBC_SUDO_ID_RANGE_START..=IBC_SUDO_ID_RANGE_END => prepare_sudo_payload(deps, env, msg), 125 | _ => Err(StdError::generic_err(format!( 126 | "unsupported reply message id {}", 127 | msg.id 128 | ))), 129 | } 130 | } 131 | 132 | fn execute_send( 133 | mut deps: DepsMut, 134 | env: Env, 135 | channel: String, 136 | to: String, 137 | denom: String, 138 | amount: u128, 139 | timeout_height: Option, 140 | ) -> StdResult { 141 | // contract must pay for relaying of acknowledgements 142 | // See more info here: https://docs.neutron.org/neutron/feerefunder/overview 143 | let fee = query_denom_min_ibc_fee(deps.as_ref(), FEE_DENOM)?; 144 | let msg1 = MsgTransfer { 145 | source_port: "transfer".to_string(), 146 | source_channel: channel.clone(), 147 | sender: env.contract.address.to_string(), 148 | receiver: to.clone(), 149 | token: Some(SDKCoin { 150 | denom: denom.clone(), 151 | amount: amount.to_string(), 152 | }), 153 | timeout_height: Some(neutron_std::types::ibc::core::client::v1::Height { 154 | revision_number: 2, 155 | revision_height: timeout_height.unwrap_or(DEFAULT_TIMEOUT_HEIGHT), 156 | }), 157 | timeout_timestamp: 0, 158 | memo: "".to_string(), 159 | fee: Some(fee.clone()), 160 | }; 161 | let msg2 = MsgTransfer { 162 | source_port: "transfer".to_string(), 163 | source_channel: channel, 164 | sender: env.contract.address.to_string(), 165 | receiver: to, 166 | token: Some(SDKCoin { 167 | denom, 168 | amount: (2 * amount).to_string(), 169 | }), 170 | timeout_height: Some(neutron_std::types::ibc::core::client::v1::Height { 171 | revision_number: 2, 172 | revision_height: timeout_height.unwrap_or(DEFAULT_TIMEOUT_HEIGHT), 173 | }), 174 | timeout_timestamp: 0, 175 | memo: "".to_string(), 176 | fee: Some(fee.clone()), 177 | }; 178 | // prepare first transfer message with payload of Type1 179 | let submsg1 = msg_with_sudo_callback( 180 | deps.branch(), 181 | msg1, 182 | SudoPayload::HandlerPayload1(Type1 { 183 | message: "message".to_string(), 184 | }), 185 | )?; 186 | // prepare second transfer message with payload of Type2 187 | // both messages have different reply ids, which allows to send them in one tx and handle both replies separately 188 | let submsg2 = msg_with_sudo_callback( 189 | deps.branch(), 190 | msg2, 191 | SudoPayload::HandlerPayload2(Type2 { 192 | data: "data".to_string(), 193 | }), 194 | )?; 195 | deps.as_ref() 196 | .api 197 | .debug(format!("WASMDEBUG: execute_send: sent submsg1: {:?}", submsg1).as_str()); 198 | deps.api 199 | .debug(format!("WASMDEBUG: execute_send: sent submsg2: {:?}", submsg2).as_str()); 200 | 201 | Ok(Response::default().add_submessages(vec![submsg1, submsg2])) 202 | } 203 | 204 | #[entry_point] 205 | pub fn sudo(deps: DepsMut, _env: Env, msg: TransferSudoMsg) -> StdResult { 206 | match msg { 207 | // For handling successful (non-error) acknowledgements 208 | TransferSudoMsg::Response { request, data } => sudo_response(deps, request, data), 209 | 210 | // For handling error acknowledgements 211 | TransferSudoMsg::Error { request, details } => sudo_error(deps, request, details), 212 | 213 | // For handling error timeouts 214 | TransferSudoMsg::Timeout { request } => sudo_timeout(deps, request), 215 | } 216 | } 217 | 218 | fn sudo_error(deps: DepsMut, req: RequestPacket, data: String) -> StdResult { 219 | deps.api.debug( 220 | format!( 221 | "WASMDEBUG: sudo_error: sudo error received: {:?} {}", 222 | req, data 223 | ) 224 | .as_str(), 225 | ); 226 | Ok(Response::new()) 227 | } 228 | 229 | fn sudo_timeout(deps: DepsMut, req: RequestPacket) -> StdResult { 230 | deps.api.debug( 231 | format!( 232 | "WASMDEBUG: sudo_timeout: sudo timeout ack received: {:?}", 233 | req 234 | ) 235 | .as_str(), 236 | ); 237 | Ok(Response::new()) 238 | } 239 | 240 | fn sudo_response(deps: DepsMut, req: RequestPacket, data: Binary) -> StdResult { 241 | deps.api.debug( 242 | format!( 243 | "WASMDEBUG: sudo_response: sudo received: {:?} {}", 244 | req, data 245 | ) 246 | .as_str(), 247 | ); 248 | let seq_id = req 249 | .sequence 250 | .ok_or_else(|| StdError::generic_err("sequence not found"))?; 251 | let channel_id = req 252 | .source_channel 253 | .ok_or_else(|| StdError::generic_err("channel_id not found"))?; 254 | 255 | match read_sudo_payload(deps.storage, channel_id, seq_id)? { 256 | // here we can do different logic depending on the type of the payload we saved in msg_with_sudo_callback() call 257 | // This allows us to distinguish different transfer message from each other. 258 | // For example some protocols can send one transfer to refund user for some action and another transfer to top up some balance. 259 | // Such different actions may require different handling of their responses. 260 | SudoPayload::HandlerPayload1(t1) => sudo_callback1(deps.as_ref(), t1), 261 | SudoPayload::HandlerPayload2(t2) => sudo_callback2(deps.as_ref(), t2), 262 | } 263 | // at this place we can safely remove the data under (channel_id, seq_id) key 264 | // but it costs an extra gas, so its on you how to use the storage 265 | } 266 | 267 | #[entry_point] 268 | pub fn migrate(deps: DepsMut, _env: Env, _msg: MigrateMsg) -> StdResult { 269 | deps.api.debug("WASMDEBUG: migrate"); 270 | Ok(Response::default()) 271 | } 272 | -------------------------------------------------------------------------------- /contracts/ibc_transfer/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![warn(clippy::unwrap_used, clippy::expect_used)] 2 | 3 | pub mod contract; 4 | pub mod msg; 5 | pub mod state; 6 | -------------------------------------------------------------------------------- /contracts/ibc_transfer/src/msg.rs: -------------------------------------------------------------------------------- 1 | use schemars::JsonSchema; 2 | use serde::{Deserialize, Serialize}; 3 | 4 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 5 | pub struct InstantiateMsg {} 6 | 7 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 8 | #[serde(rename_all = "snake_case")] 9 | pub enum ExecuteMsg { 10 | Send { 11 | channel: String, 12 | to: String, 13 | denom: String, 14 | amount: u128, 15 | timeout_height: Option, 16 | }, 17 | } 18 | 19 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 20 | pub struct MigrateMsg {} 21 | -------------------------------------------------------------------------------- /contracts/ibc_transfer/src/state.rs: -------------------------------------------------------------------------------- 1 | use cosmwasm_std::{from_json, to_json_vec, Binary, StdResult, Storage}; 2 | use cw_storage_plus::{Item, Map}; 3 | 4 | use crate::contract::SudoPayload; 5 | 6 | pub const IBC_SUDO_ID_RANGE_START: u64 = 1_000_000_000; 7 | pub const IBC_SUDO_ID_RANGE_SIZE: u64 = 1_000; 8 | pub const IBC_SUDO_ID_RANGE_END: u64 = IBC_SUDO_ID_RANGE_START + IBC_SUDO_ID_RANGE_SIZE; 9 | 10 | pub const REPLY_QUEUE_ID: Map> = Map::new("reply_queue_id"); 11 | 12 | const REPLY_ID: Item = Item::new("reply_id"); 13 | 14 | /// get_next_id gives us an id for a reply msg 15 | /// dynamic reply id helps us to pass sudo payload to sudo handler via reply handler 16 | /// by setting unique(in transaction lifetime) id to the reply and mapping our payload to the id 17 | /// execute ->(unique reply.id) reply (channel_id,seq_id)-> sudo handler 18 | /// Since id uniqueless id only matters inside a transaction, 19 | /// we can safely reuse the same id set in every new transaction 20 | pub fn get_next_id(store: &mut dyn Storage) -> StdResult { 21 | let mut id = REPLY_ID.may_load(store)?.unwrap_or(IBC_SUDO_ID_RANGE_START); 22 | if id > IBC_SUDO_ID_RANGE_END { 23 | id = IBC_SUDO_ID_RANGE_START 24 | } 25 | REPLY_ID.save(store, &(id + 1))?; 26 | Ok(id) 27 | } 28 | 29 | pub fn save_reply_payload(store: &mut dyn Storage, payload: SudoPayload) -> StdResult { 30 | let id = get_next_id(store)?; 31 | REPLY_QUEUE_ID.save(store, id, &to_json_vec(&payload)?)?; 32 | Ok(id) 33 | } 34 | 35 | pub fn read_reply_payload(store: &dyn Storage, id: u64) -> StdResult { 36 | let data = REPLY_QUEUE_ID.load(store, id)?; 37 | from_json(Binary::new(data)) 38 | } 39 | 40 | /// SUDO_PAYLOAD - tmp storage for sudo handler payloads 41 | /// key (String, u64) - (channel_id, seq_id) 42 | /// every ibc chanel have its own sequence counter(autoincrement) 43 | /// we can catch the counter in the reply msg for outgoing sudo msg 44 | /// and save our payload for the msg 45 | pub const SUDO_PAYLOAD: Map<(String, u64), Vec> = Map::new("sudo_payload"); 46 | 47 | pub fn save_sudo_payload( 48 | store: &mut dyn Storage, 49 | channel_id: String, 50 | seq_id: u64, 51 | payload: SudoPayload, 52 | ) -> StdResult<()> { 53 | SUDO_PAYLOAD.save(store, (channel_id, seq_id), &to_json_vec(&payload)?) 54 | } 55 | 56 | pub fn read_sudo_payload( 57 | store: &dyn Storage, 58 | channel_id: String, 59 | seq_id: u64, 60 | ) -> StdResult { 61 | let data = SUDO_PAYLOAD.load(store, (channel_id, seq_id))?; 62 | from_json(Binary::new(data)) 63 | } 64 | -------------------------------------------------------------------------------- /contracts/neutron_interchain_queries/.cargo/config: -------------------------------------------------------------------------------- 1 | [alias] 2 | wasm = "build --release --target wasm32-unknown-unknown" 3 | wasm-debug = "build --target wasm32-unknown-unknown" 4 | unit-test = "test --lib" 5 | integration-test = "test --test integration" 6 | schema = "run --bin neutron_interchain_queries_schema" 7 | -------------------------------------------------------------------------------- /contracts/neutron_interchain_queries/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "neutron_interchain_queries" 3 | version = "0.1.0" 4 | authors = ["pr0n00gler "] 5 | edition = "2021" 6 | 7 | exclude = [ 8 | # Those files are rust-optimizer artifacts. You might want to commit them for convenience but they should not be part of the source code publication. 9 | "contract.wasm", 10 | "hash.txt", 11 | ] 12 | 13 | [lib] 14 | crate-type = ["cdylib", "rlib"] 15 | 16 | [features] 17 | library = [] 18 | 19 | [dependencies] 20 | cosmwasm-std = { workspace = true } 21 | cw2 = { workspace = true } 22 | schemars = { workspace = true } 23 | serde = { workspace = true } 24 | neutron-sdk = { path = "../../packages/neutron-sdk", default-features = false } 25 | cosmos-sdk-proto = { workspace = true } 26 | cw-storage-plus = { workspace = true } 27 | serde-json-wasm = { workspace = true } 28 | prost-types = { workspace = true } 29 | cosmwasm-schema = { workspace = true } 30 | neutron-std = { workspace = true } 31 | prost = { workspace = true } 32 | 33 | [dev-dependencies] 34 | base64 = { workspace = true } 35 | -------------------------------------------------------------------------------- /contracts/neutron_interchain_queries/Makefile: -------------------------------------------------------------------------------- 1 | # Validators Registry 2 | 3 | CURRENT_DIR = $(shell pwd) 4 | CURRENT_DIR_RELATIVE = $(notdir $(shell pwd)) 5 | 6 | clippy: 7 | rustup component add clippy || true 8 | cargo clippy --all-targets --all-features --workspace -- -D warnings 9 | 10 | test: clippy 11 | cargo unit-test 12 | -------------------------------------------------------------------------------- /contracts/neutron_interchain_queries/README.md: -------------------------------------------------------------------------------- 1 | # Neutron Interchain Queries Example Contract 2 | 3 | The example contract shows how to use and interact with [Interchain Queries Module](https://docs.neutron.org/neutron/modules/interchain-queries/overview). 4 | 5 | ## How to test 6 | 7 | 1. run `make build` in the root folder of `neutron-sdk/` 8 | 2. set up [Localnet](https://docs.neutron.org/neutron/build-and-run/localnet) 9 | 3. cd `scripts/` 10 | 4. `./test_kv_query.sh` (or `NEUTRON_DIR=/path/to/somedir/ ./test_kv_query.sh` if the neutron dir is not `../../neutron/`) 11 | 5. `./test_tx_query.sh` (or `NEUTRON_DIR=/path/to/somedir/ ./test_tx_query.sh` if the neutron dir is not `../../neutron/`) 12 | -------------------------------------------------------------------------------- /contracts/neutron_interchain_queries/schema/execute_msg.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json-schema.org/draft-07/schema#", 3 | "title": "ExecuteMsg", 4 | "oneOf": [ 5 | { 6 | "type": "object", 7 | "required": [ 8 | "register_balances_query" 9 | ], 10 | "properties": { 11 | "register_balances_query": { 12 | "type": "object", 13 | "required": [ 14 | "addr", 15 | "connection_id", 16 | "denoms", 17 | "update_period" 18 | ], 19 | "properties": { 20 | "addr": { 21 | "type": "string" 22 | }, 23 | "connection_id": { 24 | "type": "string" 25 | }, 26 | "denoms": { 27 | "type": "array", 28 | "items": { 29 | "type": "string" 30 | } 31 | }, 32 | "update_period": { 33 | "type": "integer", 34 | "format": "uint64", 35 | "minimum": 0.0 36 | } 37 | }, 38 | "additionalProperties": false 39 | } 40 | }, 41 | "additionalProperties": false 42 | }, 43 | { 44 | "type": "object", 45 | "required": [ 46 | "register_bank_total_supply_query" 47 | ], 48 | "properties": { 49 | "register_bank_total_supply_query": { 50 | "type": "object", 51 | "required": [ 52 | "connection_id", 53 | "denoms", 54 | "update_period" 55 | ], 56 | "properties": { 57 | "connection_id": { 58 | "type": "string" 59 | }, 60 | "denoms": { 61 | "type": "array", 62 | "items": { 63 | "type": "string" 64 | } 65 | }, 66 | "update_period": { 67 | "type": "integer", 68 | "format": "uint64", 69 | "minimum": 0.0 70 | } 71 | }, 72 | "additionalProperties": false 73 | } 74 | }, 75 | "additionalProperties": false 76 | }, 77 | { 78 | "type": "object", 79 | "required": [ 80 | "register_distribution_fee_pool_query" 81 | ], 82 | "properties": { 83 | "register_distribution_fee_pool_query": { 84 | "type": "object", 85 | "required": [ 86 | "connection_id", 87 | "update_period" 88 | ], 89 | "properties": { 90 | "connection_id": { 91 | "type": "string" 92 | }, 93 | "update_period": { 94 | "type": "integer", 95 | "format": "uint64", 96 | "minimum": 0.0 97 | } 98 | }, 99 | "additionalProperties": false 100 | } 101 | }, 102 | "additionalProperties": false 103 | }, 104 | { 105 | "type": "object", 106 | "required": [ 107 | "register_staking_validators_query" 108 | ], 109 | "properties": { 110 | "register_staking_validators_query": { 111 | "type": "object", 112 | "required": [ 113 | "connection_id", 114 | "update_period", 115 | "validators" 116 | ], 117 | "properties": { 118 | "connection_id": { 119 | "type": "string" 120 | }, 121 | "update_period": { 122 | "type": "integer", 123 | "format": "uint64", 124 | "minimum": 0.0 125 | }, 126 | "validators": { 127 | "type": "array", 128 | "items": { 129 | "type": "string" 130 | } 131 | } 132 | }, 133 | "additionalProperties": false 134 | } 135 | }, 136 | "additionalProperties": false 137 | }, 138 | { 139 | "type": "object", 140 | "required": [ 141 | "register_validators_signing_infos_query" 142 | ], 143 | "properties": { 144 | "register_validators_signing_infos_query": { 145 | "type": "object", 146 | "required": [ 147 | "connection_id", 148 | "update_period", 149 | "validators" 150 | ], 151 | "properties": { 152 | "connection_id": { 153 | "type": "string" 154 | }, 155 | "update_period": { 156 | "type": "integer", 157 | "format": "uint64", 158 | "minimum": 0.0 159 | }, 160 | "validators": { 161 | "type": "array", 162 | "items": { 163 | "type": "string" 164 | } 165 | } 166 | }, 167 | "additionalProperties": false 168 | } 169 | }, 170 | "additionalProperties": false 171 | }, 172 | { 173 | "type": "object", 174 | "required": [ 175 | "register_government_proposals_query" 176 | ], 177 | "properties": { 178 | "register_government_proposals_query": { 179 | "type": "object", 180 | "required": [ 181 | "connection_id", 182 | "proposals_ids", 183 | "update_period" 184 | ], 185 | "properties": { 186 | "connection_id": { 187 | "type": "string" 188 | }, 189 | "proposals_ids": { 190 | "type": "array", 191 | "items": { 192 | "type": "integer", 193 | "format": "uint64", 194 | "minimum": 0.0 195 | } 196 | }, 197 | "update_period": { 198 | "type": "integer", 199 | "format": "uint64", 200 | "minimum": 0.0 201 | } 202 | }, 203 | "additionalProperties": false 204 | } 205 | }, 206 | "additionalProperties": false 207 | }, 208 | { 209 | "type": "object", 210 | "required": [ 211 | "register_transfers_query" 212 | ], 213 | "properties": { 214 | "register_transfers_query": { 215 | "type": "object", 216 | "required": [ 217 | "connection_id", 218 | "recipient", 219 | "update_period" 220 | ], 221 | "properties": { 222 | "connection_id": { 223 | "type": "string" 224 | }, 225 | "min_height": { 226 | "type": [ 227 | "integer", 228 | "null" 229 | ], 230 | "format": "uint64", 231 | "minimum": 0.0 232 | }, 233 | "recipient": { 234 | "type": "string" 235 | }, 236 | "update_period": { 237 | "type": "integer", 238 | "format": "uint64", 239 | "minimum": 0.0 240 | } 241 | }, 242 | "additionalProperties": false 243 | } 244 | }, 245 | "additionalProperties": false 246 | }, 247 | { 248 | "type": "object", 249 | "required": [ 250 | "register_delegator_delegations_query" 251 | ], 252 | "properties": { 253 | "register_delegator_delegations_query": { 254 | "type": "object", 255 | "required": [ 256 | "connection_id", 257 | "delegator", 258 | "update_period", 259 | "validators" 260 | ], 261 | "properties": { 262 | "connection_id": { 263 | "type": "string" 264 | }, 265 | "delegator": { 266 | "type": "string" 267 | }, 268 | "update_period": { 269 | "type": "integer", 270 | "format": "uint64", 271 | "minimum": 0.0 272 | }, 273 | "validators": { 274 | "type": "array", 275 | "items": { 276 | "type": "string" 277 | } 278 | } 279 | }, 280 | "additionalProperties": false 281 | } 282 | }, 283 | "additionalProperties": false 284 | }, 285 | { 286 | "type": "object", 287 | "required": [ 288 | "register_delegator_unbonding_delegations_query" 289 | ], 290 | "properties": { 291 | "register_delegator_unbonding_delegations_query": { 292 | "type": "object", 293 | "required": [ 294 | "connection_id", 295 | "delegator", 296 | "update_period", 297 | "validators" 298 | ], 299 | "properties": { 300 | "connection_id": { 301 | "type": "string" 302 | }, 303 | "delegator": { 304 | "type": "string" 305 | }, 306 | "update_period": { 307 | "type": "integer", 308 | "format": "uint64", 309 | "minimum": 0.0 310 | }, 311 | "validators": { 312 | "type": "array", 313 | "items": { 314 | "type": "string" 315 | } 316 | } 317 | }, 318 | "additionalProperties": false 319 | } 320 | }, 321 | "additionalProperties": false 322 | }, 323 | { 324 | "type": "object", 325 | "required": [ 326 | "register_cw20_balance_query" 327 | ], 328 | "properties": { 329 | "register_cw20_balance_query": { 330 | "type": "object", 331 | "required": [ 332 | "account_address", 333 | "connection_id", 334 | "cw20_contract_address", 335 | "update_period" 336 | ], 337 | "properties": { 338 | "account_address": { 339 | "type": "string" 340 | }, 341 | "connection_id": { 342 | "type": "string" 343 | }, 344 | "cw20_contract_address": { 345 | "type": "string" 346 | }, 347 | "update_period": { 348 | "type": "integer", 349 | "format": "uint64", 350 | "minimum": 0.0 351 | } 352 | }, 353 | "additionalProperties": false 354 | } 355 | }, 356 | "additionalProperties": false 357 | }, 358 | { 359 | "type": "object", 360 | "required": [ 361 | "update_interchain_query" 362 | ], 363 | "properties": { 364 | "update_interchain_query": { 365 | "type": "object", 366 | "required": [ 367 | "new_keys", 368 | "new_update_period", 369 | "query_id" 370 | ], 371 | "properties": { 372 | "new_keys": { 373 | "type": "array", 374 | "items": { 375 | "$ref": "#/definitions/KvKey" 376 | } 377 | }, 378 | "new_recipient": { 379 | "type": [ 380 | "string", 381 | "null" 382 | ] 383 | }, 384 | "new_update_period": { 385 | "type": "integer", 386 | "format": "uint64", 387 | "minimum": 0.0 388 | }, 389 | "query_id": { 390 | "type": "integer", 391 | "format": "uint64", 392 | "minimum": 0.0 393 | } 394 | }, 395 | "additionalProperties": false 396 | } 397 | }, 398 | "additionalProperties": false 399 | }, 400 | { 401 | "type": "object", 402 | "required": [ 403 | "remove_interchain_query" 404 | ], 405 | "properties": { 406 | "remove_interchain_query": { 407 | "type": "object", 408 | "required": [ 409 | "query_id" 410 | ], 411 | "properties": { 412 | "query_id": { 413 | "type": "integer", 414 | "format": "uint64", 415 | "minimum": 0.0 416 | } 417 | }, 418 | "additionalProperties": false 419 | } 420 | }, 421 | "additionalProperties": false 422 | } 423 | ], 424 | "definitions": { 425 | "KvKey": { 426 | "type": "object", 427 | "required": [ 428 | "key", 429 | "path" 430 | ], 431 | "properties": { 432 | "key": { 433 | "description": "Key you want to read from the storage", 434 | "type": "array", 435 | "items": { 436 | "type": "integer", 437 | "format": "uint8", 438 | "minimum": 0.0 439 | } 440 | }, 441 | "path": { 442 | "description": "Path (storage prefix) to the storage where you want to read value by key (usually name of cosmos-sdk module: 'staking', 'bank', etc.)", 443 | "type": "string" 444 | } 445 | }, 446 | "additionalProperties": false 447 | } 448 | } 449 | } 450 | -------------------------------------------------------------------------------- /contracts/neutron_interchain_queries/schema/instantiate_msg.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json-schema.org/draft-07/schema#", 3 | "title": "InstantiateMsg", 4 | "type": "object", 5 | "additionalProperties": false 6 | } 7 | -------------------------------------------------------------------------------- /contracts/neutron_interchain_queries/schema/query_msg.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json-schema.org/draft-07/schema#", 3 | "title": "QueryMsg", 4 | "oneOf": [ 5 | { 6 | "type": "object", 7 | "required": [ 8 | "balance" 9 | ], 10 | "properties": { 11 | "balance": { 12 | "type": "object", 13 | "required": [ 14 | "query_id" 15 | ], 16 | "properties": { 17 | "query_id": { 18 | "type": "integer", 19 | "format": "uint64", 20 | "minimum": 0.0 21 | } 22 | }, 23 | "additionalProperties": false 24 | } 25 | }, 26 | "additionalProperties": false 27 | }, 28 | { 29 | "type": "object", 30 | "required": [ 31 | "bank_total_supply" 32 | ], 33 | "properties": { 34 | "bank_total_supply": { 35 | "type": "object", 36 | "required": [ 37 | "query_id" 38 | ], 39 | "properties": { 40 | "query_id": { 41 | "type": "integer", 42 | "format": "uint64", 43 | "minimum": 0.0 44 | } 45 | }, 46 | "additionalProperties": false 47 | } 48 | }, 49 | "additionalProperties": false 50 | }, 51 | { 52 | "type": "object", 53 | "required": [ 54 | "distribution_fee_pool" 55 | ], 56 | "properties": { 57 | "distribution_fee_pool": { 58 | "type": "object", 59 | "required": [ 60 | "query_id" 61 | ], 62 | "properties": { 63 | "query_id": { 64 | "type": "integer", 65 | "format": "uint64", 66 | "minimum": 0.0 67 | } 68 | }, 69 | "additionalProperties": false 70 | } 71 | }, 72 | "additionalProperties": false 73 | }, 74 | { 75 | "type": "object", 76 | "required": [ 77 | "staking_validators" 78 | ], 79 | "properties": { 80 | "staking_validators": { 81 | "type": "object", 82 | "required": [ 83 | "query_id" 84 | ], 85 | "properties": { 86 | "query_id": { 87 | "type": "integer", 88 | "format": "uint64", 89 | "minimum": 0.0 90 | } 91 | }, 92 | "additionalProperties": false 93 | } 94 | }, 95 | "additionalProperties": false 96 | }, 97 | { 98 | "type": "object", 99 | "required": [ 100 | "validators_signing_infos" 101 | ], 102 | "properties": { 103 | "validators_signing_infos": { 104 | "type": "object", 105 | "required": [ 106 | "query_id" 107 | ], 108 | "properties": { 109 | "query_id": { 110 | "type": "integer", 111 | "format": "uint64", 112 | "minimum": 0.0 113 | } 114 | }, 115 | "additionalProperties": false 116 | } 117 | }, 118 | "additionalProperties": false 119 | }, 120 | { 121 | "type": "object", 122 | "required": [ 123 | "government_proposals" 124 | ], 125 | "properties": { 126 | "government_proposals": { 127 | "type": "object", 128 | "required": [ 129 | "query_id" 130 | ], 131 | "properties": { 132 | "query_id": { 133 | "type": "integer", 134 | "format": "uint64", 135 | "minimum": 0.0 136 | } 137 | }, 138 | "additionalProperties": false 139 | } 140 | }, 141 | "additionalProperties": false 142 | }, 143 | { 144 | "type": "object", 145 | "required": [ 146 | "get_delegations" 147 | ], 148 | "properties": { 149 | "get_delegations": { 150 | "type": "object", 151 | "required": [ 152 | "query_id" 153 | ], 154 | "properties": { 155 | "query_id": { 156 | "type": "integer", 157 | "format": "uint64", 158 | "minimum": 0.0 159 | } 160 | }, 161 | "additionalProperties": false 162 | } 163 | }, 164 | "additionalProperties": false 165 | }, 166 | { 167 | "type": "object", 168 | "required": [ 169 | "get_unbonding_delegations" 170 | ], 171 | "properties": { 172 | "get_unbonding_delegations": { 173 | "type": "object", 174 | "required": [ 175 | "query_id" 176 | ], 177 | "properties": { 178 | "query_id": { 179 | "type": "integer", 180 | "format": "uint64", 181 | "minimum": 0.0 182 | } 183 | }, 184 | "additionalProperties": false 185 | } 186 | }, 187 | "additionalProperties": false 188 | }, 189 | { 190 | "type": "object", 191 | "required": [ 192 | "cw20_balance" 193 | ], 194 | "properties": { 195 | "cw20_balance": { 196 | "type": "object", 197 | "required": [ 198 | "query_id" 199 | ], 200 | "properties": { 201 | "query_id": { 202 | "type": "integer", 203 | "format": "uint64", 204 | "minimum": 0.0 205 | } 206 | }, 207 | "additionalProperties": false 208 | } 209 | }, 210 | "additionalProperties": false 211 | }, 212 | { 213 | "type": "object", 214 | "required": [ 215 | "get_registered_query" 216 | ], 217 | "properties": { 218 | "get_registered_query": { 219 | "type": "object", 220 | "required": [ 221 | "query_id" 222 | ], 223 | "properties": { 224 | "query_id": { 225 | "type": "integer", 226 | "format": "uint64", 227 | "minimum": 0.0 228 | } 229 | }, 230 | "additionalProperties": false 231 | } 232 | }, 233 | "additionalProperties": false 234 | }, 235 | { 236 | "type": "object", 237 | "required": [ 238 | "get_recipient_txs" 239 | ], 240 | "properties": { 241 | "get_recipient_txs": { 242 | "type": "object", 243 | "required": [ 244 | "recipient" 245 | ], 246 | "properties": { 247 | "recipient": { 248 | "type": "string" 249 | } 250 | }, 251 | "additionalProperties": false 252 | } 253 | }, 254 | "additionalProperties": false 255 | } 256 | ] 257 | } 258 | -------------------------------------------------------------------------------- /contracts/neutron_interchain_queries/src/bin/neutron_interchain_queries_schema.rs: -------------------------------------------------------------------------------- 1 | use std::env::current_dir; 2 | use std::fs::create_dir_all; 3 | 4 | use cosmwasm_schema::{export_schema, remove_schemas, schema_for}; 5 | use neutron_interchain_queries::msg::{ExecuteMsg, InstantiateMsg, QueryMsg}; 6 | 7 | fn main() { 8 | let mut out_dir = current_dir().unwrap(); 9 | out_dir.push("schema"); 10 | create_dir_all(&out_dir).unwrap(); 11 | remove_schemas(&out_dir).unwrap(); 12 | 13 | export_schema(&schema_for!(InstantiateMsg), &out_dir); 14 | export_schema(&schema_for!(ExecuteMsg), &out_dir); 15 | export_schema(&schema_for!(QueryMsg), &out_dir); 16 | } 17 | -------------------------------------------------------------------------------- /contracts/neutron_interchain_queries/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![warn(clippy::unwrap_used, clippy::expect_used)] 2 | 3 | pub mod contract; 4 | pub mod msg; 5 | pub mod state; 6 | 7 | #[allow(clippy::unwrap_used)] 8 | #[cfg(test)] 9 | mod testing; 10 | -------------------------------------------------------------------------------- /contracts/neutron_interchain_queries/src/msg.rs: -------------------------------------------------------------------------------- 1 | use crate::state::Transfer; 2 | use cosmwasm_std::Uint128; 3 | use neutron_std::types::neutron::interchainqueries::KvKey; 4 | use schemars::JsonSchema; 5 | use serde::{Deserialize, Serialize}; 6 | 7 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 8 | pub struct InstantiateMsg {} 9 | 10 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 11 | #[serde(rename_all = "snake_case")] 12 | pub enum ExecuteMsg { 13 | RegisterBalancesQuery { 14 | connection_id: String, 15 | update_period: u64, 16 | addr: String, 17 | denoms: Vec, 18 | }, 19 | RegisterBankTotalSupplyQuery { 20 | connection_id: String, 21 | update_period: u64, 22 | denoms: Vec, 23 | }, 24 | RegisterDistributionFeePoolQuery { 25 | connection_id: String, 26 | update_period: u64, 27 | }, 28 | RegisterStakingValidatorsQuery { 29 | connection_id: String, 30 | update_period: u64, 31 | validators: Vec, 32 | }, 33 | RegisterValidatorsSigningInfosQuery { 34 | connection_id: String, 35 | update_period: u64, 36 | validators: Vec, 37 | }, 38 | RegisterGovernmentProposalsQuery { 39 | connection_id: String, 40 | proposals_ids: Vec, 41 | update_period: u64, 42 | }, 43 | RegisterTransfersQuery { 44 | connection_id: String, 45 | update_period: u64, 46 | recipient: String, 47 | min_height: Option, 48 | }, 49 | RegisterDelegatorDelegationsQuery { 50 | delegator: String, 51 | validators: Vec, 52 | connection_id: String, 53 | update_period: u64, 54 | }, 55 | RegisterDelegatorUnbondingDelegationsQuery { 56 | delegator: String, 57 | validators: Vec, 58 | connection_id: String, 59 | update_period: u64, 60 | }, 61 | RegisterCw20BalanceQuery { 62 | connection_id: String, 63 | update_period: u64, 64 | cw20_contract_address: String, 65 | account_address: String, 66 | }, 67 | UpdateInterchainQuery { 68 | query_id: u64, 69 | new_keys: Vec, 70 | new_update_period: u64, 71 | new_recipient: Option, 72 | }, 73 | RemoveInterchainQuery { 74 | query_id: u64, 75 | }, 76 | } 77 | 78 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 79 | #[serde(rename_all = "snake_case")] 80 | pub enum QueryMsg { 81 | Balance { query_id: u64 }, 82 | BankTotalSupply { query_id: u64 }, 83 | DistributionFeePool { query_id: u64 }, 84 | StakingValidators { query_id: u64 }, 85 | ValidatorsSigningInfos { query_id: u64 }, 86 | GovernmentProposals { query_id: u64 }, 87 | GetDelegations { query_id: u64 }, 88 | GetUnbondingDelegations { query_id: u64 }, 89 | Cw20Balance { query_id: u64 }, 90 | GetRegisteredQuery { query_id: u64 }, 91 | GetRecipientTxs { recipient: String }, 92 | } 93 | 94 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 95 | #[serde(rename_all = "snake_case")] 96 | pub struct Cw20BalanceResponse { 97 | pub balance: Uint128, 98 | } 99 | 100 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 101 | #[serde(rename_all = "snake_case")] 102 | pub struct GetRecipientTxsResponse { 103 | pub transfers: Vec, 104 | } 105 | 106 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 107 | pub struct MigrateMsg {} 108 | -------------------------------------------------------------------------------- /contracts/neutron_interchain_queries/src/state.rs: -------------------------------------------------------------------------------- 1 | use cw_storage_plus::{Item, Map}; 2 | use schemars::JsonSchema; 3 | use serde::{Deserialize, Serialize}; 4 | 5 | pub type Recipient = str; 6 | 7 | /// contains all transfers mapped by a recipient address observed by the contract. 8 | pub const RECIPIENT_TXS: Map<&Recipient, Vec> = Map::new("recipient_txs"); 9 | /// contains number of transfers to addresses observed by the contract. 10 | pub const TRANSFERS: Item = Item::new("transfers"); 11 | 12 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 13 | pub struct Transfer { 14 | pub recipient: String, 15 | pub sender: String, 16 | pub denom: String, 17 | pub amount: String, 18 | } 19 | -------------------------------------------------------------------------------- /contracts/neutron_interchain_queries/src/testing/mock_querier.rs: -------------------------------------------------------------------------------- 1 | use cosmwasm_std::testing::{MockApi, MockQuerier, MockStorage}; 2 | use cosmwasm_std::{ 3 | from_json, Binary, Coin, ContractResult, CustomQuery, GrpcQuery, OwnedDeps, Querier, 4 | QuerierResult, QueryRequest, SystemError, SystemResult, Uint128, 5 | }; 6 | use neutron_std::types::neutron::interchainqueries::{ 7 | QueryRegisteredQueryRequest, QueryRegisteredQueryResultRequest, 8 | }; 9 | use schemars::JsonSchema; 10 | use serde::{Deserialize, Serialize}; 11 | use std::collections::HashMap; 12 | use std::marker::PhantomData; 13 | 14 | pub const MOCK_CONTRACT_ADDR: &str = "cosmos2contract"; 15 | 16 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 17 | #[serde(rename_all = "snake_case")] 18 | pub struct CustomQueryWrapper {} 19 | 20 | // implement custom query 21 | impl CustomQuery for CustomQueryWrapper {} 22 | 23 | pub fn mock_dependencies( 24 | contract_balance: &[Coin], 25 | ) -> OwnedDeps { 26 | let contract_addr = MOCK_CONTRACT_ADDR; 27 | let custom_querier: WasmMockQuerier = 28 | WasmMockQuerier::new(MockQuerier::new(&[(contract_addr, contract_balance)])); 29 | 30 | OwnedDeps { 31 | storage: MockStorage::default(), 32 | api: MockApi::default(), 33 | querier: custom_querier, 34 | custom_query_type: PhantomData, 35 | } 36 | } 37 | 38 | pub struct WasmMockQuerier { 39 | base: MockQuerier, 40 | query_responses: HashMap, 41 | registered_queries: HashMap, 42 | } 43 | 44 | impl Querier for WasmMockQuerier { 45 | fn raw_query(&self, bin_request: &[u8]) -> QuerierResult { 46 | let request: QueryRequest = match from_json(bin_request) { 47 | Ok(v) => v, 48 | Err(e) => { 49 | return QuerierResult::Err(SystemError::InvalidRequest { 50 | error: format!("Parsing query request: {}", e), 51 | request: bin_request.into(), 52 | }); 53 | } 54 | }; 55 | self.handle_query(&request) 56 | } 57 | } 58 | 59 | impl WasmMockQuerier { 60 | pub fn handle_query(&self, request: &QueryRequest) -> QuerierResult { 61 | match &request { 62 | QueryRequest::Grpc(GrpcQuery { path, data }) => { 63 | if path == "/neutron.interchainqueries.Query/QueryResult" { 64 | let request: QueryRegisteredQueryResultRequest = 65 | ::prost::Message::decode(&data[..]).unwrap(); 66 | SystemResult::Ok(ContractResult::Ok( 67 | (*self.query_responses.get(&request.query_id).unwrap()).clone(), 68 | )) 69 | } else if path == "/neutron.interchainqueries.Query/RegisteredQuery" { 70 | let request: QueryRegisteredQueryRequest = 71 | ::prost::Message::decode(&data[..]).unwrap(); 72 | SystemResult::Ok(ContractResult::Ok( 73 | (*self.registered_queries.get(&request.query_id).unwrap()).clone(), 74 | )) 75 | } else { 76 | self.base.handle_query(request) 77 | } 78 | } 79 | _ => self.base.handle_query(request), 80 | } 81 | } 82 | 83 | pub fn add_query_response(&mut self, query_id: u64, response: Binary) { 84 | self.query_responses.insert(query_id, response); 85 | } 86 | pub fn add_registered_queries(&mut self, query_id: u64, response: Binary) { 87 | self.registered_queries.insert(query_id, response); 88 | } 89 | } 90 | 91 | #[derive(Clone, Default)] 92 | pub struct BalanceQuerier { 93 | _balances: HashMap, 94 | } 95 | 96 | #[derive(Clone, Default)] 97 | pub struct TokenQuerier { 98 | _balances: HashMap>, 99 | } 100 | 101 | impl WasmMockQuerier { 102 | pub fn new(base: MockQuerier) -> Self { 103 | WasmMockQuerier { 104 | base, 105 | query_responses: HashMap::new(), 106 | registered_queries: HashMap::new(), 107 | } 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /contracts/neutron_interchain_queries/src/testing/mod.rs: -------------------------------------------------------------------------------- 1 | mod mock_querier; 2 | mod tests; 3 | -------------------------------------------------------------------------------- /contracts/neutron_interchain_txs/.cargo/config: -------------------------------------------------------------------------------- 1 | [alias] 2 | wasm = "build --release --target wasm32-unknown-unknown" 3 | wasm-debug = "build --target wasm32-unknown-unknown" 4 | unit-test = "test --lib" 5 | integration-test = "test --test integration" 6 | schema = "run --bin neutron_interchain_txs_schema" 7 | -------------------------------------------------------------------------------- /contracts/neutron_interchain_txs/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "neutron_interchain_txs" 3 | version = "0.1.0" 4 | authors = ["ratik "] 5 | edition = "2021" 6 | 7 | exclude = [ 8 | # Those files are rust-optimizer artifacts. You might want to commit them for convenience but they should not be part of the source code publication. 9 | "contract.wasm", 10 | "hash.txt", 11 | ] 12 | 13 | [lib] 14 | crate-type = ["cdylib", "rlib"] 15 | 16 | [features] 17 | library = [] 18 | 19 | [dependencies] 20 | cosmwasm-std = { workspace = true } 21 | cw2 = { workspace = true } 22 | schemars = { workspace = true } 23 | serde = { workspace = true } 24 | serde-json-wasm = { workspace = true } 25 | cw-storage-plus = { workspace = true } 26 | cosmos-sdk-proto = { workspace = true } 27 | neutron-sdk = { path = "../../packages/neutron-sdk", default-features = false } 28 | prost-types = { workspace = true } 29 | cosmwasm-schema = { workspace = true } 30 | neutron-std = { workspace = true } -------------------------------------------------------------------------------- /contracts/neutron_interchain_txs/Makefile: -------------------------------------------------------------------------------- 1 | CURRENT_DIR = $(shell pwd) 2 | CURRENT_DIR_RELATIVE = $(notdir $(shell pwd)) 3 | 4 | clippy: 5 | rustup component add clippy || true 6 | cargo clippy --all-targets --all-features --workspace -- -D warnings 7 | 8 | test: clippy 9 | cargo unit-test 10 | -------------------------------------------------------------------------------- /contracts/neutron_interchain_txs/README.md: -------------------------------------------------------------------------------- 1 | # Neutron Interchain Txs Example Contract 2 | 3 | The example contract shows how to use and interact with [Interchain Txs Module](https://docs.neutron.org/neutron/modules/interchain-txs/overview). 4 | 5 | ## How to test 6 | 7 | 1. run `make build` in the root folder of `neutron-sdk/` 8 | 2. set up [Localnet](https://docs.neutron.org/neutron/build-and-run/localnet) 9 | 3. cd `scripts/` 10 | 4. `./test_intechain_txs.sh` (or `NEUTRON_DIR=/path/to/somedir/ ./test_interchain_txs.sh` if the neutron dir is not `../../neutron/`) 11 | -------------------------------------------------------------------------------- /contracts/neutron_interchain_txs/schema/execute_msg.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json-schema.org/draft-07/schema#", 3 | "title": "ExecuteMsg", 4 | "oneOf": [ 5 | { 6 | "type": "object", 7 | "required": [ 8 | "register" 9 | ], 10 | "properties": { 11 | "register": { 12 | "type": "object", 13 | "required": [ 14 | "connection_id", 15 | "interchain_account_id", 16 | "register_fee" 17 | ], 18 | "properties": { 19 | "connection_id": { 20 | "type": "string" 21 | }, 22 | "interchain_account_id": { 23 | "type": "string" 24 | }, 25 | "ordering": { 26 | "anyOf": [ 27 | { 28 | "$ref": "#/definitions/Order" 29 | }, 30 | { 31 | "type": "null" 32 | } 33 | ] 34 | }, 35 | "register_fee": { 36 | "type": "array", 37 | "items": { 38 | "$ref": "#/definitions/Coin" 39 | } 40 | } 41 | }, 42 | "additionalProperties": false 43 | } 44 | }, 45 | "additionalProperties": false 46 | }, 47 | { 48 | "type": "object", 49 | "required": [ 50 | "delegate" 51 | ], 52 | "properties": { 53 | "delegate": { 54 | "type": "object", 55 | "required": [ 56 | "amount", 57 | "denom", 58 | "interchain_account_id", 59 | "validator" 60 | ], 61 | "properties": { 62 | "amount": { 63 | "type": "integer", 64 | "format": "uint128", 65 | "minimum": 0.0 66 | }, 67 | "denom": { 68 | "type": "string" 69 | }, 70 | "interchain_account_id": { 71 | "type": "string" 72 | }, 73 | "timeout": { 74 | "type": [ 75 | "integer", 76 | "null" 77 | ], 78 | "format": "uint64", 79 | "minimum": 0.0 80 | }, 81 | "validator": { 82 | "type": "string" 83 | } 84 | }, 85 | "additionalProperties": false 86 | } 87 | }, 88 | "additionalProperties": false 89 | }, 90 | { 91 | "type": "object", 92 | "required": [ 93 | "undelegate" 94 | ], 95 | "properties": { 96 | "undelegate": { 97 | "type": "object", 98 | "required": [ 99 | "amount", 100 | "denom", 101 | "interchain_account_id", 102 | "validator" 103 | ], 104 | "properties": { 105 | "amount": { 106 | "type": "integer", 107 | "format": "uint128", 108 | "minimum": 0.0 109 | }, 110 | "denom": { 111 | "type": "string" 112 | }, 113 | "interchain_account_id": { 114 | "type": "string" 115 | }, 116 | "timeout": { 117 | "type": [ 118 | "integer", 119 | "null" 120 | ], 121 | "format": "uint64", 122 | "minimum": 0.0 123 | }, 124 | "validator": { 125 | "type": "string" 126 | } 127 | }, 128 | "additionalProperties": false 129 | } 130 | }, 131 | "additionalProperties": false 132 | } 133 | ], 134 | "definitions": { 135 | "Coin": { 136 | "description": "Coin defines a token with a denomination and an amount.\n\nNOTE: The amount field is an Int which implements the custom method signatures required by gogoproto.", 137 | "type": "object", 138 | "required": [ 139 | "amount", 140 | "denom" 141 | ], 142 | "properties": { 143 | "amount": { 144 | "type": "string" 145 | }, 146 | "denom": { 147 | "type": "string" 148 | } 149 | }, 150 | "additionalProperties": false 151 | }, 152 | "Order": { 153 | "description": "Order defines if a channel is ORDERED or UNORDERED", 154 | "oneOf": [ 155 | { 156 | "description": "zero-value for channel ordering", 157 | "type": "string", 158 | "enum": [ 159 | "NoneUnspecified" 160 | ] 161 | }, 162 | { 163 | "description": "packets can be delivered in any order, which may differ from the order in which they were sent.", 164 | "type": "string", 165 | "enum": [ 166 | "Unordered" 167 | ] 168 | }, 169 | { 170 | "description": "packets are delivered exactly in the order which they were sent", 171 | "type": "string", 172 | "enum": [ 173 | "Ordered" 174 | ] 175 | } 176 | ] 177 | } 178 | } 179 | } 180 | -------------------------------------------------------------------------------- /contracts/neutron_interchain_txs/schema/instantiate_msg.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json-schema.org/draft-07/schema#", 3 | "title": "InstantiateMsg", 4 | "type": "object", 5 | "additionalProperties": false 6 | } 7 | -------------------------------------------------------------------------------- /contracts/neutron_interchain_txs/schema/migrate_msg.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json-schema.org/draft-07/schema#", 3 | "title": "MigrateMsg", 4 | "type": "object", 5 | "additionalProperties": false 6 | } 7 | -------------------------------------------------------------------------------- /contracts/neutron_interchain_txs/schema/query_msg.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json-schema.org/draft-07/schema#", 3 | "title": "QueryMsg", 4 | "oneOf": [ 5 | { 6 | "description": "query stored ICA from Neutron", 7 | "type": "object", 8 | "required": [ 9 | "interchain_account_address" 10 | ], 11 | "properties": { 12 | "interchain_account_address": { 13 | "type": "object", 14 | "required": [ 15 | "connection_id", 16 | "interchain_account_id" 17 | ], 18 | "properties": { 19 | "connection_id": { 20 | "type": "string" 21 | }, 22 | "interchain_account_id": { 23 | "type": "string" 24 | } 25 | }, 26 | "additionalProperties": false 27 | } 28 | }, 29 | "additionalProperties": false 30 | }, 31 | { 32 | "description": "query ICA from contract store, saved during processing the acknowledgement", 33 | "type": "object", 34 | "required": [ 35 | "interchain_account_address_from_contract" 36 | ], 37 | "properties": { 38 | "interchain_account_address_from_contract": { 39 | "type": "object", 40 | "required": [ 41 | "interchain_account_id" 42 | ], 43 | "properties": { 44 | "interchain_account_id": { 45 | "type": "string" 46 | } 47 | }, 48 | "additionalProperties": false 49 | } 50 | }, 51 | "additionalProperties": false 52 | }, 53 | { 54 | "type": "object", 55 | "required": [ 56 | "acknowledgement_result" 57 | ], 58 | "properties": { 59 | "acknowledgement_result": { 60 | "type": "object", 61 | "required": [ 62 | "interchain_account_id", 63 | "sequence_id" 64 | ], 65 | "properties": { 66 | "interchain_account_id": { 67 | "type": "string" 68 | }, 69 | "sequence_id": { 70 | "type": "integer", 71 | "format": "uint64", 72 | "minimum": 0.0 73 | } 74 | }, 75 | "additionalProperties": false 76 | } 77 | }, 78 | "additionalProperties": false 79 | }, 80 | { 81 | "type": "object", 82 | "required": [ 83 | "errors_queue" 84 | ], 85 | "properties": { 86 | "errors_queue": { 87 | "type": "object", 88 | "additionalProperties": false 89 | } 90 | }, 91 | "additionalProperties": false 92 | } 93 | ] 94 | } 95 | -------------------------------------------------------------------------------- /contracts/neutron_interchain_txs/schema/sudo_msg.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json-schema.org/draft-07/schema#", 3 | "title": "SudoMsg", 4 | "oneOf": [ 5 | { 6 | "type": "object", 7 | "required": [ 8 | "response" 9 | ], 10 | "properties": { 11 | "response": { 12 | "type": "object", 13 | "required": [ 14 | "data", 15 | "request" 16 | ], 17 | "properties": { 18 | "data": { 19 | "$ref": "#/definitions/Binary" 20 | }, 21 | "request": { 22 | "$ref": "#/definitions/RequestPacket" 23 | } 24 | }, 25 | "additionalProperties": false 26 | } 27 | }, 28 | "additionalProperties": false 29 | }, 30 | { 31 | "type": "object", 32 | "required": [ 33 | "error" 34 | ], 35 | "properties": { 36 | "error": { 37 | "type": "object", 38 | "required": [ 39 | "details", 40 | "request" 41 | ], 42 | "properties": { 43 | "details": { 44 | "type": "string" 45 | }, 46 | "request": { 47 | "$ref": "#/definitions/RequestPacket" 48 | } 49 | }, 50 | "additionalProperties": false 51 | } 52 | }, 53 | "additionalProperties": false 54 | }, 55 | { 56 | "type": "object", 57 | "required": [ 58 | "timeout" 59 | ], 60 | "properties": { 61 | "timeout": { 62 | "type": "object", 63 | "required": [ 64 | "request" 65 | ], 66 | "properties": { 67 | "request": { 68 | "$ref": "#/definitions/RequestPacket" 69 | } 70 | }, 71 | "additionalProperties": false 72 | } 73 | }, 74 | "additionalProperties": false 75 | }, 76 | { 77 | "type": "object", 78 | "required": [ 79 | "open_ack" 80 | ], 81 | "properties": { 82 | "open_ack": { 83 | "type": "object", 84 | "required": [ 85 | "channel_id", 86 | "counterparty_channel_id", 87 | "counterparty_version", 88 | "port_id" 89 | ], 90 | "properties": { 91 | "channel_id": { 92 | "type": "string" 93 | }, 94 | "counterparty_channel_id": { 95 | "type": "string" 96 | }, 97 | "counterparty_version": { 98 | "type": "string" 99 | }, 100 | "port_id": { 101 | "type": "string" 102 | } 103 | }, 104 | "additionalProperties": false 105 | } 106 | }, 107 | "additionalProperties": false 108 | }, 109 | { 110 | "type": "object", 111 | "required": [ 112 | "tx_query_result" 113 | ], 114 | "properties": { 115 | "tx_query_result": { 116 | "type": "object", 117 | "required": [ 118 | "data", 119 | "height", 120 | "query_id" 121 | ], 122 | "properties": { 123 | "data": { 124 | "$ref": "#/definitions/Binary" 125 | }, 126 | "height": { 127 | "$ref": "#/definitions/Height" 128 | }, 129 | "query_id": { 130 | "type": "integer", 131 | "format": "uint64", 132 | "minimum": 0.0 133 | } 134 | }, 135 | "additionalProperties": false 136 | } 137 | }, 138 | "additionalProperties": false 139 | }, 140 | { 141 | "type": "object", 142 | "required": [ 143 | "kv_query_result" 144 | ], 145 | "properties": { 146 | "kv_query_result": { 147 | "type": "object", 148 | "required": [ 149 | "query_id" 150 | ], 151 | "properties": { 152 | "query_id": { 153 | "type": "integer", 154 | "format": "uint64", 155 | "minimum": 0.0 156 | } 157 | }, 158 | "additionalProperties": false 159 | } 160 | }, 161 | "additionalProperties": false 162 | } 163 | ], 164 | "definitions": { 165 | "Binary": { 166 | "description": "Binary is a wrapper around Vec to add base64 de/serialization with serde. It also adds some helper methods to help encode inline.\n\nThis is only needed as serde-json-{core,wasm} has a horrible encoding for Vec. See also .", 167 | "type": "string" 168 | }, 169 | "Height": { 170 | "description": "Height is used for sudo call for `TxQueryResult` enum variant type", 171 | "type": "object", 172 | "properties": { 173 | "revision_height": { 174 | "description": "*height** is a height of remote chain", 175 | "default": 0, 176 | "type": "integer", 177 | "format": "uint64", 178 | "minimum": 0.0 179 | }, 180 | "revision_number": { 181 | "description": "the revision that the client is currently on", 182 | "default": 0, 183 | "type": "integer", 184 | "format": "uint64", 185 | "minimum": 0.0 186 | } 187 | }, 188 | "additionalProperties": false 189 | }, 190 | "RequestPacket": { 191 | "type": "object", 192 | "properties": { 193 | "data": { 194 | "anyOf": [ 195 | { 196 | "$ref": "#/definitions/Binary" 197 | }, 198 | { 199 | "type": "null" 200 | } 201 | ] 202 | }, 203 | "destination_channel": { 204 | "type": [ 205 | "string", 206 | "null" 207 | ] 208 | }, 209 | "destination_port": { 210 | "type": [ 211 | "string", 212 | "null" 213 | ] 214 | }, 215 | "sequence": { 216 | "type": [ 217 | "integer", 218 | "null" 219 | ], 220 | "format": "uint64", 221 | "minimum": 0.0 222 | }, 223 | "source_channel": { 224 | "type": [ 225 | "string", 226 | "null" 227 | ] 228 | }, 229 | "source_port": { 230 | "type": [ 231 | "string", 232 | "null" 233 | ] 234 | }, 235 | "timeout_height": { 236 | "anyOf": [ 237 | { 238 | "$ref": "#/definitions/RequestPacketTimeoutHeight" 239 | }, 240 | { 241 | "type": "null" 242 | } 243 | ] 244 | }, 245 | "timeout_timestamp": { 246 | "type": [ 247 | "integer", 248 | "null" 249 | ], 250 | "format": "uint64", 251 | "minimum": 0.0 252 | } 253 | }, 254 | "additionalProperties": false 255 | }, 256 | "RequestPacketTimeoutHeight": { 257 | "type": "object", 258 | "properties": { 259 | "revision_height": { 260 | "type": [ 261 | "integer", 262 | "null" 263 | ], 264 | "format": "uint64", 265 | "minimum": 0.0 266 | }, 267 | "revision_number": { 268 | "type": [ 269 | "integer", 270 | "null" 271 | ], 272 | "format": "uint64", 273 | "minimum": 0.0 274 | } 275 | }, 276 | "additionalProperties": false 277 | } 278 | } 279 | } 280 | -------------------------------------------------------------------------------- /contracts/neutron_interchain_txs/src/bin/neutron_interchain_txs_schema.rs: -------------------------------------------------------------------------------- 1 | use cosmwasm_schema::{export_schema, remove_schemas, schema_for}; 2 | use neutron_interchain_txs::msg::{ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg}; 3 | use neutron_sdk::sudo::msg::SudoMsg; 4 | use std::env::current_dir; 5 | use std::fs::create_dir_all; 6 | 7 | fn main() { 8 | let mut out_dir = current_dir().unwrap(); 9 | out_dir.push("schema"); 10 | create_dir_all(&out_dir).unwrap(); 11 | remove_schemas(&out_dir).unwrap(); 12 | 13 | export_schema(&schema_for!(InstantiateMsg), &out_dir); 14 | export_schema(&schema_for!(MigrateMsg), &out_dir); 15 | export_schema(&schema_for!(SudoMsg), &out_dir); 16 | export_schema(&schema_for!(QueryMsg), &out_dir); 17 | export_schema(&schema_for!(ExecuteMsg), &out_dir); 18 | } 19 | -------------------------------------------------------------------------------- /contracts/neutron_interchain_txs/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![warn(clippy::unwrap_used, clippy::expect_used)] 2 | 3 | extern crate core; 4 | 5 | pub mod contract; 6 | pub mod msg; 7 | 8 | mod storage; 9 | 10 | #[allow(clippy::unwrap_used)] 11 | #[cfg(test)] 12 | mod testing; 13 | -------------------------------------------------------------------------------- /contracts/neutron_interchain_txs/src/msg.rs: -------------------------------------------------------------------------------- 1 | use neutron_std::types::cosmos::base::v1beta1::Coin; 2 | use neutron_std::types::ibc::core::channel::v1::Order; 3 | use schemars::JsonSchema; 4 | use serde::{Deserialize, Serialize}; 5 | 6 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 7 | #[serde(rename_all = "snake_case")] 8 | pub enum QueryMsg { 9 | /// query stored ICA from Neutron 10 | InterchainAccountAddress { 11 | interchain_account_id: String, 12 | connection_id: String, 13 | }, 14 | /// query ICA from contract store, saved during processing the acknowledgement 15 | InterchainAccountAddressFromContract { 16 | interchain_account_id: String, 17 | }, 18 | // this query returns acknowledgement result after interchain transaction 19 | AcknowledgementResult { 20 | interchain_account_id: String, 21 | sequence_id: u64, 22 | }, 23 | // this query returns non-critical errors list 24 | ErrorsQueue {}, 25 | } 26 | 27 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 28 | pub struct MigrateMsg {} 29 | 30 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 31 | pub struct InstantiateMsg {} 32 | 33 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 34 | #[serde(rename_all = "snake_case")] 35 | pub enum ExecuteMsg { 36 | Register { 37 | connection_id: String, 38 | interchain_account_id: String, 39 | register_fee: Vec, 40 | ordering: Option, 41 | }, 42 | Delegate { 43 | interchain_account_id: String, 44 | validator: String, 45 | amount: u128, 46 | denom: String, 47 | timeout: Option, 48 | }, 49 | Undelegate { 50 | interchain_account_id: String, 51 | validator: String, 52 | amount: u128, 53 | denom: String, 54 | timeout: Option, 55 | }, 56 | } 57 | -------------------------------------------------------------------------------- /contracts/neutron_interchain_txs/src/storage.rs: -------------------------------------------------------------------------------- 1 | use cosmwasm_std::{from_json, to_json_vec, Binary, Order, StdResult, Storage}; 2 | use cw_storage_plus::{Item, Map}; 3 | use schemars::JsonSchema; 4 | use serde::{Deserialize, Serialize}; 5 | 6 | /// SudoPayload is a type that stores information about a transaction that we try to execute 7 | /// on the host chain. This is a type introduced for our convenience. 8 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 9 | #[serde(rename_all = "snake_case")] 10 | pub struct SudoPayload { 11 | pub message: String, 12 | pub port_id: String, 13 | } 14 | 15 | pub const SUDO_PAYLOAD_REPLY_ID: u64 = 1; 16 | 17 | pub const REPLY_ID_STORAGE: Item> = Item::new("reply_queue_id"); 18 | pub const SUDO_PAYLOAD: Map<(String, u64), Vec> = Map::new("sudo_payload"); 19 | pub const INTERCHAIN_ACCOUNTS: Map> = 20 | Map::new("interchain_accounts"); 21 | 22 | // interchain transaction responses - ack/err/timeout state to query later 23 | pub const ACKNOWLEDGEMENT_RESULTS: Map<(String, u64), AcknowledgementResult> = 24 | Map::new("acknowledgement_results"); 25 | 26 | pub const ERRORS_QUEUE: Map = Map::new("errors_queue"); 27 | 28 | /// Serves for storing acknowledgement calls for interchain transactions 29 | #[derive(Serialize, Deserialize, Clone, PartialEq, Eq, JsonSchema, Debug)] 30 | #[serde(rename_all = "snake_case")] 31 | pub enum AcknowledgementResult { 32 | /// Success - Got success acknowledgement in sudo with array of message item types in it 33 | Success(Vec), 34 | /// Error - Got error acknowledgement in sudo with payload message in it and error details 35 | Error((String, String)), 36 | /// Timeout - Got timeout acknowledgement in sudo with payload message in it 37 | Timeout(String), 38 | } 39 | 40 | pub fn save_reply_payload(store: &mut dyn Storage, payload: SudoPayload) -> StdResult<()> { 41 | REPLY_ID_STORAGE.save(store, &to_json_vec(&payload)?) 42 | } 43 | 44 | pub fn read_reply_payload(store: &dyn Storage) -> StdResult { 45 | let data = REPLY_ID_STORAGE.load(store)?; 46 | from_json(Binary::new(data)) 47 | } 48 | 49 | pub fn add_error_to_queue(store: &mut dyn Storage, error_msg: String) -> Option<()> { 50 | let result = ERRORS_QUEUE 51 | .keys(store, None, None, Order::Descending) 52 | .next() 53 | .and_then(|data| data.ok()) 54 | .map(|c| c + 1) 55 | .or(Some(0)); 56 | 57 | result.and_then(|idx| ERRORS_QUEUE.save(store, idx, &error_msg).ok()) 58 | } 59 | 60 | pub fn read_errors_from_queue(store: &dyn Storage) -> StdResult, String)>> { 61 | ERRORS_QUEUE 62 | .range_raw(store, None, None, Order::Ascending) 63 | .collect() 64 | } 65 | 66 | pub fn read_sudo_payload( 67 | store: &dyn Storage, 68 | channel_id: String, 69 | seq_id: u64, 70 | ) -> StdResult { 71 | let data = SUDO_PAYLOAD.load(store, (channel_id, seq_id))?; 72 | from_json(Binary::new(data)) 73 | } 74 | 75 | pub fn save_sudo_payload( 76 | store: &mut dyn Storage, 77 | channel_id: String, 78 | seq_id: u64, 79 | payload: SudoPayload, 80 | ) -> StdResult<()> { 81 | SUDO_PAYLOAD.save(store, (channel_id, seq_id), &to_json_vec(&payload)?) 82 | } 83 | -------------------------------------------------------------------------------- /contracts/neutron_interchain_txs/src/testing/mod.rs: -------------------------------------------------------------------------------- 1 | mod tests; 2 | -------------------------------------------------------------------------------- /contracts/neutron_interchain_txs/src/testing/tests.rs: -------------------------------------------------------------------------------- 1 | use std::marker::PhantomData; 2 | 3 | use crate::{ 4 | contract::query_errors_queue, 5 | storage::{add_error_to_queue, read_errors_from_queue, ERRORS_QUEUE}, 6 | }; 7 | 8 | use cosmwasm_std::{ 9 | from_json, 10 | testing::{MockApi, MockQuerier, MockStorage}, 11 | OwnedDeps, 12 | }; 13 | 14 | pub fn mock_dependencies() -> OwnedDeps { 15 | OwnedDeps { 16 | storage: MockStorage::default(), 17 | api: MockApi::default(), 18 | querier: MockQuerier::default(), 19 | custom_query_type: PhantomData, 20 | } 21 | } 22 | 23 | #[test] 24 | fn test_query_errors_queue() { 25 | let mut deps = mock_dependencies(); 26 | 27 | let result = query_errors_queue(deps.as_ref()).unwrap(); 28 | let result: Vec<(Vec, String)> = from_json(result).unwrap(); 29 | 30 | assert_eq!(0, result.len()); 31 | 32 | let error_msg = "Error message".to_string(); 33 | 34 | ERRORS_QUEUE 35 | .save(&mut deps.storage, 0u32, &error_msg) 36 | .unwrap(); 37 | 38 | let result = query_errors_queue(deps.as_ref()).unwrap(); 39 | let result: Vec<(Vec, String)> = from_json(result).unwrap(); 40 | 41 | assert_eq!(1, result.len()); 42 | } 43 | 44 | #[test] 45 | fn test_errors_queue() { 46 | let mut store = MockStorage::new(); 47 | 48 | let errors = read_errors_from_queue(&store); 49 | let errors = errors.unwrap(); 50 | 51 | assert_eq!(0, errors.len()); 52 | 53 | let error = "some error message".to_string(); 54 | 55 | add_error_to_queue(&mut store, error.clone()).unwrap(); 56 | 57 | let errors = read_errors_from_queue(&store); 58 | let errors = errors.unwrap(); 59 | 60 | assert_eq!(1, errors.len()); 61 | assert_eq!(errors, vec![(0u32.to_be_bytes().to_vec(), error.clone())]); 62 | 63 | add_error_to_queue(&mut store, error.clone()).unwrap(); 64 | add_error_to_queue(&mut store, error.clone()).unwrap(); 65 | 66 | let errors = read_errors_from_queue(&store); 67 | let errors = errors.unwrap(); 68 | 69 | assert_eq!(3, errors.len()); 70 | assert_eq!( 71 | errors, 72 | vec![ 73 | (0u32.to_be_bytes().to_vec(), error.clone()), 74 | (1u32.to_be_bytes().to_vec(), error.clone()), 75 | (2u32.to_be_bytes().to_vec(), error) 76 | ] 77 | ); 78 | } 79 | -------------------------------------------------------------------------------- /packages/neutron-sdk/.cargo/config: -------------------------------------------------------------------------------- 1 | [alias] 2 | wasm = "build --release --target wasm32-unknown-unknown" 3 | wasm-debug = "build --target wasm32-unknown-unknown" 4 | unit-test = "test --lib" 5 | schema = "run --bin neutron_sdk_schema" -------------------------------------------------------------------------------- /packages/neutron-sdk/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "neutron-sdk" 3 | description = "Neutron CosmWasm SDK for interacting with Neutron blockchain" 4 | version = "0.11.0" 5 | edition = "2021" 6 | license = "Apache-2.0" 7 | repository = "https://github.com/neutron-org/neutron-sdk" 8 | homepage = "https://neutron.org" 9 | readme = "README.md" 10 | 11 | [dependencies] 12 | cosmwasm-std = { workspace = true, features = ["cosmwasm_2_0"] } 13 | cosmos-sdk-proto = { workspace = true } 14 | serde = { workspace = true, features = ["derive"] } 15 | serde-cw-value = "0.7.0" 16 | schemars = { workspace = true } 17 | serde-json-wasm = { workspace = true } 18 | bech32 = { workspace = true } 19 | thiserror = { workspace = true } 20 | protobuf = { workspace = true } 21 | serde_json = { workspace = true } 22 | cosmwasm-schema = { workspace = true } 23 | prost = { workspace = true } 24 | prost-types = { workspace = true } 25 | tendermint-proto = { workspace = true } 26 | speedate = { workspace = true } 27 | chrono = { version = "0.4.22", default-features = false } 28 | neutron-std = { workspace = true } 29 | 30 | [dev-dependencies] 31 | base64 = { workspace = true } 32 | prost-types = { workspace = true } 33 | hex = { workspace = true } 34 | -------------------------------------------------------------------------------- /packages/neutron-sdk/README.md: -------------------------------------------------------------------------------- 1 | # Neutron Cosmwasm SDK 2 | 3 | The CosmWasm library with helper methods and structures for interacting with [Neutron blockchain](https://github.com/neutron-org/neutron) 4 | 5 | ## Overview 6 | 7 | The Neutron SDK consists of the following subpackages: 8 | 9 | | Package | Reference | Description | 10 | |---------------------------------|--------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------| 11 | | Neutron Interchain Queries | https://github.com/neutron-org/neutron-sdk/tree/main/packages/neutron-sdk/src/interchain_queries | Queries, messages and helper methods for interacting with Neutron Interchain Queries Module | 12 | | Neutron Interchain Transactions | https://github.com/neutron-org/neutron-sdk/tree/main/packages/neutron-sdk/src/interchain_txs | Queries, messages and helper methods for interacting with Neutron Interchain Transactions Module | 13 | | Neutron Bindings | https://github.com/neutron-org/neutron-sdk/tree/main/packages/neutron-sdk/src/bindings | Structures and helper methods for interacting with Neutron blockchain | 14 | | Neutron Sudo | https://github.com/neutron-org/neutron-sdk/tree/main/packages/neutron-sdk/src/sudo | Structures for Sudo Contract callbacks from Neutron blockchain | 15 | | Neutron Errors | https://github.com/neutron-org/neutron-sdk/tree/main/packages/neutron-sdk/src/errors | Structures and helpers for Neutron specific error and result types | 16 | | Neutron Proto Types | https://github.com/neutron-org/neutron-sdk/tree/main/packages/neutron-sdk/src/proto_types | Neutron specific protobuf types. | 17 | 18 | ## Documentation 19 | 20 | Check out our documentation at https://docs.neutron.org. 21 | 22 | ## License 23 | 24 | This package is part of the [neutron-sdk](https://github.com/neutron-org/neutron-sdk) repository, licensed under the Apache 25 | License 2.0 (see [NOTICE](https://github.com/neutron-org/neutron-sdk/blob/main/NOTICE) 26 | and [LICENSE](https://github.com/neutron-org/neutron-sdk/blob/main/LICENSE)). -------------------------------------------------------------------------------- /packages/neutron-sdk/src/bin/neutron_sdk_schema.rs: -------------------------------------------------------------------------------- 1 | use std::env::current_dir; 2 | use std::fs::create_dir_all; 3 | 4 | use cosmwasm_schema::{export_schema, remove_schemas, schema_for}; 5 | #[allow(deprecated)] 6 | use neutron_sdk::bindings::msg::NeutronMsg; 7 | 8 | fn main() { 9 | let mut out_dir = current_dir().unwrap(); 10 | out_dir.push("schema"); 11 | create_dir_all(&out_dir).unwrap(); 12 | remove_schemas(&out_dir).unwrap(); 13 | #[allow(deprecated)] 14 | export_schema(&schema_for!(NeutronMsg), &out_dir); 15 | } 16 | -------------------------------------------------------------------------------- /packages/neutron-sdk/src/bindings/mod.rs: -------------------------------------------------------------------------------- 1 | #[allow(deprecated)] 2 | pub mod msg; 3 | -------------------------------------------------------------------------------- /packages/neutron-sdk/src/bindings/msg.rs: -------------------------------------------------------------------------------- 1 | use cosmwasm_std::{Binary, CosmosMsg, CustomMsg}; 2 | use neutron_std::shim::Any; 3 | use schemars::JsonSchema; 4 | use serde::{Deserialize, Serialize}; 5 | 6 | #[deprecated( 7 | note = "Please use neutron-std grpc messages instead of wasmbindings", 8 | since = "0.12.0" 9 | )] 10 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 11 | #[serde(rename_all = "snake_case")] 12 | /// A number of Custom messages that can call into the Neutron bindings. 13 | pub enum NeutronMsg { 14 | /// SubmitAdminProposal sends a proposal to neutron's Admin module. 15 | /// This type of messages can be only executed by Neutron DAO. 16 | SubmitAdminProposal { admin_proposal: AdminProposal }, 17 | } 18 | 19 | impl From for CosmosMsg { 20 | fn from(msg: NeutronMsg) -> CosmosMsg { 21 | CosmosMsg::Custom(msg) 22 | } 23 | } 24 | 25 | impl CustomMsg for NeutronMsg {} 26 | 27 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 28 | #[serde(rename_all = "snake_case")] 29 | /// AdminProposal defines the struct for various proposals which Neutron's Admin Module may accept. 30 | pub enum AdminProposal { 31 | /// Proposal to change params. Note that this works for old params. 32 | /// New params has their own `MsgUpdateParams` msgs that can be supplied to `ProposalExecuteMessage` 33 | ParamChangeProposal(ParamChangeProposal), 34 | 35 | #[deprecated( 36 | since = "0.11.0", 37 | note = "Used only for querying old proposals. Will fail if executed in a new proposal. Use ProposalExecuteMessage instead" 38 | )] 39 | /// Deprecated. Proposal to upgrade IBC client 40 | UpgradeProposal(UpgradeProposal), 41 | 42 | #[deprecated( 43 | since = "0.11.0", 44 | note = "Used only for querying old proposals. Will fail if executed in a new proposal. Use ProposalExecuteMessage instead" 45 | )] 46 | /// Deprecated. Proposal to update IBC client 47 | ClientUpdateProposal(ClientUpdateProposal), 48 | 49 | /// Proposal to execute CosmosMsg. 50 | ProposalExecuteMessage(ProposalExecuteMessage), 51 | 52 | #[deprecated( 53 | since = "0.7.0", 54 | note = "Used only for querying old proposals. Will fail if executed in a new proposal. Use ProposalExecuteMessage instead" 55 | )] 56 | /// Deprecated. Proposal to upgrade network 57 | SoftwareUpgradeProposal(SoftwareUpgradeProposal), 58 | 59 | #[deprecated( 60 | since = "0.7.0", 61 | note = "Used only for querying old proposals. Will fail if executed in a new proposal. Use ProposalExecuteMessage instead" 62 | )] 63 | /// Deprecated. Proposal to cancel existing software upgrade 64 | CancelSoftwareUpgradeProposal(CancelSoftwareUpgradeProposal), 65 | 66 | /// Deprecated. Will fail to execute if you use it. 67 | #[deprecated( 68 | since = "0.7.0", 69 | note = "Used only for querying old proposals. Will fail if executed in a new proposal. Use ProposalExecuteMessage instead" 70 | )] 71 | /// Deprecated. Proposal to pin wasm contract codes 72 | PinCodesProposal(PinCodesProposal), 73 | 74 | #[deprecated( 75 | since = "0.7.0", 76 | note = "Used only for querying old proposals. Will fail if executed in a new proposal. Use ProposalExecuteMessage instead" 77 | )] 78 | /// Deprecated. Deprecated. Proposal to unpin wasm contract codes. 79 | UnpinCodesProposal(UnpinCodesProposal), 80 | 81 | #[deprecated( 82 | since = "0.7.0", 83 | note = "Used only for querying old proposals. Will fail if executed in a new proposal. Use ProposalExecuteMessage instead" 84 | )] 85 | /// Deprecated. Proposal to call sudo on contract. 86 | SudoContractProposal(SudoContractProposal), 87 | 88 | #[deprecated( 89 | since = "0.7.0", 90 | note = "Used only for querying old proposals. Will fail if executed in a new proposal. Use ProposalExecuteMessage instead" 91 | )] 92 | /// Deprecated. Proposal to update contract admin. 93 | UpdateAdminProposal(UpdateAdminProposal), 94 | 95 | #[deprecated( 96 | since = "0.7.0", 97 | note = "Used only for querying old proposals. Will fail if executed in a new proposal. Use ProposalExecuteMessage instead" 98 | )] 99 | /// Deprecated. Proposal to clear contract admin. 100 | ClearAdminProposal(ClearAdminProposal), 101 | } 102 | 103 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 104 | #[serde(rename_all = "snake_case")] 105 | /// ParamChangeProposal defines the struct for single parameter change proposal. 106 | pub struct ParamChangeProposal { 107 | /// **title** is a text title of proposal. Non unique. 108 | pub title: String, 109 | /// **description** is a text description of proposal. Non unique. 110 | pub description: String, 111 | /// **param_changes** is a vector of params to be changed. Non unique. 112 | pub param_changes: Vec, 113 | } 114 | 115 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 116 | #[serde(rename_all = "snake_case")] 117 | /// ParamChange defines the struct for parameter change request. 118 | pub struct ParamChange { 119 | /// **subspace** is a key of module to which the parameter to change belongs. Unique for each module. 120 | pub subspace: String, 121 | /// **key** is a name of parameter. Unique for subspace. 122 | pub key: String, 123 | /// **value** is a new value for given parameter. Non unique. 124 | pub value: String, 125 | } 126 | 127 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 128 | #[serde(rename_all = "snake_case")] 129 | /// Plan defines the struct for planned upgrade. 130 | pub struct Plan { 131 | /// **name** is a name for the upgrade 132 | pub name: String, 133 | /// **height** is a height at which the upgrade must be performed 134 | pub height: i64, 135 | /// **info** is any application specific upgrade info to be included on-chain 136 | pub info: String, 137 | } 138 | 139 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 140 | #[serde(rename_all = "snake_case")] 141 | #[deprecated( 142 | since = "0.11.0", 143 | note = "Used only for querying old proposals. Will fail if executed in a new proposal. Use ProposalExecuteMessage instead" 144 | )] 145 | /// UpgradeProposal defines the struct for IBC upgrade proposal. 146 | pub struct UpgradeProposal { 147 | /// **title** is a text title of proposal. 148 | pub title: String, 149 | /// **description** is a text description of proposal. 150 | pub description: String, 151 | /// **plan** is a plan of upgrade. 152 | pub plan: Plan, 153 | /// **upgraded_client_state** is an upgraded client state. 154 | pub upgraded_client_state: Any, 155 | } 156 | 157 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 158 | #[serde(rename_all = "snake_case")] 159 | #[deprecated( 160 | since = "0.11.0", 161 | note = "Used only for querying old proposals. Will fail if executed in a new proposal. Use ProposalExecuteMessage instead" 162 | )] 163 | /// ClientUpdateProposal defines the struct for client update proposal. 164 | pub struct ClientUpdateProposal { 165 | /// **title** is a text title of proposal. 166 | pub title: String, 167 | /// **description** is a text description of proposal. Non unique. 168 | pub description: String, 169 | /// **subject_client_id** is a subject client id. 170 | pub subject_client_id: String, 171 | /// **substitute_client_id** is a substitute client id. 172 | pub substitute_client_id: String, 173 | } 174 | 175 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 176 | #[serde(rename_all = "snake_case")] 177 | /// ProposalExecuteMessage defines the struct for sdk47 compatible admin proposal. 178 | pub struct ProposalExecuteMessage { 179 | /// **message** is a json representing an sdk message passed to admin module to execute. 180 | pub message: String, 181 | } 182 | 183 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 184 | #[serde(rename_all = "snake_case")] 185 | /// MsgExecuteContract defines a call to the contract execution 186 | pub struct MsgExecuteContract { 187 | /// **contract** is a contract address that will be called 188 | pub contract: String, 189 | /// **msg** is a contract call message 190 | pub msg: String, 191 | } 192 | 193 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 194 | #[serde(rename_all = "snake_case")] 195 | #[deprecated( 196 | since = "0.7.0", 197 | note = "Used only for querying old proposals. Will fail if executed in a new proposal. Use ProposalExecuteMessage instead" 198 | )] 199 | /// Deprecated. SoftwareUpgradeProposal defines the struct for software upgrade proposal. 200 | pub struct SoftwareUpgradeProposal { 201 | /// **title** is a text title of proposal. Non unique. 202 | pub title: String, 203 | /// **description** is a text description of proposal. Non unique. 204 | pub description: String, 205 | /// **plan** is a plan of upgrade. 206 | pub plan: Plan, 207 | } 208 | 209 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 210 | #[serde(rename_all = "snake_case")] 211 | #[deprecated( 212 | since = "0.7.0", 213 | note = "Used only for querying old proposals. Will fail if executed in a new proposal. Use ProposalExecuteMessage instead" 214 | )] 215 | /// Deprecated. CancelSoftwareUpgradeProposal defines the struct for cancel software upgrade proposal. 216 | pub struct CancelSoftwareUpgradeProposal { 217 | /// **title** is a text title of proposal. Non unique. 218 | pub title: String, 219 | /// **description** is a text description of proposal. Non unique. 220 | pub description: String, 221 | } 222 | 223 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 224 | #[serde(rename_all = "snake_case")] 225 | #[deprecated( 226 | since = "0.7.0", 227 | note = "Used only for querying old proposals. Will fail if executed in a new proposal. Use ProposalExecuteMessage instead" 228 | )] 229 | /// Deprecated. SudoContractProposal defines the struct for sudo execution proposal. 230 | pub struct SudoContractProposal { 231 | /// **title** is a text title of proposal. 232 | pub title: String, 233 | /// **description** is a text description of proposal. 234 | pub description: String, 235 | /// **contract** is an address of contract to be executed. 236 | pub contract: String, 237 | /// ***msg*** is a sudo message. 238 | pub msg: Binary, 239 | } 240 | 241 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 242 | #[serde(rename_all = "snake_case")] 243 | #[deprecated( 244 | since = "0.7.0", 245 | note = "Used only for querying old proposals. Will fail if executed in a new proposal. Use ProposalExecuteMessage instead" 246 | )] 247 | /// Deprecated. PinCodesProposal defines the struct for pin contract codes proposal. 248 | pub struct PinCodesProposal { 249 | /// **title** is a text title of proposal. 250 | pub title: String, 251 | /// **description** is a text description of proposal. 252 | pub description: String, 253 | /// **code_ids** is an array of codes to be pined. 254 | pub code_ids: Vec, 255 | } 256 | 257 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 258 | #[serde(rename_all = "snake_case")] 259 | #[deprecated( 260 | since = "0.7.0", 261 | note = "Used only for querying old proposals. Will fail if executed in a new proposal. Use ProposalExecuteMessage instead" 262 | )] 263 | /// Deprecated. UnpinCodesProposal defines the struct for unpin contract codes proposal. 264 | pub struct UnpinCodesProposal { 265 | /// **title** is a text title of proposal. 266 | pub title: String, 267 | /// **description** is a text description of proposal. 268 | pub description: String, 269 | /// **code_ids** is an array of codes to be unpined. 270 | pub code_ids: Vec, 271 | } 272 | 273 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 274 | #[serde(rename_all = "snake_case")] 275 | #[deprecated( 276 | since = "0.7.0", 277 | note = "Used only for querying old proposals. Will fail if executed in a new proposal. Use ProposalExecuteMessage instead" 278 | )] 279 | /// Deprecated. UpdateAdminProposal defines the struct for update admin proposal. 280 | pub struct UpdateAdminProposal { 281 | /// **title** is a text title of proposal. 282 | pub title: String, 283 | /// **description** is a text description of proposal. 284 | pub description: String, 285 | /// ***new_admin*** is an address of new admin 286 | pub new_admin: String, 287 | /// **contract** is an address of contract to update admin. 288 | pub contract: String, 289 | } 290 | 291 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 292 | #[serde(rename_all = "snake_case")] 293 | #[deprecated( 294 | since = "0.7.0", 295 | note = "Used only for querying old proposals. Will fail if executed in a new proposal. Use ProposalExecuteMessage instead" 296 | )] 297 | /// Deprecated. SudoContractProposal defines the struct for clear admin proposal. 298 | pub struct ClearAdminProposal { 299 | /// **title** is a text title of proposal. 300 | pub title: String, 301 | /// **description** is a text description of proposal. 302 | pub description: String, 303 | /// **contract** is an address of contract admin will be removed. 304 | pub contract: String, 305 | } 306 | -------------------------------------------------------------------------------- /packages/neutron-sdk/src/errors/error.rs: -------------------------------------------------------------------------------- 1 | use cosmwasm_std::{Decimal256RangeExceeded, DecimalRangeExceeded, OverflowError, StdError}; 2 | use serde_json_wasm; 3 | use thiserror::Error; 4 | 5 | pub type NeutronResult = Result; 6 | 7 | #[derive(Error, Debug, PartialEq)] 8 | pub enum NeutronError { 9 | #[error("{0}")] 10 | Std(#[from] StdError), 11 | 12 | #[error("{0}")] 13 | Fmt(#[from] std::fmt::Error), 14 | 15 | #[error("{0}")] 16 | FromUTF8Error(#[from] std::string::FromUtf8Error), 17 | 18 | #[error("Bech32 error")] 19 | Bech32(#[from] bech32::Error), 20 | 21 | #[error("Prost protobuf error")] 22 | ProstProtobuf(#[from] prost::DecodeError), 23 | 24 | #[error("Serde JSON (Wasm) error")] 25 | SerdeJSONWasm(String), 26 | 27 | #[error("address length should be max {max:?} bytes, got {actual:?}")] 28 | MaxAddrLength { max: usize, actual: usize }, 29 | 30 | #[error("invalid reply id: {0}")] 31 | InvalidReplyID(u64), 32 | 33 | #[error("invalid query type: {query_type:?}")] 34 | InvalidQueryType { query_type: String }, 35 | 36 | #[error("Decimal range exceeded")] 37 | DecimalRangeExceeded(#[from] DecimalRangeExceeded), 38 | 39 | #[error("Decimal256 range exceeded")] 40 | Decimal256RangeExceeded(#[from] Decimal256RangeExceeded), 41 | 42 | #[error("Overflow error")] 43 | OverflowError(#[from] OverflowError), 44 | 45 | #[error("Invalid query result format: {0}")] 46 | InvalidQueryResultFormat(String), 47 | 48 | #[error("Integration tests mock is active")] 49 | IntegrationTestsMock {}, 50 | 51 | #[error("Can't deconstruct account denom balance key: {0}")] 52 | AccountDenomBalanceKeyDeconstructionError(String), 53 | } 54 | 55 | impl From for NeutronError { 56 | fn from(e: serde_json_wasm::de::Error) -> Self { 57 | NeutronError::SerdeJSONWasm(e.to_string()) 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /packages/neutron-sdk/src/errors/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod error; 2 | -------------------------------------------------------------------------------- /packages/neutron-sdk/src/interchain_queries/helpers.rs: -------------------------------------------------------------------------------- 1 | use crate::errors::error::{NeutronError, NeutronResult}; 2 | use crate::interchain_queries::types::{ 3 | AddressBytes, QueryPayload, QueryType, TransactionFilterItem, MAX_ADDR_LEN, 4 | }; 5 | use cosmwasm_std::{Addr, CosmosMsg, StdError, Uint128, Uint256}; 6 | use neutron_std::types::neutron::interchainqueries::{ 7 | KvKey, MsgRegisterInterchainQuery, MsgRemoveInterchainQueryRequest, 8 | MsgUpdateInterchainQueryRequest, 9 | }; 10 | use serde_json_wasm::to_string; 11 | use std::fmt::Write as _; 12 | 13 | /// Decodes a bech32 encoded string and converts to base64 encoded bytes 14 | /// 15 | pub fn decode_and_convert(encoded: &str) -> NeutronResult { 16 | let (_hrp, bytes, _variant) = bech32::decode(encoded)?; 17 | 18 | Ok(bech32::convert_bits(&bytes, 5, 8, false)?) 19 | } 20 | 21 | /// Prefixes the address bytes with its length 22 | pub fn length_prefix>(addr: AddrBytes) -> NeutronResult> { 23 | let bz_length = addr.as_ref().len(); 24 | 25 | if bz_length == 0 { 26 | return Ok(vec![]); 27 | } 28 | 29 | if bz_length > MAX_ADDR_LEN { 30 | return Err(NeutronError::MaxAddrLength { 31 | max: MAX_ADDR_LEN, 32 | actual: bz_length, 33 | }); 34 | } 35 | 36 | let mut p: Vec = vec![bz_length as u8]; 37 | p.extend_from_slice(addr.as_ref()); 38 | 39 | Ok(p) 40 | } 41 | 42 | pub fn uint256_to_u128(value: Uint256) -> Result { 43 | let converted: Uint128 = value 44 | .try_into() 45 | .map_err(|_| StdError::generic_err("Uint256 value exceeds u128 limits"))?; 46 | Ok(converted.u128()) 47 | } 48 | 49 | /// Basic helper to define a register interchain query message: 50 | /// * **contract** is a contract address that registers the interchain query. 51 | /// Must be equal to the contract that sends the message. 52 | /// * **query** is a query type identifier ('tx' or 'kv' for now) with a payload: 53 | /// - when the query enum is 'kv' then payload is the KV-storage keys for which we want to get 54 | /// values from remote chain; 55 | /// - when the query enum is 'tx' then payload is the filters for transaction search ICQ, 56 | /// maximum allowed number of filters is 32. 57 | /// * **connection_id** is an IBC connection identifier between Neutron and remote chain; 58 | /// * **update_period** is used to say how often (in neutron blocks) the query must be updated. 59 | pub fn register_interchain_query( 60 | contract: Addr, 61 | query: QueryPayload, 62 | connection_id: String, 63 | update_period: u64, 64 | ) -> NeutronResult { 65 | Ok(match query { 66 | QueryPayload::KV(keys) => MsgRegisterInterchainQuery { 67 | sender: contract.to_string(), 68 | query_type: QueryType::KV.into(), 69 | keys, 70 | transactions_filter: String::new(), 71 | connection_id, 72 | update_period, 73 | }, 74 | QueryPayload::TX(transactions_filters) => MsgRegisterInterchainQuery { 75 | sender: contract.to_string(), 76 | query_type: QueryType::TX.into(), 77 | keys: vec![], 78 | transactions_filter: to_string(&transactions_filters) 79 | .map_err(|e| StdError::generic_err(e.to_string()))?, 80 | connection_id, 81 | update_period, 82 | }, 83 | } 84 | .into()) 85 | } 86 | 87 | /// Basic helper to define a update interchain query message: 88 | /// * **contract** is a contract address that updates the interchain query. 89 | /// Must be equal to the contract that sends the message. 90 | /// * **query_id** is ID of the query we want to update; 91 | /// * **new_keys** is encoded keys to query; 92 | /// * **new_update_period** is used to say how often (in neutron blocks) the query must be updated. 93 | pub fn update_interchain_query( 94 | contract: Addr, 95 | query_id: u64, 96 | new_keys: Vec, 97 | new_update_period: u64, 98 | new_transactions_filter: Option>, 99 | ) -> NeutronResult { 100 | Ok(MsgUpdateInterchainQueryRequest { 101 | sender: contract.to_string(), 102 | query_id, 103 | new_keys, 104 | new_update_period, 105 | new_transactions_filter: match new_transactions_filter { 106 | Some(filters) => { 107 | to_string(&filters).map_err(|e| StdError::generic_err(e.to_string()))? 108 | } 109 | None => "".to_string(), 110 | }, 111 | } 112 | .into()) 113 | } 114 | 115 | /// Basic helper to define a remove interchain query message: 116 | /// * **contract** is a contract address that removes the interchain query. 117 | /// Must be equal to the contract that sends the message. 118 | /// * **query_id** is ID of the query we want to remove. 119 | pub fn remove_interchain_query(contract: Addr, query_id: u64) -> NeutronResult { 120 | Ok(MsgRemoveInterchainQueryRequest { 121 | sender: contract.to_string(), 122 | query_id, 123 | } 124 | .into()) 125 | } 126 | 127 | const KV_PATH_KEY_DELIMITER: &str = "/"; 128 | 129 | pub fn kv_key_from_string>(s: S) -> Option { 130 | let split: Vec<&str> = s.as_ref().split(KV_PATH_KEY_DELIMITER).collect(); 131 | if split.len() < 2 { 132 | return None; 133 | } 134 | 135 | Some(KvKey { 136 | path: split[0].to_string(), 137 | key: decode_hex(split[1])?, 138 | }) 139 | } 140 | 141 | /// Encodes bytes slice into hex string 142 | pub fn encode_hex(bytes: &[u8]) -> String { 143 | let mut s = String::with_capacity(bytes.len() * 2); 144 | for &b in bytes { 145 | let _ = write!(s, "{:02x}", b); 146 | } 147 | s 148 | } 149 | 150 | /// Decodes hex string into bytes vec 151 | pub fn decode_hex(s: &str) -> Option> { 152 | (0..s.len()) 153 | .step_by(2) 154 | .map(|i| u8::from_str_radix(&s[i..i + 2], 16).ok()) 155 | .collect() 156 | } 157 | -------------------------------------------------------------------------------- /packages/neutron-sdk/src/interchain_queries/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod helpers; 2 | pub mod queries; 3 | pub mod types; 4 | pub mod v045; 5 | pub mod v047; 6 | 7 | pub use queries::{check_query_type, get_registered_query, query_kv_result}; 8 | -------------------------------------------------------------------------------- /packages/neutron-sdk/src/interchain_queries/queries.rs: -------------------------------------------------------------------------------- 1 | use crate::errors::error::NeutronResult; 2 | use crate::interchain_queries::types::{KVReconstruct, QueryType}; 3 | use crate::NeutronError; 4 | use cosmwasm_std::{Deps, StdError}; 5 | use neutron_std::types::neutron::interchainqueries::{ 6 | InterchainqueriesQuerier, QueryResult, RegisteredQuery, 7 | }; 8 | 9 | /// Checks **actual** query type is **expected** query type 10 | pub fn check_query_type(actual: String, expected: QueryType) -> NeutronResult<()> { 11 | let expected_str: String = expected.into(); 12 | if actual != expected_str { 13 | return Err(NeutronError::InvalidQueryType { query_type: actual }); 14 | } 15 | Ok(()) 16 | } 17 | 18 | /// Queries registered query info 19 | pub fn get_registered_query( 20 | deps: Deps, 21 | interchain_query_id: u64, 22 | ) -> NeutronResult { 23 | let querier = InterchainqueriesQuerier::new(&deps.querier); 24 | let query_res = querier.registered_query(interchain_query_id)?; 25 | let res = query_res 26 | .registered_query 27 | .ok_or_else(|| StdError::generic_err("no registered query"))?; 28 | Ok(res) 29 | } 30 | 31 | /// Reads submitted raw KV values for Interchain Query with **query_id** from the storage and reconstructs the result 32 | pub fn query_kv_result(deps: Deps, query_id: u64) -> NeutronResult { 33 | let registered_query_result = get_raw_interchain_query_result(deps, query_id)?; 34 | KVReconstruct::reconstruct(registered_query_result.kv_results.as_slice()) 35 | } 36 | 37 | /// Queries raw interchain query result (raw KV storage values or transactions) from Interchain Queries Module. 38 | /// Usually it is better to implement [KVReconstruct] for your own type and then use [query_kv_result], 39 | /// but in cases when Rust forbids to implement foreign trait [KVReconstruct] for some foreign type, 40 | /// it is possible to use [get_raw_interchain_query_result] and reconstruct query result manually. 41 | pub fn get_raw_interchain_query_result( 42 | deps: Deps, 43 | interchain_query_id: u64, 44 | ) -> NeutronResult { 45 | let querier = InterchainqueriesQuerier::new(&deps.querier); 46 | let query_res = querier.query_result(interchain_query_id)?; 47 | let res = query_res 48 | .result 49 | .ok_or_else(|| StdError::generic_err("no result in registered query"))?; 50 | 51 | Ok(res) 52 | } 53 | -------------------------------------------------------------------------------- /packages/neutron-sdk/src/interchain_queries/types.rs: -------------------------------------------------------------------------------- 1 | use crate::errors::error::NeutronResult; 2 | use cosmwasm_std::{from_json, StdError, Uint128}; 3 | use neutron_std::types::neutron::interchainqueries::{KvKey, StorageValue}; 4 | use schemars::{JsonSchema, _serde_json::Value}; 5 | use serde::{Deserialize, Deserializer, Serialize, Serializer}; 6 | 7 | pub const QUERY_TYPE_KV_VALUE: &str = "kv"; 8 | pub const QUERY_TYPE_TX_VALUE: &str = "tx"; 9 | 10 | /// Maximum length of address 11 | pub const MAX_ADDR_LEN: usize = 255; 12 | 13 | #[derive(Serialize, Deserialize, PartialEq, Eq, Debug)] 14 | pub enum TransactionFilterOp { 15 | Eq, 16 | Lt, 17 | Gt, 18 | Lte, 19 | Gte, 20 | } 21 | 22 | #[derive(PartialEq, Eq, Debug)] 23 | pub enum TransactionFilterValue { 24 | String(String), 25 | Int(u64), 26 | } 27 | 28 | impl<'de> Deserialize<'de> for TransactionFilterValue { 29 | fn deserialize(deserializer: D) -> Result 30 | where 31 | D: Deserializer<'de>, 32 | { 33 | use serde::de::Error; 34 | 35 | let v = Value::deserialize(deserializer)?; 36 | let n = v.as_u64(); 37 | if let Some(n) = n { 38 | Ok(Self::Int(n)) 39 | } else { 40 | let n = v 41 | .as_str() 42 | .ok_or_else(|| D::Error::custom("Value must be number or string"))?; 43 | Ok(Self::String(n.to_string())) 44 | } 45 | } 46 | } 47 | 48 | impl Serialize for TransactionFilterValue { 49 | fn serialize(&self, serializer: S) -> Result 50 | where 51 | S: Serializer, 52 | { 53 | match self { 54 | TransactionFilterValue::String(v) => serializer.serialize_str(v), 55 | TransactionFilterValue::Int(v) => serializer.serialize_u64(*v), 56 | } 57 | } 58 | } 59 | 60 | #[derive(Serialize, Deserialize, Debug)] 61 | pub struct TransactionFilterItem { 62 | pub field: String, 63 | pub op: TransactionFilterOp, 64 | pub value: TransactionFilterValue, 65 | } 66 | 67 | #[derive(Serialize, Deserialize, Copy, Clone, Debug, PartialEq, Eq, JsonSchema)] 68 | /// Describes possible interchain query types 69 | pub enum QueryType { 70 | #[serde(rename = "kv")] 71 | /// **kv** is an interchain query type to query KV values from remote chain 72 | KV, 73 | 74 | /// **tx** is an interchain query type to query transactions from remote chain 75 | #[serde(rename = "tx")] 76 | TX, 77 | } 78 | 79 | #[allow(clippy::from_over_into)] 80 | impl Into for QueryType { 81 | fn into(self) -> String { 82 | match self { 83 | QueryType::KV => QUERY_TYPE_KV_VALUE.to_string(), 84 | QueryType::TX => QUERY_TYPE_TX_VALUE.to_string(), 85 | } 86 | } 87 | } 88 | 89 | /// Describes possible interchain query types with a payload 90 | pub enum QueryPayload { 91 | /// **kv** is an interchain query type to query KV values from remote chain 92 | /// payload is kvkeys 93 | KV(Vec), 94 | 95 | /// **tx** is an interchain query type to query transactions from remote chain 96 | /// payload is transactions filter 97 | TX(Vec), 98 | } 99 | 100 | /// Bytes representations of Bech32 address 101 | pub type AddressBytes = Vec; 102 | 103 | /// A **data structure** that can be reconstructed from slice of **StorageValue** structures. 104 | /// Neutron provides `KVReconstruct` for many primitive and standard Cosmos-SDK types and query responses. 105 | /// 106 | /// Third-party projects may provide `KVReconstruct` implementations for types that they introduce. 107 | /// For example if some query is not implemented in Neutron standard library, developers can create their own type/query and implement `KVReconstruct` for it. 108 | /// 109 | /// 110 | /// Usually used together with `query_kv_result` function. For example, there is an Interchain Query with some `query_id` to query balance from remote chain. 111 | /// And there is an implemented `KVReconstruct` for `Balance` structure. 112 | /// So you can easily get reconstructed response for the query just in one line: 113 | /// ```rust ignore 114 | /// let balances: Balances = query_kv_result(deps, query_id)?; 115 | /// ``` 116 | /// 117 | /// Anyone can implement `KVReconstruct` for any type and use `query_kv_result` without any problems. 118 | pub trait KVReconstruct: Sized { 119 | /// Reconstructs this value from the slice of **StorageValue**'s. 120 | fn reconstruct(kvs: &[StorageValue]) -> NeutronResult; 121 | } 122 | 123 | impl KVReconstruct for Uint128 { 124 | fn reconstruct(storage_values: &[StorageValue]) -> NeutronResult { 125 | let value = storage_values 126 | .first() 127 | .ok_or_else(|| StdError::generic_err("empty query result"))?; 128 | let balance: Uint128 = from_json(&value.value)?; 129 | Ok(balance) 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /packages/neutron-sdk/src/interchain_queries/v045/helpers.rs: -------------------------------------------------------------------------------- 1 | use super::types::{GOV_STORE_KEY, VOTES_KEY_PREFIX}; 2 | use crate::errors::error::NeutronResult; 3 | use crate::interchain_queries::helpers::{decode_and_convert, length_prefix}; 4 | use crate::interchain_queries::types::AddressBytes; 5 | use crate::interchain_queries::v045::types::{ 6 | BALANCES_PREFIX, BANK_STORE_KEY, DELEGATION_KEY, FEE_POOL_KEY, PARAMS_STORE_DELIMITER, 7 | PROPOSALS_KEY_PREFIX, SUPPLY_PREFIX, UNBONDING_DELEGATION_KEY, VALIDATORS_KEY, 8 | VALIDATOR_SIGNING_INFO_KEY, WASM_CONTRACT_STORE_PREFIX, 9 | }; 10 | use crate::NeutronError; 11 | use cosmos_sdk_proto::cosmos::staking::v1beta1::Commission as ValidatorCommission; 12 | use cosmwasm_std::{Decimal, Uint128}; 13 | use neutron_std::types::neutron::interchainqueries::KvKey; 14 | use std::str::{from_utf8, FromStr}; 15 | 16 | /// Creates KV key to get **module** param by **key** 17 | pub fn create_params_store_key(module: &str, key: &str) -> Vec { 18 | let mut s = String::with_capacity(module.len() + 1 + key.len()); 19 | s.push_str(module); 20 | s.push_str(PARAMS_STORE_DELIMITER); 21 | s.push_str(key); 22 | 23 | s.into_bytes() 24 | } 25 | 26 | /// Creates balances Cosmos-SDK storage prefix for account with **addr** 27 | /// 28 | pub fn create_account_balances_prefix>( 29 | addr: AddrBytes, 30 | ) -> NeutronResult> { 31 | let mut prefix: Vec = vec![BALANCES_PREFIX]; 32 | prefix.extend_from_slice(length_prefix(addr)?.as_slice()); 33 | 34 | Ok(prefix) 35 | } 36 | 37 | /// Creates **denom** balance Cosmos-SDK storage key for account with **addr** 38 | pub fn create_account_denom_balance_key, S: AsRef>( 39 | addr: AddrBytes, 40 | denom: S, 41 | ) -> NeutronResult> { 42 | let mut account_balance_key = create_account_balances_prefix(addr)?; 43 | account_balance_key.extend_from_slice(denom.as_ref().as_bytes()); 44 | 45 | Ok(account_balance_key) 46 | } 47 | 48 | /// Creates keys for an Interchain Query to get balance of account on remote chain for list of denoms 49 | /// 50 | /// * **addr** address of an account on remote chain for which you want to get balances; 51 | /// * **denoms** denominations of the coins for which you want to get balance; 52 | pub fn create_balances_query_keys(addr: String, denoms: Vec) -> NeutronResult> { 53 | let converted_addr_bytes = decode_and_convert(addr.as_str())?; 54 | let mut kv_keys: Vec = Vec::with_capacity(denoms.len()); 55 | 56 | for denom in denoms { 57 | let balance_key = create_account_denom_balance_key(&converted_addr_bytes, denom)?; 58 | 59 | let kv_key = KvKey { 60 | path: BANK_STORE_KEY.to_string(), 61 | key: balance_key, 62 | }; 63 | 64 | kv_keys.push(kv_key) 65 | } 66 | Ok(kv_keys) 67 | } 68 | 69 | /// Deconstructs a storage key for an **account** balance of a particular **denom**. 70 | /// Returns two values: **address** of an account and **denom** 71 | pub fn deconstruct_account_denom_balance_key>( 72 | key: Key, 73 | ) -> NeutronResult<(AddressBytes, String)> { 74 | let mut key = key.into_iter(); 75 | 76 | // the first element must be BALANCES_PREFIX 77 | let prefix = key 78 | .next() 79 | .ok_or(NeutronError::AccountDenomBalanceKeyDeconstructionError( 80 | "invalid key length".to_string(), 81 | ))?; 82 | if prefix != BALANCES_PREFIX { 83 | return Err(NeutronError::AccountDenomBalanceKeyDeconstructionError( 84 | format!( 85 | "first element in key does not equal to BALANCES_PREFIX: {:?} != {:?}", 86 | prefix, BALANCES_PREFIX 87 | ) 88 | .to_string(), 89 | )); 90 | } 91 | 92 | // next we try read address bytes 93 | let address_length = 94 | key.next() 95 | .ok_or(NeutronError::AccountDenomBalanceKeyDeconstructionError( 96 | "invalid key length".to_string(), 97 | ))?; 98 | let address: AddressBytes = (&mut key).take(address_length as usize).collect(); 99 | if address.len() != address_length as usize { 100 | return Err(NeutronError::AccountDenomBalanceKeyDeconstructionError( 101 | "address length in key is invalid".to_string(), 102 | )); 103 | } 104 | 105 | // and the rest should be denom 106 | let denom = String::from_utf8(key.collect::>())?; 107 | if denom.is_empty() { 108 | return Err(NeutronError::AccountDenomBalanceKeyDeconstructionError( 109 | "denom in key can't be empty".to_string(), 110 | )); 111 | } 112 | 113 | Ok((address, denom)) 114 | } 115 | 116 | /// Creates **denom** balance Cosmos-SDK storage key for account with **addr** 117 | pub fn create_denom_balance_key, S: AsRef>( 118 | addr: AddrBytes, 119 | denom: S, 120 | ) -> NeutronResult> { 121 | let mut account_balance_key = create_account_balances_prefix(addr)?; 122 | account_balance_key.extend_from_slice(denom.as_ref().as_bytes()); 123 | 124 | Ok(account_balance_key) 125 | } 126 | 127 | /// Creates **denom** total Cosmos-SDK storage key for bank module 128 | pub fn create_total_denom_key>(denom: S) -> NeutronResult> { 129 | let mut total_supply: Vec = vec![SUPPLY_PREFIX]; 130 | total_supply.extend_from_slice(denom.as_ref().as_bytes()); 131 | 132 | Ok(total_supply) 133 | } 134 | 135 | /// Creates delegations Cosmos-SDK storage prefix for delegator with **delegator_addr** 136 | /// 137 | pub fn create_delegations_key>( 138 | delegator_address: AddrBytes, 139 | ) -> NeutronResult> { 140 | let mut key: Vec = vec![DELEGATION_KEY]; 141 | key.extend_from_slice(length_prefix(delegator_address)?.as_slice()); 142 | 143 | Ok(key) 144 | } 145 | 146 | /// Creates Cosmos-SDK storage key for delegation between delegator with **delegator_addr** and validator with **validator_addr** 147 | /// 148 | pub fn create_delegation_key>( 149 | delegator_address: AddrBytes, 150 | validator_address: AddrBytes, 151 | ) -> NeutronResult> { 152 | let mut delegations_key: Vec = create_delegations_key(delegator_address)?; 153 | delegations_key.extend_from_slice(length_prefix(validator_address)?.as_slice()); 154 | 155 | Ok(delegations_key) 156 | } 157 | 158 | /// Creates unbonding delegations Cosmos-SDK storage prefix for delegator with **delegator_addr** 159 | /// 160 | pub fn create_unbonding_delegations_key>( 161 | delegator_address: AddrBytes, 162 | ) -> NeutronResult> { 163 | let mut key: Vec = vec![UNBONDING_DELEGATION_KEY]; 164 | key.extend_from_slice(length_prefix(delegator_address)?.as_slice()); 165 | 166 | Ok(key) 167 | } 168 | 169 | /// Creates Cosmos-SDK storage key for unbonding delegation between delegator with **delegator_addr** and validator with **validator_addr** 170 | /// 171 | pub fn create_unbonding_delegation_key>( 172 | delegator_address: AddrBytes, 173 | validator_address: AddrBytes, 174 | ) -> NeutronResult> { 175 | let mut unbonding_delegations_key: Vec = 176 | create_unbonding_delegations_key(delegator_address)?; 177 | unbonding_delegations_key.extend_from_slice(length_prefix(validator_address)?.as_slice()); 178 | 179 | Ok(unbonding_delegations_key) 180 | } 181 | 182 | /// Creates Cosmos-SDK storage key for validator with **operator_address** 183 | /// 184 | pub fn create_validator_key>( 185 | operator_address: AddrBytes, 186 | ) -> NeutronResult> { 187 | let mut key: Vec = vec![VALIDATORS_KEY]; 188 | key.extend_from_slice(length_prefix(operator_address)?.as_slice()); 189 | 190 | Ok(key) 191 | } 192 | 193 | /// Creates Cosmos-SDK storage key for validator with **valcons_addr** 194 | /// 195 | pub fn create_validator_signing_info_key>( 196 | valcons_addr: AddrBytes, 197 | ) -> NeutronResult> { 198 | let mut key: Vec = vec![VALIDATOR_SIGNING_INFO_KEY]; 199 | key.extend_from_slice(length_prefix(valcons_addr)?.as_slice()); 200 | 201 | Ok(key) 202 | } 203 | 204 | /// Creates Wasm key for contract state. 205 | /// This function is similar to 206 | /// , 207 | /// but it also concatenates resulting contract store prefix with contract's storage key, 208 | /// resulting in a complete storage key. 209 | pub fn create_wasm_contract_store_key, Key: AsRef<[u8]>>( 210 | contract_address: AddrBytes, 211 | key: Key, 212 | ) -> NeutronResult> { 213 | let mut prefix: Vec = vec![WASM_CONTRACT_STORE_PREFIX]; 214 | prefix.extend_from_slice(contract_address.as_ref()); 215 | prefix.extend_from_slice(key.as_ref()); 216 | 217 | Ok(prefix) 218 | } 219 | 220 | /// Creates Cosmos-SDK distribution key for fee pool 221 | /// 222 | pub fn create_fee_pool_key() -> NeutronResult> { 223 | let key: Vec = vec![FEE_POOL_KEY]; 224 | 225 | Ok(key) 226 | } 227 | 228 | /// Creates Cosmos-SDK governance key for proposal with specific id 229 | /// 230 | pub fn create_gov_proposal_key(proposal_id: u64) -> NeutronResult> { 231 | let mut key: Vec = vec![PROPOSALS_KEY_PREFIX]; 232 | key.extend_from_slice(proposal_id.to_be_bytes().as_slice()); 233 | 234 | Ok(key) 235 | } 236 | 237 | /// Creates Cosmos-SDK storage keys for list of proposals 238 | pub fn create_gov_proposal_keys(proposals_ids: Vec) -> NeutronResult> { 239 | let mut kv_keys: Vec = Vec::with_capacity(proposals_ids.len()); 240 | 241 | for id in proposals_ids { 242 | let kv_key = KvKey { 243 | path: GOV_STORE_KEY.to_string(), 244 | key: create_gov_proposal_key(id)?, 245 | }; 246 | 247 | kv_keys.push(kv_key) 248 | } 249 | 250 | Ok(kv_keys) 251 | } 252 | 253 | /// Creates Cosmos-SDK governance key for votes for proposal with specific id 254 | /// 255 | pub fn create_gov_proposal_votes_key(proposal_id: u64) -> NeutronResult> { 256 | let mut key: Vec = vec![VOTES_KEY_PREFIX]; 257 | key.extend_from_slice(proposal_id.to_be_bytes().as_slice()); 258 | 259 | Ok(key) 260 | } 261 | 262 | /// Creates Cosmos-SDK storage key for specific voter on specific proposal 263 | /// 264 | pub fn create_gov_proposal_voter_votes_key>( 265 | proposal_id: u64, 266 | voter_address: AddrBytes, 267 | ) -> NeutronResult> { 268 | let mut votes_key: Vec = create_gov_proposal_votes_key(proposal_id)?; 269 | votes_key.extend_from_slice(length_prefix(voter_address)?.as_slice()); 270 | 271 | Ok(votes_key) 272 | } 273 | 274 | /// Creates Cosmos-SDK storage keys for list of voters on list of proposals 275 | pub fn create_gov_proposals_voters_votes_keys( 276 | proposals_ids: Vec, 277 | voters: Vec, 278 | ) -> NeutronResult> { 279 | let mut kv_keys: Vec = Vec::with_capacity(voters.len() * proposals_ids.len()); 280 | 281 | for voter in voters { 282 | let voter_addr = decode_and_convert(&voter)?; 283 | 284 | for proposal_id in proposals_ids.clone() { 285 | let kv_key = KvKey { 286 | path: GOV_STORE_KEY.to_string(), 287 | key: create_gov_proposal_voter_votes_key(proposal_id, &voter_addr)?, 288 | }; 289 | 290 | kv_keys.push(kv_key) 291 | } 292 | } 293 | 294 | Ok(kv_keys) 295 | } 296 | 297 | /// Returns validator max change rate 298 | pub fn get_max_change_rate(commission: &Option) -> Option { 299 | let commission_rates = commission.as_ref().map(|v| v.commission_rates.as_ref())?; 300 | commission_rates 301 | .map(|v| Decimal::new(Uint128::from_str(v.max_change_rate.as_str()).unwrap_or_default())) 302 | } 303 | 304 | /// Returns validator max rate 305 | pub fn get_max_rate(commission: &Option) -> Option { 306 | let commission_rates = commission.as_ref().map(|v| v.commission_rates.as_ref())?; 307 | commission_rates 308 | .map(|v| Decimal::new(Uint128::from_str(v.max_rate.as_str()).unwrap_or_default())) 309 | } 310 | 311 | /// Returns current validator rate 312 | pub fn get_rate(commission: &Option) -> Option { 313 | let commission_rates = commission.as_ref().map(|v| v.commission_rates.as_ref())?; 314 | commission_rates.map(|v| Decimal::new(Uint128::from_str(v.rate.as_str()).unwrap_or_default())) 315 | } 316 | 317 | /// Returns current validator rate 318 | pub fn get_update_time(commission: &Option) -> Option { 319 | let commission_rates = commission.as_ref().map(|v| v.update_time.as_ref())?; 320 | commission_rates.map(|v| v.seconds as u64) 321 | } 322 | 323 | /// Returns denom for total supply from StorageValue key 324 | pub fn get_total_supply_denom(denom: &[u8]) -> Option { 325 | if denom.len() < 2 { 326 | return None; 327 | } 328 | if denom[0] == SUPPLY_PREFIX { 329 | // We need to cut off first byte because it contains storage key following by denom. 330 | return from_utf8(&denom[1..]).ok().map(|d| d.to_string()); 331 | } 332 | 333 | None 334 | } 335 | 336 | /// Returns total supply amount from StorageValue key 337 | pub fn get_total_supply_amount(amount: &Vec) -> Option { 338 | from_utf8(amount.as_slice()) 339 | .ok() 340 | .map(|a| Uint128::from_str(a).ok())? 341 | } 342 | -------------------------------------------------------------------------------- /packages/neutron-sdk/src/interchain_queries/v045/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod helpers; 2 | pub mod queries; 3 | pub mod register_queries; 4 | pub mod types; 5 | 6 | #[allow(deprecated)] 7 | pub use register_queries::{ 8 | new_register_balance_query_msg, new_register_balances_query_msg, 9 | new_register_bank_total_supply_query_msg, new_register_delegator_delegations_query_msg, 10 | new_register_delegator_unbonding_delegations_query_msg, 11 | new_register_distribution_fee_pool_query_msg, new_register_gov_proposals_query_msg, 12 | new_register_staking_validators_query_msg, new_register_transfers_query_msg, 13 | }; 14 | 15 | #[cfg(test)] 16 | mod testing; 17 | -------------------------------------------------------------------------------- /packages/neutron-sdk/src/interchain_queries/v045/queries.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | interchain_queries::{ 3 | queries::{check_query_type, get_registered_query, query_kv_result}, 4 | types::QueryType, 5 | v045::types::{ 6 | Balances, Delegations, FeePool, GovernmentProposal, GovernmentProposalVotes, 7 | SigningInfo, StakingValidator, StdDelegation, TotalSupply, UnbondingDelegations, 8 | }, 9 | }, 10 | NeutronResult, 11 | }; 12 | use cosmwasm_std::{Deps, Env}; 13 | use schemars::JsonSchema; 14 | use serde::{Deserialize, Serialize}; 15 | 16 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 17 | #[serde(rename_all = "snake_case")] 18 | pub struct BalanceResponse { 19 | pub balances: Balances, 20 | pub last_submitted_local_height: u64, 21 | } 22 | 23 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 24 | #[serde(rename_all = "snake_case")] 25 | pub struct TotalSupplyResponse { 26 | pub supply: TotalSupply, 27 | pub last_submitted_local_height: u64, 28 | } 29 | 30 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 31 | #[serde(rename_all = "snake_case")] 32 | pub struct FeePoolResponse { 33 | pub pool: FeePool, 34 | pub last_submitted_local_height: u64, 35 | } 36 | 37 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 38 | #[serde(rename_all = "snake_case")] 39 | pub struct ValidatorResponse { 40 | pub validator: StakingValidator, 41 | pub last_submitted_local_height: u64, 42 | } 43 | 44 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 45 | #[serde(rename_all = "snake_case")] 46 | pub struct ValidatorSigningInfoResponse { 47 | pub signing_infos: SigningInfo, 48 | pub last_submitted_local_height: u64, 49 | } 50 | 51 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 52 | #[serde(rename_all = "snake_case")] 53 | pub struct ProposalResponse { 54 | pub proposals: GovernmentProposal, 55 | pub last_submitted_local_height: u64, 56 | } 57 | 58 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 59 | #[serde(rename_all = "snake_case")] 60 | pub struct ProposalVotesResponse { 61 | pub votes: GovernmentProposalVotes, 62 | pub last_submitted_local_height: u64, 63 | } 64 | 65 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 66 | #[serde(rename_all = "snake_case")] 67 | pub struct DelegatorDelegationsResponse { 68 | pub delegations: Vec, 69 | pub last_submitted_local_height: u64, 70 | } 71 | 72 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 73 | #[serde(rename_all = "snake_case")] 74 | pub struct DelegatorUnbondingDelegationsResponse { 75 | pub unbonding_delegations: UnbondingDelegations, 76 | pub last_submitted_local_height: u64, 77 | } 78 | 79 | /// Returns balance of account on remote chain for particular denom 80 | /// * ***registered_query_id*** is an identifier of the corresponding registered interchain query 81 | pub fn query_balance( 82 | deps: Deps, 83 | _env: Env, 84 | registered_query_id: u64, 85 | ) -> NeutronResult { 86 | let registered_query = get_registered_query(deps, registered_query_id)?; 87 | 88 | check_query_type(registered_query.query_type, QueryType::KV)?; 89 | 90 | let balances: Balances = query_kv_result(deps, registered_query_id)?; 91 | 92 | Ok(BalanceResponse { 93 | last_submitted_local_height: registered_query.last_submitted_result_local_height, 94 | balances, 95 | }) 96 | } 97 | 98 | /// Returns bank total supply on remote chain for particular denom 99 | /// * ***registered_query_id*** is an identifier of the corresponding registered interchain query 100 | pub fn query_bank_total( 101 | deps: Deps, 102 | _env: Env, 103 | registered_query_id: u64, 104 | ) -> NeutronResult { 105 | let registered_query = get_registered_query(deps, registered_query_id)?; 106 | 107 | check_query_type(registered_query.query_type, QueryType::KV)?; 108 | 109 | let total_supply: TotalSupply = query_kv_result(deps, registered_query_id)?; 110 | 111 | Ok(TotalSupplyResponse { 112 | last_submitted_local_height: registered_query.last_submitted_result_local_height, 113 | supply: total_supply, 114 | }) 115 | } 116 | 117 | /// Returns distribution fee pool on remote chain 118 | /// * ***registered_query_id*** is an identifier of the corresponding registered interchain query 119 | pub fn query_distribution_fee_pool( 120 | deps: Deps, 121 | _env: Env, 122 | registered_query_id: u64, 123 | ) -> NeutronResult { 124 | let registered_query = get_registered_query(deps, registered_query_id)?; 125 | 126 | check_query_type(registered_query.query_type, QueryType::KV)?; 127 | 128 | let fee_pool: FeePool = query_kv_result(deps, registered_query_id)?; 129 | 130 | Ok(FeePoolResponse { 131 | last_submitted_local_height: registered_query.last_submitted_result_local_height, 132 | pool: fee_pool, 133 | }) 134 | } 135 | 136 | /// Returns staking validator from remote chain 137 | /// * ***registered_query_id*** is an identifier of the corresponding registered interchain query 138 | pub fn query_staking_validators( 139 | deps: Deps, 140 | _env: Env, 141 | registered_query_id: u64, 142 | ) -> NeutronResult { 143 | let registered_query = get_registered_query(deps, registered_query_id)?; 144 | 145 | check_query_type(registered_query.query_type, QueryType::KV)?; 146 | 147 | let validator: StakingValidator = query_kv_result(deps, registered_query_id)?; 148 | 149 | Ok(ValidatorResponse { 150 | last_submitted_local_height: registered_query.last_submitted_result_local_height, 151 | validator, 152 | }) 153 | } 154 | 155 | /// Returns validators signing infos from remote chain 156 | /// * ***registered_query_id*** is an identifier of the corresponding registered interchain query 157 | pub fn query_validators_signing_infos( 158 | deps: Deps, 159 | _env: Env, 160 | registered_query_id: u64, 161 | ) -> NeutronResult { 162 | let registered_query = get_registered_query(deps, registered_query_id)?; 163 | 164 | check_query_type(registered_query.query_type, QueryType::KV)?; 165 | 166 | let signing_infos: SigningInfo = query_kv_result(deps, registered_query_id)?; 167 | 168 | Ok(ValidatorSigningInfoResponse { 169 | last_submitted_local_height: registered_query.last_submitted_result_local_height, 170 | signing_infos, 171 | }) 172 | } 173 | 174 | /// Returns list of government proposals on the remote chain 175 | /// * ***registered_query_id*** is an identifier of the corresponding registered interchain query 176 | pub fn query_government_proposals( 177 | deps: Deps, 178 | _env: Env, 179 | registered_query_id: u64, 180 | ) -> NeutronResult { 181 | let registered_query = get_registered_query(deps, registered_query_id)?; 182 | 183 | check_query_type(registered_query.query_type, QueryType::KV)?; 184 | 185 | let proposals: GovernmentProposal = query_kv_result(deps, registered_query_id)?; 186 | 187 | Ok(ProposalResponse { 188 | last_submitted_local_height: registered_query.last_submitted_result_local_height, 189 | proposals, 190 | }) 191 | } 192 | 193 | /// Returns list of government proposal votes on the remote chain 194 | /// * ***registered_query_id*** is an identifier of the corresponding registered interchain query 195 | pub fn query_government_proposal_votes( 196 | deps: Deps, 197 | _env: Env, 198 | registered_query_id: u64, 199 | ) -> NeutronResult { 200 | let registered_query = get_registered_query(deps, registered_query_id)?; 201 | 202 | check_query_type(registered_query.query_type, QueryType::KV)?; 203 | 204 | let votes: GovernmentProposalVotes = query_kv_result(deps, registered_query_id)?; 205 | 206 | Ok(ProposalVotesResponse { 207 | last_submitted_local_height: registered_query.last_submitted_result_local_height, 208 | votes, 209 | }) 210 | } 211 | 212 | /// Returns delegations of particular delegator on remote chain 213 | /// * ***registered_query_id*** is an identifier of the corresponding registered interchain query 214 | pub fn query_delegations( 215 | deps: Deps, 216 | _env: Env, 217 | registered_query_id: u64, 218 | ) -> NeutronResult { 219 | let registered_query = get_registered_query(deps, registered_query_id)?; 220 | 221 | check_query_type(registered_query.query_type, QueryType::KV)?; 222 | 223 | let delegations: Delegations = query_kv_result(deps, registered_query_id)?; 224 | 225 | Ok(DelegatorDelegationsResponse { 226 | delegations: delegations.delegations, 227 | last_submitted_local_height: registered_query.last_submitted_result_local_height, 228 | }) 229 | } 230 | 231 | /// Returns list of unbonding delegations of particular delegator on remote chain 232 | /// * ***registered_query_id*** is an identifier of the corresponding registered interchain query 233 | pub fn query_unbonding_delegations( 234 | deps: Deps, 235 | _env: Env, 236 | registered_query_id: u64, 237 | ) -> NeutronResult { 238 | let registered_query = get_registered_query(deps, registered_query_id)?; 239 | 240 | check_query_type(registered_query.query_type, QueryType::KV)?; 241 | 242 | let unbonding_delegations: UnbondingDelegations = query_kv_result(deps, registered_query_id)?; 243 | 244 | Ok(DelegatorUnbondingDelegationsResponse { 245 | unbonding_delegations, 246 | last_submitted_local_height: registered_query.last_submitted_result_local_height, 247 | }) 248 | } 249 | -------------------------------------------------------------------------------- /packages/neutron-sdk/src/interchain_queries/v047/mod.rs: -------------------------------------------------------------------------------- 1 | // import all unchanged helpers and methods from v045 package 2 | // to make it available from v047 package (kinda proxy) since they work with Cosmos SDK 0.47 as usual 3 | pub use crate::interchain_queries::v045::helpers; 4 | 5 | pub mod queries; 6 | pub mod types; 7 | 8 | pub mod register_queries; 9 | #[cfg(test)] 10 | mod testing; 11 | -------------------------------------------------------------------------------- /packages/neutron-sdk/src/interchain_queries/v047/queries.rs: -------------------------------------------------------------------------------- 1 | // import all queries from v045 package 2 | // to make it available from v047 package (kinda proxy) since they work with Cosmos SDK 0.47 as usual 3 | pub use crate::interchain_queries::v045::queries::*; 4 | 5 | // But at the same time we redefine some methods from v045 with methods below to create methods 6 | // compatible with Cosmos SDK 0.47 7 | 8 | use crate::interchain_queries::v047::types::Delegations; 9 | use crate::{ 10 | interchain_queries::{ 11 | queries::{check_query_type, get_registered_query, query_kv_result}, 12 | types::QueryType, 13 | v047::types::{Balances, StdDelegation}, 14 | }, 15 | NeutronResult, 16 | }; 17 | use cosmwasm_std::{Deps, Env}; 18 | use schemars::JsonSchema; 19 | use serde::{Deserialize, Serialize}; 20 | 21 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 22 | #[serde(rename_all = "snake_case")] 23 | pub struct BalanceResponse { 24 | pub balances: Balances, 25 | pub last_submitted_local_height: u64, 26 | } 27 | 28 | /// Returns balance of account on remote chain for particular denom 29 | /// * ***registered_query_id*** is an identifier of the corresponding registered interchain query 30 | pub fn query_balance( 31 | deps: Deps, 32 | _env: Env, 33 | registered_query_id: u64, 34 | ) -> NeutronResult { 35 | let registered_query = get_registered_query(deps, registered_query_id)?; 36 | 37 | check_query_type(registered_query.query_type, QueryType::KV)?; 38 | 39 | let balances: Balances = query_kv_result(deps, registered_query_id)?; 40 | 41 | Ok(BalanceResponse { 42 | last_submitted_local_height: registered_query.last_submitted_result_local_height, 43 | balances, 44 | }) 45 | } 46 | 47 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 48 | #[serde(rename_all = "snake_case")] 49 | pub struct DelegatorDelegationsResponse { 50 | pub delegations: Vec, 51 | pub last_submitted_local_height: u64, 52 | } 53 | 54 | /// Returns delegations of particular delegator on remote chain 55 | /// * ***registered_query_id*** is an identifier of the corresponding registered interchain query 56 | pub fn query_delegations( 57 | deps: Deps, 58 | _env: Env, 59 | registered_query_id: u64, 60 | ) -> NeutronResult { 61 | let registered_query = get_registered_query(deps, registered_query_id)?; 62 | 63 | check_query_type(registered_query.query_type, QueryType::KV)?; 64 | 65 | let delegations: Delegations = query_kv_result(deps, registered_query_id)?; 66 | 67 | Ok(DelegatorDelegationsResponse { 68 | delegations: delegations.delegations, 69 | last_submitted_local_height: registered_query.last_submitted_result_local_height, 70 | }) 71 | } 72 | -------------------------------------------------------------------------------- /packages/neutron-sdk/src/interchain_queries/v047/register_queries.rs: -------------------------------------------------------------------------------- 1 | // import all helpers from v045 package 2 | // to make it available from v047 package (kinda proxy) since they work with Cosmos SDK 0.47 as usual 3 | pub use crate::interchain_queries::v045::register_queries::*; 4 | 5 | use crate::interchain_queries::helpers::decode_and_convert; 6 | use crate::interchain_queries::types::QueryType; 7 | use crate::interchain_queries::v045::helpers::{create_delegation_key, create_validator_key}; 8 | use crate::interchain_queries::v045::types::STAKING_STORE_KEY; 9 | use crate::interchain_queries::v047::types::STAKING_PARAMS_KEY; 10 | use crate::NeutronResult; 11 | use cosmwasm_std::{Addr, CosmosMsg}; 12 | use neutron_std::types::neutron::interchainqueries::{KvKey, MsgRegisterInterchainQuery}; 13 | 14 | /// Creates a message to register an Interchain Query to get delegations of particular delegator on remote chain. 15 | /// 16 | /// * **connection_id** is an IBC connection identifier between Neutron and remote chain; 17 | /// * **delegator** is an address of an account on remote chain for which you want to get list of delegations; 18 | /// * **validators** is a list of validators addresses for which you want to get delegations from particular **delegator**; 19 | /// * **update_period** is used to say how often the query must be updated. 20 | pub fn new_register_delegator_delegations_query_msg( 21 | contract: Addr, 22 | connection_id: String, 23 | delegator: String, 24 | validators: Vec, 25 | update_period: u64, 26 | ) -> NeutronResult { 27 | let delegator_addr = decode_and_convert(&delegator)?; 28 | 29 | // Allocate memory for such KV keys as: 30 | // * staking module params to get staking denomination 31 | // * validators structures to calculate amount of delegated tokens 32 | // * delegations structures to get info about delegations itself 33 | let mut keys: Vec = Vec::with_capacity(validators.len() * 2 + 1); 34 | 35 | // create KV key to get Staking Params from staking module 36 | keys.push(KvKey { 37 | path: STAKING_STORE_KEY.to_string(), 38 | key: vec![STAKING_PARAMS_KEY], 39 | }); 40 | 41 | for v in validators { 42 | let val_addr = decode_and_convert(&v)?; 43 | 44 | // create delegation key to get delegation structure 45 | keys.push(KvKey { 46 | path: STAKING_STORE_KEY.to_string(), 47 | key: create_delegation_key(&delegator_addr, &val_addr)?, 48 | }); 49 | 50 | // create validator key to get validator structure 51 | keys.push(KvKey { 52 | path: STAKING_STORE_KEY.to_string(), 53 | key: create_validator_key(&val_addr)?, 54 | }) 55 | } 56 | 57 | Ok(MsgRegisterInterchainQuery { 58 | query_type: QueryType::KV.into(), 59 | keys, 60 | transactions_filter: "".to_string(), 61 | connection_id, 62 | update_period, 63 | sender: contract.to_string(), 64 | } 65 | .into()) 66 | } 67 | -------------------------------------------------------------------------------- /packages/neutron-sdk/src/interchain_queries/v047/types.rs: -------------------------------------------------------------------------------- 1 | use std::ops::Div; 2 | // import all types from v045 package 3 | // to make it available from v047 package (kinda proxy) since they work with Cosmos SDK 0.47 as usual 4 | pub use crate::interchain_queries::v045::types::*; 5 | 6 | // But at the same time we replace some structs from v045 with structs below to create structures 7 | // compatible with Cosmos SDK 0.47 8 | 9 | use crate::interchain_queries::types::KVReconstruct; 10 | use crate::{errors::error::NeutronResult, NeutronError}; 11 | 12 | use crate::interchain_queries::helpers::uint256_to_u128; 13 | use crate::interchain_queries::v047::helpers::deconstruct_account_denom_balance_key; 14 | use cosmos_sdk_proto::cosmos::staking::v1beta1::{ 15 | Delegation, Params, Validator as CosmosValidator, 16 | }; 17 | use cosmos_sdk_proto::traits::Message; 18 | use cosmwasm_std::{Addr, Coin, Decimal256, Uint128, Uint256}; 19 | use neutron_std::types::neutron::interchainqueries::StorageValue; 20 | use schemars::JsonSchema; 21 | use serde::{Deserialize, Serialize}; 22 | use std::str::FromStr; 23 | 24 | /// Key for Staking Params in the **staking** module's storage 25 | /// 26 | pub const STAKING_PARAMS_KEY: u8 = 0x51; 27 | 28 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 29 | /// A structure that can be reconstructed from **StorageValues**'s for the **Balance Interchain Query**. 30 | /// Contains amounts of coins that are held by some account on remote chain. 31 | pub struct Balances { 32 | pub coins: Vec, 33 | } 34 | 35 | impl KVReconstruct for Balances { 36 | fn reconstruct(storage_values: &[StorageValue]) -> NeutronResult { 37 | let mut coins: Vec = Vec::with_capacity(storage_values.len()); 38 | 39 | for kv in storage_values { 40 | let (_, denom) = deconstruct_account_denom_balance_key(kv.key.to_vec())?; 41 | let amount = if kv.value.is_empty() { 42 | Uint128::zero() 43 | } else { 44 | Uint128::from_str(&String::from_utf8(kv.value.to_vec())?)? 45 | }; 46 | 47 | coins.push(Coin::new(amount.u128(), denom)) 48 | } 49 | 50 | Ok(Balances { coins }) 51 | } 52 | } 53 | 54 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 55 | /// A structure that can be reconstructed from **StorageValues**'s for the **Delegator Delegation Interchain Query**. 56 | /// Contains delegations which some delegator has on remote chain. 57 | pub struct Delegations { 58 | pub delegations: Vec, 59 | } 60 | 61 | impl KVReconstruct for Delegations { 62 | fn reconstruct(storage_values: &[StorageValue]) -> NeutronResult { 63 | // We are taking 2 items chunks from starage_value to calculate one delegation 64 | let mut delegations: Vec = Vec::with_capacity(storage_values.len() / 2); 65 | 66 | if storage_values.is_empty() { 67 | return Err(NeutronError::InvalidQueryResultFormat( 68 | "storage_values length is 0".into(), 69 | )); 70 | } 71 | // first StorageValue is staking params 72 | if storage_values[0].value.is_empty() { 73 | // Incoming params cannot be empty, it should always be configured on chain. 74 | // If we receive empty params, that means incoming data structure is corrupted 75 | // and we cannot build `cosmwasm_std::Delegation`'s using this data. 76 | return Err(NeutronError::InvalidQueryResultFormat( 77 | "params is empty".into(), 78 | )); 79 | } 80 | let params: Params = Params::decode(storage_values[0].value.as_slice())?; 81 | 82 | // the rest are delegations and validators alternately 83 | for chunk in storage_values[1..].chunks(2) { 84 | if chunk[0].value.is_empty() { 85 | // Incoming delegation can actually be empty, this just means that delegation 86 | // is not present on remote chain, which is to be expected. So, if it doesn't 87 | // exist, we can safely skip this and following chunk. 88 | continue; 89 | } 90 | let delegation_sdk: Delegation = Delegation::decode(chunk[0].value.as_slice())?; 91 | 92 | let mut delegation_std = StdDelegation { 93 | delegator: Addr::unchecked(delegation_sdk.delegator_address.as_str()), 94 | validator: delegation_sdk.validator_address, 95 | amount: Default::default(), 96 | }; 97 | 98 | if chunk[1].value.is_empty() { 99 | // At this point, incoming validator cannot be empty, that would be invalid, 100 | // because delegation is already defined, so, building `cosmwasm_std::Delegation` 101 | // from this data is impossible, incoming data is corrupted.post 102 | return Err(NeutronError::InvalidQueryResultFormat( 103 | "validator is empty".into(), 104 | )); 105 | } 106 | let validator: CosmosValidator = CosmosValidator::decode(chunk[1].value.as_slice())?; 107 | 108 | let delegation_shares = Decimal256::from_atomics( 109 | Uint256::from_str(&delegation_sdk.shares)?, 110 | DECIMAL_PLACES, 111 | )?; 112 | 113 | let delegator_shares = Decimal256::from_atomics( 114 | Uint256::from_str(&validator.delegator_shares)?, 115 | DECIMAL_PLACES, 116 | )?; 117 | 118 | let validator_tokens = 119 | Decimal256::from_atomics(Uint128::from_str(&validator.tokens)?, 0)?; 120 | 121 | // https://github.com/cosmos/cosmos-sdk/blob/35ae2c4c72d4aeb33447d5a7af23ca47f786606e/x/staking/keeper/querier.go#L463 122 | // delegated_tokens = quotient(delegation.shares * validator.tokens / validator.total_shares); 123 | let delegated_tokens = delegation_shares 124 | .checked_mul(validator_tokens)? 125 | .div(delegator_shares) 126 | .atomics() 127 | .div(Uint256::from_u128(DECIMAL_FRACTIONAL)); 128 | 129 | delegation_std.amount = 130 | Coin::new(uint256_to_u128(delegated_tokens)?, ¶ms.bond_denom); 131 | 132 | delegations.push(delegation_std); 133 | } 134 | 135 | Ok(Delegations { delegations }) 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /packages/neutron-sdk/src/interchain_txs/helpers.rs: -------------------------------------------------------------------------------- 1 | use cosmos_sdk_proto::traits::Message; 2 | use cosmwasm_std::{Addr, CosmosMsg, Deps, StdError, StdResult}; 3 | use neutron_std::shim::Any; 4 | use neutron_std::types::cosmos::base::v1beta1::Coin; 5 | use neutron_std::types::ibc::core::channel::v1::Order; 6 | use neutron_std::types::neutron::feerefunder::{Fee, FeerefunderQuerier}; 7 | use neutron_std::types::neutron::interchaintxs::v1::{MsgRegisterInterchainAccount, MsgSubmitTx}; 8 | 9 | /// Decodes protobuf any item into T structure 10 | pub fn decode_message_response(item: &Vec) -> StdResult { 11 | let res = T::decode(item.as_slice()); 12 | match res { 13 | Err(e) => Err(StdError::generic_err(format!("Can't decode item: {}", e))), 14 | Ok(data) => Ok(data), 15 | } 16 | } 17 | 18 | const CONTROLLER_PORT_PREFIX: &str = "icacontroller-"; 19 | const ICA_OWNER_DELIMITER: &str = "."; 20 | 21 | /// Constructs a full ICA controller port identifier for a contract with **contract_address** and **interchain_account_id** 22 | /// 23 | pub fn get_port_id>(contract_address: R, interchain_account_id: R) -> String { 24 | CONTROLLER_PORT_PREFIX.to_string() 25 | + contract_address.as_ref() 26 | + ICA_OWNER_DELIMITER 27 | + interchain_account_id.as_ref() 28 | } 29 | 30 | /// Basic helper to define a register interchain account message. 31 | /// 32 | /// * **contract** is a contract that registers ICA. Must be the contract address that sends this message. 33 | /// * **connection_id** is an IBC connection identifier between Neutron and remote chain; 34 | /// * **interchain_account_id** is an identifier of your new interchain account. Can be any string. 35 | /// * **ordering** is an ordering of ICA channel. Set to ORDERED if not specified 36 | pub fn register_interchain_account( 37 | contract: Addr, 38 | connection_id: String, 39 | interchain_account_id: String, 40 | register_fee: Vec, 41 | ordering: Option, 42 | ) -> CosmosMsg { 43 | MsgRegisterInterchainAccount { 44 | from_address: contract.to_string(), 45 | connection_id, 46 | interchain_account_id, 47 | register_fee, 48 | ordering: ordering.unwrap_or(Order::Ordered).into(), 49 | } 50 | .into() 51 | } 52 | 53 | /// Basic helper to define a submit tx message. 54 | /// 55 | /// * **contract** is a contract that is sending the message 56 | /// * **connection_id** is an IBC connection identifier between Neutron and remote chain; 57 | /// * **interchain_account_id** is an identifier of your interchain account from which you want to execute msgs; 58 | /// * **msgs** is a list of protobuf encoded Cosmos-SDK messages you want to execute on remote chain; 59 | /// * **memo** is a memo you want to attach to your interchain transaction. It behaves like a memo in usual Cosmos transaction; 60 | /// * **timeout** is a timeout in seconds after which the packet times out. 61 | /// * **fee** is a fee that is used for different kinds of callbacks. Unused fee types will be returned to msg sender. 62 | pub fn submit_tx( 63 | contract: Addr, 64 | connection_id: String, 65 | interchain_account_id: String, 66 | msgs: Vec, 67 | memo: String, 68 | timeout: u64, 69 | fee: Fee, 70 | ) -> CosmosMsg { 71 | MsgSubmitTx { 72 | from_address: contract.to_string(), 73 | connection_id, 74 | interchain_account_id, 75 | msgs, 76 | memo, 77 | timeout, 78 | fee: Some(fee), 79 | } 80 | .into() 81 | } 82 | 83 | /// Queries chain for minimum fee for given denom. Returns Err if not found. 84 | /// 85 | /// * **deps** is contract `Deps` 86 | /// * **denom** is a denom which can be used. Function will return Err if denom is not in a list of fee denoms. 87 | pub fn query_denom_min_ibc_fee(deps: Deps, denom: &str) -> StdResult { 88 | let fee = query_min_fee(deps)?; 89 | Ok(Fee { 90 | recv_fee: fee_with_denom(fee.recv_fee, denom)?, 91 | ack_fee: fee_with_denom(fee.ack_fee, denom)?, 92 | timeout_fee: fee_with_denom(fee.timeout_fee, denom)?, 93 | }) 94 | } 95 | 96 | /// Queries chain for all possible minimal fee. Each fee in Vec is a different denom. 97 | /// 98 | /// * **deps** is contract `Deps` 99 | pub fn query_min_fee(deps: Deps) -> StdResult { 100 | let querier = FeerefunderQuerier::new(&deps.querier); 101 | let params = querier.params()?; 102 | let params_inner = params 103 | .params 104 | .ok_or_else(|| StdError::generic_err("no params found for feerefunder"))?; 105 | let min_fee = params_inner 106 | .min_fee 107 | .ok_or_else(|| StdError::generic_err("no minimum fee param for feerefunder"))?; 108 | 109 | Ok(min_fee) 110 | } 111 | 112 | fn fee_with_denom(fee: Vec, denom: &str) -> StdResult> { 113 | Ok(vec![fee 114 | .iter() 115 | .find(|a| a.denom == denom) 116 | .map(|r| Coin { 117 | denom: r.denom.to_string(), 118 | amount: r.amount.clone(), 119 | }) 120 | .ok_or_else(|| { 121 | StdError::not_found(format!("cannot find fee for denom {}", denom)) 122 | })?]) 123 | } 124 | -------------------------------------------------------------------------------- /packages/neutron-sdk/src/interchain_txs/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod helpers; 2 | 3 | pub mod v045; 4 | pub mod v047; 5 | -------------------------------------------------------------------------------- /packages/neutron-sdk/src/interchain_txs/v045/helpers.rs: -------------------------------------------------------------------------------- 1 | use cosmos_sdk_proto::{ 2 | cosmos::base::abci::v1beta1::{MsgData, TxMsgData}, 3 | traits::Message, 4 | }; 5 | use cosmwasm_std::{Binary, StdError, StdResult}; 6 | 7 | /// Decodes acknowledgement into `Vec` structure 8 | pub fn decode_acknowledgement_response(data: Binary) -> StdResult> { 9 | let msg_data: Result = TxMsgData::decode(data.as_slice()); 10 | match msg_data { 11 | Err(e) => Err(StdError::generic_err(format!( 12 | "Can't decode response: {}", 13 | e 14 | ))), 15 | #[allow(deprecated)] 16 | Ok(msg) => Ok(msg.data), 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /packages/neutron-sdk/src/interchain_txs/v045/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod helpers; 2 | -------------------------------------------------------------------------------- /packages/neutron-sdk/src/interchain_txs/v047/helpers.rs: -------------------------------------------------------------------------------- 1 | use cosmos_sdk_proto::{cosmos::base::abci::v1beta1::TxMsgData, traits::Message}; 2 | use cosmwasm_std::{Binary, StdError, StdResult}; 3 | use prost_types::Any; 4 | 5 | /// Decodes acknowledgement into `Vec` structure 6 | pub fn decode_acknowledgement_response(data: Binary) -> StdResult> { 7 | let msg_data: Result = TxMsgData::decode(data.as_slice()); 8 | match msg_data { 9 | Err(e) => Err(StdError::generic_err(format!( 10 | "Can't decode response: {}", 11 | e 12 | ))), 13 | Ok(msg) => Ok(msg.msg_responses), 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /packages/neutron-sdk/src/interchain_txs/v047/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod helpers; 2 | -------------------------------------------------------------------------------- /packages/neutron-sdk/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![doc = include_str!("../README.md")] 2 | #![cfg_attr(docsrs, feature(doc_cfg))] 3 | // #![forbid(unsafe_code)] 4 | #![warn(trivial_casts, trivial_numeric_casts, unused_import_braces)] 5 | 6 | pub mod bindings; 7 | mod errors; 8 | pub mod interchain_queries; 9 | pub mod interchain_txs; 10 | pub mod sudo; 11 | 12 | pub use errors::error::{NeutronError, NeutronResult}; 13 | 14 | // This is a signal, such that any contract that imports these helpers will only run on the 15 | // neutron blockchain 16 | #[no_mangle] 17 | extern "C" fn requires_neutron() {} 18 | -------------------------------------------------------------------------------- /packages/neutron-sdk/src/sudo/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod msg; 2 | -------------------------------------------------------------------------------- /packages/neutron-sdk/src/sudo/msg.rs: -------------------------------------------------------------------------------- 1 | use cosmwasm_std::Binary; 2 | use schemars::JsonSchema; 3 | use serde::{Deserialize, Serialize}; 4 | 5 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 6 | pub struct RequestPacket { 7 | pub sequence: Option, 8 | pub source_port: Option, 9 | pub source_channel: Option, 10 | pub destination_port: Option, 11 | pub destination_channel: Option, 12 | pub data: Option, 13 | pub timeout_height: Option, 14 | pub timeout_timestamp: Option, 15 | } 16 | 17 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 18 | pub struct RequestPacketTimeoutHeight { 19 | pub revision_number: Option, 20 | pub revision_height: Option, 21 | } 22 | 23 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 24 | #[serde(rename_all = "snake_case")] 25 | pub enum SudoMsg { 26 | Response { 27 | request: RequestPacket, 28 | data: Binary, 29 | }, 30 | Error { 31 | request: RequestPacket, 32 | details: String, 33 | }, 34 | Timeout { 35 | request: RequestPacket, 36 | }, 37 | OpenAck { 38 | port_id: String, 39 | channel_id: String, 40 | counterparty_channel_id: String, 41 | counterparty_version: String, 42 | }, 43 | TxQueryResult { 44 | query_id: u64, 45 | height: Height, 46 | data: Binary, 47 | }, 48 | #[serde(rename = "kv_query_result")] 49 | KVQueryResult { 50 | query_id: u64, 51 | }, 52 | } 53 | 54 | /// TransferSudoMsg is a sudo response payload for a native ibc transfer 55 | /// SudoMsg for ibc transfer has fewer methods than SudoMsg for ica txs 56 | /// so we describe standalone type to not confuse users with useless variants 57 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 58 | #[serde(rename_all = "snake_case")] 59 | pub enum TransferSudoMsg { 60 | Response { 61 | request: RequestPacket, 62 | data: Binary, 63 | }, 64 | Error { 65 | request: RequestPacket, 66 | details: String, 67 | }, 68 | Timeout { 69 | request: RequestPacket, 70 | }, 71 | } 72 | 73 | /// Height is used for sudo call for `TxQueryResult` enum variant type 74 | #[derive(Default, Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] 75 | #[serde(rename_all = "snake_case")] 76 | pub struct Height { 77 | /// the revision that the client is currently on 78 | #[serde(default)] 79 | pub revision_number: u64, 80 | /// **height** is a height of remote chain 81 | #[serde(default)] 82 | pub revision_height: u64, 83 | } 84 | -------------------------------------------------------------------------------- /rust-toolchain.toml: -------------------------------------------------------------------------------- 1 | [toolchain] 2 | channel = "1.78.0" 3 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | # stable 2 | newline_style = "unix" 3 | hard_tabs = false 4 | tab_spaces = 4 5 | 6 | # unstable... should we require `rustup run nightly cargo fmt` ? 7 | # or just update the style guide when they are stable? 8 | #fn_single_line = true 9 | #format_code_in_doc_comments = true 10 | #overflow_delimited_expr = true 11 | #reorder_impl_items = true 12 | #struct_field_align_threshold = 20 13 | #struct_lit_single_line = true 14 | #report_todo = "Always" 15 | -------------------------------------------------------------------------------- /scripts/test_ibc_transfer.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # http://redsymbol.net/articles/unofficial-bash-strict-mode/ 4 | set -euo pipefail 5 | IFS=$'\n\t' 6 | 7 | CONTRACT_PATH="../artifacts/ibc_transfer.wasm" 8 | CHAIN_ID="test-1" 9 | NEUTRON_DIR="${NEUTRON_DIR:-../../neutron}" 10 | HOME="$NEUTRON_DIR/data/test-1/" 11 | KEY="demowallet1" 12 | ADMIN="neutron1m9l358xunhhwds0568za49mzhvuxx9ux8xafx2" 13 | NODE="tcp://127.0.0.1:26657" 14 | GAIA_NODE="tcp://127.0.0.1:16657" 15 | 16 | wait_tx() { 17 | local txhash 18 | local attempts 19 | txhash="$(jq -r '.txhash' /dev/null; do 22 | ((attempts-=1)) || { 23 | echo "tx $txhash still not included in block" 1>&2 24 | exit 1 25 | } 26 | sleep 0.1 27 | done 28 | } 29 | 30 | code_id="$(neutrond tx wasm store "$CONTRACT_PATH" \ 31 | --from "$KEY" -y --chain-id "$CHAIN_ID" \ 32 | --gas 50000000 --gas-prices 0.0025untrn \ 33 | --broadcast-mode=sync --keyring-backend=test \ 34 | --output json --home "$HOME" --node "$NODE" \ 35 | | wait_tx | jq -r '.logs[0].events[] | select(.type == "store_code").attributes[] | select(.key == "code_id").value')" 36 | echo "Code ID: $code_id" 37 | 38 | contract_address="$(neutrond tx wasm instantiate "$code_id" '{}' \ 39 | --from ${KEY} --admin ${ADMIN} -y --chain-id "$CHAIN_ID" \ 40 | --output json --broadcast-mode=sync --label "init" \ 41 | --keyring-backend=test --gas-prices 0.0025untrn \ 42 | --home "$HOME" --node "$NODE" \ 43 | | wait_tx | jq -r '.logs[0].events[] | select(.type == "instantiate").attributes[] | select(.key == "_contract_address").value')" 44 | echo "Contract address: $contract_address" 45 | 46 | tx_result="$(neutrond tx bank send demowallet1 "$contract_address" 20000untrn \ 47 | -y --chain-id "$CHAIN_ID" --home "$HOME" --node "$NODE" \ 48 | --keyring-backend=test --gas-prices 0.0025untrn --output json \ 49 | --broadcast-mode=sync | wait_tx)" 50 | code="$(echo "$tx_result" | jq '.code')" 51 | if [[ "$code" -ne 0 ]]; then 52 | echo "Failed to send money to contract: $(echo "$tx_result" | jq '.raw_log')" && exit 1 53 | fi 54 | echo "Sent money to contract to pay fees" 55 | 56 | msg='{"send":{ 57 | "to": "cosmos17dtl0mjt3t77kpuhg2edqzjpszulwhgzuj9ljs", 58 | "amount": "1000", 59 | "denom": "untrn", 60 | "channel": "channel-0" 61 | }}' 62 | tx_result="$(neutrond tx wasm execute "$contract_address" "$msg" \ 63 | --from ${KEY} -y --chain-id ${CHAIN_ID} --output json \ 64 | --broadcast-mode=sync --gas-prices 0.0025untrn --gas 1000000 \ 65 | --keyring-backend test --home "$HOME" --node "$NODE" | wait_tx)" 66 | code="$(echo "$tx_result" | jq '.code')" 67 | if [[ "$code" -ne 0 ]]; then 68 | echo "Failed to execute contract: $(echo "$tx_result" | jq '.raw_log')" && exit 1 69 | fi 70 | 71 | echo "Waiting 20 seconds for IBC transfer to complete…" 72 | # shellcheck disable=SC2034 73 | for i in $(seq 20); do 74 | sleep 1 75 | echo -n . 76 | done 77 | echo " done" 78 | 79 | echo 80 | echo "cosmos17dtl0mjt3t77kpuhg2edqzjpszulwhgzuj9ljs should have 3000untrn now:" 81 | gaiad query bank balances "cosmos17dtl0mjt3t77kpuhg2edqzjpszulwhgzuj9ljs" \ 82 | --node "$GAIA_NODE" --output json | jq '.balances' 83 | 84 | echo 85 | echo "If you see more than 3000untrn, you have already run this test several times before" 86 | -------------------------------------------------------------------------------- /scripts/test_icq_wasm_juno_testnet/.gitignore: -------------------------------------------------------------------------------- 1 | storage/ 2 | -------------------------------------------------------------------------------- /scripts/test_icq_wasm_juno_testnet/README.md: -------------------------------------------------------------------------------- 1 | # Test ICQ wasm contract state using Juno testnet 2 | 3 | This test serves as a tutorial on how to query remote cw20 balance. 4 | This tutorial could be used as a general guide on how to query any 5 | remote cw20 state. Sadly, storage keys are always contract dependent, 6 | and cw20 balance is not an exception. This tutorial crafts storage keys for 7 | [cw20-base](https://github.com/CosmWasm/cw-plus/tree/main/contracts/cw20-base) 8 | contract. In general, it is always better to deploy your own contract with 9 | a stable well-defined state known by you, so you can easily figure out 10 | the storage keys, and they will never change this way. The contract you 11 | could deploy manually is expected to perform wasm query and save query 12 | result into its state. 13 | 14 | This test uses 15 | [neutron_interchain_queries](https://github.com/neutron-org/neutron-sdk/tree/main/contracts/neutron_interchain_queries) 16 | contract, sending `ExecuteMsg::RegisterCw20BalanceQuery` and querying 17 | `QueryMsg::Cw20Balance`. You can study this contract's code to learn 18 | more on how to craft storage keys. 19 | 20 | ## 1. Install dependencies 21 | 22 | Read [instructions](https://docs.neutron.org/neutron/build-and-run/localnet) 23 | and install: 24 | - neutron 25 | - hermes 26 | - neutron query relayer 27 | 28 | ## 2. Launch neutron 29 | 30 | Go to `neutron/` directory and run `make start`. 31 | This will deploy Neutron localnet. 32 | Please wait 20 to 30 seconds for chain to initialize before 33 | proceeding to step 3. 34 | 35 | ## 3. Connect to Juno testnet 36 | 37 | Open `neutron-sdk/scripts/test_icq_wasm_juno_testnet/create_juno_connection.sh` in your text editor of choice. 38 | Navigate to `JUNO_MNEMONIC=""` and insert there your own testnet mnemonic. 39 | Please make sure to have at least 0.01 JUNOX on uni-6 testnet, these funds 40 | are needed to create a connection. 41 | 42 | Change current directory to `neutron-sdk/scripts/test_icq_wasm_juno_testnet/` 43 | and run `./create_juno_connection.sh`. After it finishes, `connection-0` should 44 | appear on Neutron localnet. You can use this snippet to query a list of 45 | connections on Neutron's localnet: 46 | 47 | ```bash 48 | neutrond query ibc connection connections --node tcp://0.0.0.0:26657 --output json | jq '.connections[] | {id, client_id, state, counterparty}' 49 | ``` 50 | 51 | If this is the first time you are running this script, you should only 52 | see `connection-0`. Don't worry if you see `connection-1`, `connection-2` 53 | and so on, simply use the last one you have created. 54 | 55 | ## 4. Deploy ICQ relayer 56 | 57 | Open `neutron-sdk/scripts/test_icq_wasm_juno_testnet/icq.env` in your text editor of choice. 58 | Navigate to `RELAYER_NEUTRON_CHAIN_CONNECTION_ID=` and insert there 59 | connection ID you have just created. 60 | 61 | ```bash 62 | cd neutron-sdk/scripts/test_icq_wasm_juno_testnet/ 63 | rm -rf storage/; export $(xargs < icq.env) && neutron_query_relayer start 64 | ``` 65 | 66 | ## 5. Prepare to run test 67 | 68 | First, navigate to root directory of neutron-sdk repo and execute 69 | `rm -rf target/; cargo update && make build`. 70 | 71 | Next, open `neutron-sdk/scripts/test_icq_wasm_juno_testnet/test_wasm_query.sh` 72 | in your text editor of choice. Navigate to `CONNECTION_ID=""` and insert there 73 | connection ID you have just created. 74 | 75 | ## 6. Run test 76 | 77 | Change directory to `neutron-sdk/scripts/test_icq_wasm_juno_testnet` and 78 | execute `./test_wasm_query.sh`. 79 | -------------------------------------------------------------------------------- /scripts/test_icq_wasm_juno_testnet/config.toml: -------------------------------------------------------------------------------- 1 | [global] 2 | log_level = 'trace' 3 | [mode] 4 | 5 | [mode.clients] 6 | enabled = true 7 | refresh = true 8 | misbehaviour = true 9 | 10 | [mode.connections] 11 | enabled = true 12 | 13 | [mode.channels] 14 | enabled = true 15 | 16 | [mode.packets] 17 | enabled = true 18 | clear_interval = 100 19 | clear_on_start = true 20 | tx_confirmation = true 21 | 22 | [rest] 23 | enabled = true 24 | host = '127.0.0.1' 25 | port = 3000 26 | 27 | [telemetry] 28 | enabled = false 29 | host = '127.0.0.1' 30 | port = 3001 31 | 32 | [[chains]] 33 | id = 'test-1' 34 | rpc_addr = 'http://127.0.0.1:26657' 35 | grpc_addr = 'http://127.0.0.1:8090' 36 | event_source = { mode = 'push', url = 'ws://127.0.0.1:26657/websocket', batch_delay = '200ms' } 37 | rpc_timeout = '10s' 38 | account_prefix = 'neutron' 39 | key_name = 'testkey_1' 40 | store_prefix = 'ibc' 41 | default_gas = 100000 42 | max_gas = 3000000 43 | gas_price = { price = 0.0025, denom = 'untrn' } 44 | gas_multiplier = 1.1 45 | max_msg_num = 30 46 | max_tx_size = 2097152 47 | clock_drift = '5s' 48 | max_block_time = '10s' 49 | trusting_period = '14days' 50 | trust_threshold = { numerator = '1', denominator = '3' } 51 | ccv_consumer_chain = true 52 | address_type = { derivation = 'cosmos' } 53 | 54 | [[chains]] 55 | id = 'uni-6' 56 | rpc_addr = 'https://juno-testnet-rpc.polkachu.com' 57 | grpc_addr = 'http://juno-testnet-grpc.polkachu.com:12690' 58 | event_source = { mode = 'push', url = 'wss://juno-testnet-rpc.polkachu.com/websocket', batch_delay = '200ms' } 59 | rpc_timeout = '10s' 60 | account_prefix = 'juno' 61 | key_name = 'testkey_2' 62 | store_prefix = 'ibc' 63 | default_gas = 100000 64 | max_gas = 3000000 65 | gas_price = { price = 0.0025, denom = 'ujunox' } 66 | gas_multiplier = 1.1 67 | max_msg_num = 30 68 | max_tx_size = 2097152 69 | clock_drift = '5s' 70 | max_block_time = '10s' 71 | trusting_period = '14days' 72 | trust_threshold = { numerator = '1', denominator = '3' } 73 | address_type = { derivation = 'cosmos' } 74 | 75 | -------------------------------------------------------------------------------- /scripts/test_icq_wasm_juno_testnet/create_juno_connection.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # http://redsymbol.net/articles/unofficial-bash-strict-mode/ 4 | set -euo pipefail 5 | IFS=$'\n\t' 6 | 7 | HERMES_CONFIG="./config.toml" 8 | NEUTRON_CHAIN_ID="test-1" 9 | JUNO_CHAIN_ID="uni-6" 10 | 11 | NEUTRON_MNEMONIC="alley afraid soup fall idea toss can goose become valve initial strong forward bright dish figure check leopard decide warfare hub unusual join cart" 12 | JUNO_MNEMONIC="ahead horn apart broom chapter pause culture defy original install critic common build act reunion frame shadow trick erode just average keen miss soda" 13 | 14 | for chain in "$NEUTRON_CHAIN_ID" "$JUNO_CHAIN_ID"; do 15 | hermes --config "$HERMES_CONFIG" keys delete --chain "$chain" --all 16 | done 17 | 18 | hermes --config "$HERMES_CONFIG" keys add \ 19 | --key-name testkey_1 \ 20 | --chain "$NEUTRON_CHAIN_ID" \ 21 | --mnemonic-file <(echo "$NEUTRON_MNEMONIC") 22 | 23 | hermes --config "$HERMES_CONFIG" keys add \ 24 | --key-name testkey_2 \ 25 | --chain "$JUNO_CHAIN_ID" \ 26 | --mnemonic-file <(echo "$JUNO_MNEMONIC") 27 | 28 | hermes --config "$HERMES_CONFIG" create connection \ 29 | --a-chain "$NEUTRON_CHAIN_ID" \ 30 | --b-chain "$JUNO_CHAIN_ID" 31 | -------------------------------------------------------------------------------- /scripts/test_icq_wasm_juno_testnet/icq.env: -------------------------------------------------------------------------------- 1 | RELAYER_NEUTRON_CHAIN_RPC_ADDR=tcp://127.0.0.1:26657 2 | RELAYER_NEUTRON_CHAIN_REST_ADDR=http://127.0.0.1:1317 3 | RELAYER_NEUTRON_CHAIN_HOME_DIR=../../../neutron/data/test-1 4 | RELAYER_NEUTRON_CHAIN_SIGN_KEY_NAME=demowallet3 5 | RELAYER_NEUTRON_CHAIN_TIMEOUT=1000s 6 | RELAYER_NEUTRON_CHAIN_GAS_PRICES=0.5untrn 7 | RELAYER_NEUTRON_CHAIN_GAS_ADJUSTMENT=2.0 8 | RELAYER_NEUTRON_CHAIN_CONNECTION_ID=connection-0 9 | RELAYER_NEUTRON_CHAIN_DEBUG=true 10 | RELAYER_NEUTRON_CHAIN_KEYRING_BACKEND=test 11 | RELAYER_NEUTRON_CHAIN_OUTPUT_FORMAT=json 12 | RELAYER_NEUTRON_CHAIN_SIGN_MODE_STR=direct 13 | RELAYER_TARGET_CHAIN_RPC_ADDR=https://rpc.uni.junonetwork.io:443 14 | RELAYER_TARGET_CHAIN_ACCOUNT_PREFIX=neutron 15 | RELAYER_TARGET_CHAIN_VALIDATOR_ACCOUNT_PREFIX=neutronvaloper 16 | RELAYER_TARGET_CHAIN_TIMEOUT=1000s 17 | RELAYER_TARGET_CHAIN_DEBUG=true 18 | RELAYER_TARGET_CHAIN_OUTPUT_FORMAT=json 19 | RELAYER_REGISTRY_ADDRESSES= 20 | RELAYER_ALLOW_TX_QUERIES=true 21 | RELAYER_ALLOW_KV_CALLBACKS=true 22 | RELAYER_MIN_KV_UPDATE_PERIOD=1 23 | RELAYER_STORAGE_PATH=storage/leveldb 24 | RELAYER_CHECK_SUBMITTED_TX_STATUS_DELAY=10s 25 | RELAYER_QUERIES_TASK_QUEUE_CAPACITY=10000 26 | -------------------------------------------------------------------------------- /scripts/test_icq_wasm_juno_testnet/test_wasm_query.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # http://redsymbol.net/articles/unofficial-bash-strict-mode/ 4 | set -euo pipefail 5 | IFS=$'\n\t' 6 | 7 | CONTRACT_PATH="../../artifacts/neutron_interchain_queries.wasm" 8 | CHAIN_ID_1="test-1" 9 | NEUTRON_DIR="${NEUTRON_DIR:-../../../neutron}" 10 | HOME_1="${NEUTRON_DIR}/data/test-1/" 11 | ADDRESS_1="neutron1m9l358xunhhwds0568za49mzhvuxx9ux8xafx2" 12 | ADMIN="neutron1m9l358xunhhwds0568za49mzhvuxx9ux8xafx2" 13 | NODE="tcp://127.0.0.1:26657" 14 | CONNECTION_ID="connection-0" 15 | 16 | wait_tx() { 17 | local txhash 18 | local attempts 19 | txhash="$(jq -r '.txhash' /dev/null; do 22 | ((attempts-=1)) || { 23 | echo "tx $txhash still not included in block" 1>&2 24 | exit 1 25 | } 26 | sleep 0.1 27 | done 28 | } 29 | 30 | code_id="$(neutrond tx wasm store "$CONTRACT_PATH" \ 31 | --from "$ADDRESS_1" --gas 50000000 --chain-id "$CHAIN_ID_1" \ 32 | --broadcast-mode=sync --gas-prices 0.0025untrn -y \ 33 | --output json --keyring-backend=test --home "$HOME_1" \ 34 | --node "$NODE" \ 35 | | wait_tx | jq -r '.logs[0].events[] | select(.type == "store_code").attributes[] | select(.key == "code_id").value')" 36 | echo "Code ID: $code_id" 37 | 38 | contract_address="$(neutrond tx wasm instantiate "$code_id" '{}' \ 39 | --from "$ADDRESS_1" --admin "$ADMIN" -y --chain-id "$CHAIN_ID_1" \ 40 | --output json --broadcast-mode=sync --label "init" --node "$NODE" \ 41 | --keyring-backend=test --gas-prices 0.0025untrn --home "$HOME_1" \ 42 | | wait_tx | jq -r '.logs[0].events[] | select(.type == "instantiate").attributes[] | select(.key == "_contract_address").value')" 43 | echo "Contract address: $contract_address" 44 | 45 | tx_result="$(neutrond tx bank send "$ADDRESS_1" "$contract_address" 10000000untrn \ 46 | -y --chain-id "$CHAIN_ID_1" --output json --broadcast-mode=sync \ 47 | --gas-prices 0.0025untrn --gas 300000 --keyring-backend=test \ 48 | --home "$HOME_1" --node "$NODE" | wait_tx)" 49 | code="$(echo "$tx_result" | jq '.code')" 50 | if [[ "$code" -ne 0 ]]; then 51 | echo "Failed to send money to contract: $(echo "$tx_result" | jq '.raw_log')" && exit 1 52 | fi 53 | echo "Sent money to contract to pay for deposit" 54 | 55 | msg="$(printf '{"register_cw20_balance_query":{ 56 | "connection_id": "%s", 57 | "update_period": 5, 58 | "cw20_contract_address": "juno1jw04ukttvcqrxwy6xsufwrehwhxl8d68d6z7gex4gxwkgta4cwcs8yufe0", 59 | "account_address": "juno1kk5eceqhcd0u65fqlzcvv52e5rjcshz704kere" 60 | }}' "$CONNECTION_ID")" 61 | tx_result="$(neutrond tx wasm execute "$contract_address" "$msg" \ 62 | --from "$ADDRESS_1" -y --chain-id "$CHAIN_ID_1" --output json \ 63 | --broadcast-mode=sync --gas-prices 0.0025untrn --gas 1000000 \ 64 | --keyring-backend=test --home "$HOME_1" --node "$NODE" | wait_tx)" 65 | code="$(echo "$tx_result" | jq '.code')" 66 | if [[ "$code" -ne 0 ]]; then 67 | echo "Failed to register ICQ: $(echo "$tx_result" | jq '.raw_log')" && exit 1 68 | fi 69 | query_id="$(echo "$tx_result" | jq -r '.logs[0].events[] | select(.type == "neutron").attributes[] | select(.key == "query_id").value')" 70 | echo "Registered cw20 balance ICQ with query ID: $query_id" 71 | 72 | echo "Waiting 10 seconds for ICQ result to arrive…" 73 | # shellcheck disable=SC2034 74 | for i in $(seq 10); do 75 | sleep 1 76 | echo -n . 77 | done 78 | echo " done" 79 | 80 | echo 81 | echo "KV query cw20 balance response:" 82 | query="$(printf '{"cw20_balance": {"query_id": %s}}' "$query_id")" 83 | neutrond query wasm contract-state smart "$contract_address" "$query" --node "$NODE" --output json | jq 84 | -------------------------------------------------------------------------------- /scripts/test_interchain_txs.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # http://redsymbol.net/articles/unofficial-bash-strict-mode/ 4 | set -euo pipefail 5 | IFS=$'\n\t' 6 | 7 | CONTRACT_PATH="../artifacts/neutron_interchain_txs.wasm" 8 | CHAIN_ID_1="test-1" 9 | CHAIN_ID_2="test-2" 10 | NEUTRON_DIR="${NEUTRON_DIR:-../../neutron}" 11 | HOME_1="${NEUTRON_DIR}/data/test-1/" 12 | HOME_2="${NEUTRON_DIR}/data/test-2/" 13 | ADDRESS_1="neutron1m9l358xunhhwds0568za49mzhvuxx9ux8xafx2" 14 | ADDRESS_2="cosmos10h9stc5v6ntgeygf5xf945njqq5h32r53uquvw" 15 | ADMIN="neutron1m9l358xunhhwds0568za49mzhvuxx9ux8xafx2" 16 | VALIDATOR="cosmosvaloper18hl5c9xn5dze2g50uaw0l2mr02ew57zk0auktn" 17 | NEUTRON_NODE="tcp://127.0.0.1:26657" 18 | GAIA_NODE="tcp://127.0.0.1:16657" 19 | 20 | wait_tx() { 21 | local txhash 22 | local attempts 23 | txhash="$(jq -r '.txhash' /dev/null; do 26 | ((attempts-=1)) || { 27 | echo "tx $txhash still not included in block" 1>&2 28 | exit 1 29 | } 30 | sleep 0.1 31 | done 32 | } 33 | 34 | wait_tx_gaia() { 35 | local txhash 36 | local attempts 37 | txhash="$(jq -r '.txhash' /dev/null; do 40 | ((attempts-=1)) || { 41 | echo "tx $txhash still not included in block" 1>&2 42 | exit 1 43 | } 44 | sleep 0.1 45 | done 46 | } 47 | 48 | code_id="$(neutrond tx wasm store "$CONTRACT_PATH" \ 49 | --from "$ADDRESS_1" --gas 50000000 --chain-id "$CHAIN_ID_1" \ 50 | --broadcast-mode=sync --gas-prices 0.0025untrn -y \ 51 | --output json --keyring-backend=test --home "$HOME_1" \ 52 | --node "$NEUTRON_NODE" \ 53 | | wait_tx | jq -r '.logs[0].events[] | select(.type == "store_code").attributes[] | select(.key == "code_id").value')" 54 | echo "Code ID: $code_id" 55 | 56 | contract_address=$(neutrond tx wasm instantiate "$code_id" '{}' \ 57 | --from "$ADDRESS_1" --admin "$ADMIN" -y --chain-id "$CHAIN_ID_1" \ 58 | --output json --broadcast-mode=sync --label "init" \ 59 | --keyring-backend=test --gas-prices 0.0025untrn --gas auto \ 60 | --gas-adjustment 1.4 --home "$HOME_1" \ 61 | --node "$NEUTRON_NODE" 2>/dev/null \ 62 | | wait_tx | jq -r '.logs[0].events[] | select(.type == "instantiate").attributes[] | select(.key == "_contract_address").value') 63 | echo "Contract address: $contract_address" 64 | 65 | msg='{"register":{ 66 | "connection_id": "connection-0", 67 | "interchain_account_id": "test", 68 | "register_fee": [{"denom":"untrn","amount":"1000000"}] 69 | }}' 70 | tx_result="$(neutrond tx wasm execute "$contract_address" "$msg" --amount 1100000untrn \ 71 | --from "$ADDRESS_1" -y --chain-id "$CHAIN_ID_1" --output json \ 72 | --broadcast-mode=sync --gas-prices 0.0025untrn --gas 1000000 \ 73 | --keyring-backend=test --home "$HOME_1" --node "$NEUTRON_NODE" | wait_tx)" 74 | code="$(echo "$tx_result" | jq '.code')" 75 | if [[ "$code" -ne 0 ]]; then 76 | echo "Failed to register interchain account: $(echo "$tx_result" | jq '.raw_log')" && exit 1 77 | fi 78 | echo "Waiting 60 seconds for interchain account (sometimes it takes a lot of time)…" 79 | # shellcheck disable=SC2034 80 | for i in $(seq 60); do 81 | sleep 1 82 | echo -n . 83 | done 84 | echo " done" 85 | 86 | msg='{"interchain_account_address_from_contract":{"interchain_account_id":"test"}}' 87 | ica_address="$(neutrond query wasm contract-state smart "$contract_address" "$msg" \ 88 | --node "$NEUTRON_NODE" --output json | jq -r '.data[0]')" 89 | echo "ICA address: $ica_address" 90 | 91 | tx_result=$(gaiad tx bank send "$ADDRESS_2" "$ica_address" 50000uatom \ 92 | --chain-id "$CHAIN_ID_2" --broadcast-mode=sync --gas-prices 0.0025uatom \ 93 | -y --output json --keyring-backend=test --home "$HOME_2" --node "$GAIA_NODE" | wait_tx_gaia) 94 | code="$(echo "$tx_result" | jq '.code')" 95 | if [[ "$code" -ne 0 ]]; then 96 | echo "Failed to send money to ICA: $(echo "$tx_result" | jq '.raw_log')" && exit 1 97 | fi 98 | echo "Sent money to ICA" 99 | 100 | msg="$(printf '{"delegate":{ 101 | "interchain_account_id": "test", 102 | "validator": "%s", 103 | "amount": "2000", 104 | "denom": "uatom" 105 | }}' "$VALIDATOR")" 106 | tx_result="$(neutrond tx wasm execute "$contract_address" "$msg" \ 107 | --from "$ADDRESS_1" -y --chain-id "$CHAIN_ID_1" --output json \ 108 | --broadcast-mode=sync --gas-prices 0.0025untrn --gas 1000000 \ 109 | --keyring-backend=test --home "$HOME_1" --node "$NEUTRON_NODE" | wait_tx)" 110 | code="$(echo "$tx_result" | jq '.code')" 111 | if [[ "$code" -ne 0 ]]; then 112 | echo "Failed to execute contract: $(echo "$tx_result" | jq '.raw_log')" && exit 1 113 | fi 114 | 115 | echo "Waiting 20 seconds for interchain transaction to complete…" 116 | # shellcheck disable=SC2034 117 | for i in $(seq 20); do 118 | sleep 1 119 | echo -n . 120 | done 121 | echo " done" 122 | 123 | echo 124 | echo "This delegation is performed using interchain tx module" 125 | curl -s "http://127.0.0.1:1316/staking/delegators/$ica_address/delegations" | jq '.result' 126 | -------------------------------------------------------------------------------- /scripts/test_kv_query.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # http://redsymbol.net/articles/unofficial-bash-strict-mode/ 4 | set -euo pipefail 5 | IFS=$'\n\t' 6 | 7 | CONTRACT_PATH="../artifacts/neutron_interchain_queries.wasm" 8 | CHAIN_ID_1="test-1" 9 | NEUTRON_DIR="${NEUTRON_DIR:-../../neutron}" 10 | HOME_1="${NEUTRON_DIR}/data/test-1/" 11 | ADDRESS_1="neutron1m9l358xunhhwds0568za49mzhvuxx9ux8xafx2" 12 | ADMIN="neutron1m9l358xunhhwds0568za49mzhvuxx9ux8xafx2" 13 | NODE="tcp://127.0.0.1:26657" 14 | 15 | wait_tx() { 16 | local txhash 17 | local attempts 18 | txhash="$(jq -r '.txhash' /dev/null; do 21 | ((attempts-=1)) || { 22 | echo "tx $txhash still not included in block" 1>&2 23 | exit 1 24 | } 25 | sleep 0.1 26 | done 27 | } 28 | 29 | code_id="$(neutrond tx wasm store "$CONTRACT_PATH" \ 30 | --from "$ADDRESS_1" --gas 50000000 --chain-id "$CHAIN_ID_1" \ 31 | --broadcast-mode=sync --gas-prices 0.0025untrn -y \ 32 | --output json --keyring-backend=test --home "$HOME_1" \ 33 | --node "$NODE" \ 34 | | wait_tx | jq -r '.logs[0].events[] | select(.type == "store_code").attributes[] | select(.key == "code_id").value')" 35 | echo "Code ID: $code_id" 36 | 37 | contract_address="$(neutrond tx wasm instantiate "$code_id" '{}' \ 38 | --from "$ADDRESS_1" --admin "$ADMIN" -y --chain-id "$CHAIN_ID_1" \ 39 | --output json --broadcast-mode=sync --label "init" --node "$NODE" \ 40 | --keyring-backend=test --gas-prices 0.0025untrn --home "$HOME_1" \ 41 | | wait_tx | jq -r '.logs[0].events[] | select(.type == "instantiate").attributes[] | select(.key == "_contract_address").value')" 42 | echo "Contract address: $contract_address" 43 | 44 | tx_result="$(neutrond tx bank send "$ADDRESS_1" "$contract_address" 10000000untrn \ 45 | -y --chain-id "$CHAIN_ID_1" --output json --broadcast-mode=sync \ 46 | --gas-prices 0.0025untrn --gas 300000 --keyring-backend=test \ 47 | --home "$HOME_1" --node "$NODE" | wait_tx)" 48 | code="$(echo "$tx_result" | jq '.code')" 49 | if [[ "$code" -ne 0 ]]; then 50 | echo "Failed to send money to contract: $(echo "$tx_result" | jq '.raw_log')" && exit 1 51 | fi 52 | echo "Sent money to contract to pay for deposit" 53 | 54 | msg='{"register_bank_total_supply_query":{ 55 | "connection_id": "connection-0", 56 | "denoms": ["uatom"], 57 | "update_period": 5 58 | }}' 59 | tx_result="$(neutrond tx wasm execute "$contract_address" "$msg" \ 60 | --from "$ADDRESS_1" -y --chain-id "$CHAIN_ID_1" --output json \ 61 | --broadcast-mode=sync --gas-prices 0.0025untrn --gas 1000000 \ 62 | --keyring-backend=test --home "$HOME_1" --node "$NODE" | wait_tx)" 63 | code="$(echo "$tx_result" | jq '.code')" 64 | if [[ "$code" -ne 0 ]]; then 65 | echo "Failed to register ICQ: $(echo "$tx_result" | jq '.raw_log')" && exit 1 66 | fi 67 | query_id="$(echo "$tx_result" | jq -r '.logs[0].events[] | select(.type == "neutron").attributes[] | select(.key == "query_id").value')" 68 | echo "Registered total supply ICQ with query ID: $query_id" 69 | 70 | echo "Waiting 10 seconds for ICQ result to arrive…" 71 | # shellcheck disable=SC2034 72 | for i in $(seq 10); do 73 | sleep 1 74 | echo -n . 75 | done 76 | echo " done" 77 | 78 | echo 79 | echo "KV query total supply response:" 80 | query="$(printf '{"bank_total_supply": {"query_id": %s}}' "$query_id")" 81 | neutrond query wasm contract-state smart "$contract_address" "$query" --node "$NODE" --output json | jq 82 | -------------------------------------------------------------------------------- /scripts/test_tx_query.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # http://redsymbol.net/articles/unofficial-bash-strict-mode/ 4 | set -euo pipefail 5 | IFS=$'\n\t' 6 | 7 | CONTRACT_PATH="../artifacts/neutron_interchain_queries.wasm" 8 | CHAIN_ID_1="test-1" 9 | CHAIN_ID_2="test-2" 10 | NEUTRON_DIR="${NEUTRON_DIR:-../../neutron}" 11 | HOME_1="${NEUTRON_DIR}/data/test-1/" 12 | HOME_2="${NEUTRON_DIR}/data/test-2/" 13 | ADDRESS_1="neutron1m9l358xunhhwds0568za49mzhvuxx9ux8xafx2" 14 | ADDRESS_2="cosmos10h9stc5v6ntgeygf5xf945njqq5h32r53uquvw" 15 | ADMIN="neutron1m9l358xunhhwds0568za49mzhvuxx9ux8xafx2" 16 | VALIDATOR="cosmos1qnk2n4nlkpw9xfqntladh74w6ujtulwn7j8za9" 17 | NEUTRON_NODE="tcp://127.0.0.1:26657" 18 | GAIA_NODE="tcp://127.0.0.1:16657" 19 | 20 | wait_tx() { 21 | local txhash 22 | local attempts 23 | txhash="$(jq -r '.txhash' /dev/null; do 26 | ((attempts-=1)) || { 27 | echo "tx $txhash still not included in block" 1>&2 28 | exit 1 29 | } 30 | sleep 0.1 31 | done 32 | } 33 | 34 | wait_tx_gaia() { 35 | local txhash 36 | local attempts 37 | txhash="$(jq -r '.txhash' /dev/null; do 40 | ((attempts-=1)) || { 41 | echo "tx $txhash still not included in block" 1>&2 42 | exit 1 43 | } 44 | sleep 0.1 45 | done 46 | } 47 | 48 | code_id="$(neutrond tx wasm store "$CONTRACT_PATH" \ 49 | --from "$ADDRESS_1" --gas 50000000 --chain-id "$CHAIN_ID_1" \ 50 | --broadcast-mode=sync --gas-prices 0.0025untrn -y \ 51 | --output json --keyring-backend=test --home "$HOME_1" \ 52 | --node "$NEUTRON_NODE" \ 53 | | wait_tx | jq -r '.logs[0].events[] | select(.type == "store_code").attributes[] | select(.key == "code_id").value')" 54 | echo "Code ID: $code_id" 55 | 56 | contract_address="$(neutrond tx wasm instantiate "$code_id" '{}' \ 57 | --from "$ADDRESS_1" --admin "$ADMIN" -y --chain-id "$CHAIN_ID_1" \ 58 | --output json --broadcast-mode=sync --label "init" --keyring-backend=test \ 59 | --gas-prices 0.0025untrn --home "$HOME_1" --node "$NEUTRON_NODE" \ 60 | | wait_tx | jq -r '.logs[0].events[] | select(.type == "instantiate").attributes[] | select(.key == "_contract_address").value')" 61 | echo "Contract address: $contract_address" 62 | 63 | tx_result="$(neutrond tx bank send "$ADDRESS_1" "$contract_address" 10000000untrn \ 64 | -y --chain-id "$CHAIN_ID_1" --output json --broadcast-mode=sync \ 65 | --gas-prices 0.0025untrn --gas 300000 --keyring-backend=test \ 66 | --home "$HOME_1" --node "$NEUTRON_NODE" | wait_tx)" 67 | code="$(echo "$tx_result" | jq '.code')" 68 | if [[ "$code" -ne 0 ]]; then 69 | echo "Failed to send money to contract: $(echo "$tx_result" | jq '.raw_log')" && exit 1 70 | fi 71 | echo "Sent money to contract to pay for deposit" 72 | 73 | msg="$(printf '{"register_transfers_query": { 74 | "connection_id": "connection-0", 75 | "recipient": "%s", 76 | "update_period": 5, 77 | "min_height": 1 78 | }}' "$VALIDATOR")" 79 | tx_result="$(neutrond tx wasm execute "$contract_address" "$msg" \ 80 | --from "$ADDRESS_1" -y --chain-id "$CHAIN_ID_1" --output json \ 81 | --broadcast-mode=sync --gas-prices 0.0025untrn --gas 1000000 \ 82 | --keyring-backend=test --home "$HOME_1" --node "$NEUTRON_NODE" | wait_tx)" 83 | code="$(echo "$tx_result" | jq '.code')" 84 | if [[ "$code" -ne 0 ]]; then 85 | echo "Failed to register ICQ: $(echo "$tx_result" | jq '.raw_log')" && exit 1 86 | fi 87 | echo "Registered transfers ICQ" 88 | 89 | tx_result="$(gaiad tx bank send "$ADDRESS_2" "$VALIDATOR" 1000uatom \ 90 | --gas 50000000 --gas-adjustment 1.4 --output json -y \ 91 | --gas-prices 0.5uatom --broadcast-mode=sync --chain-id "$CHAIN_ID_2" \ 92 | --keyring-backend=test --home "$HOME_2" --node "$GAIA_NODE" | wait_tx_gaia)" 93 | code="$(echo "$tx_result" | jq '.code')" 94 | if [[ "$code" -ne 0 ]]; then 95 | echo "Failed to transfer funds to trigger TX ICQ: $(echo "$tx_result" | jq '.raw_log')" && exit 1 96 | fi 97 | echo "Triggered TX ICQ via transferring funds to watched address" 98 | 99 | echo "Waiting 10 seconds for ICQ result to arrive…" 100 | # shellcheck disable=SC2034 101 | for i in $(seq 10); do 102 | sleep 1 103 | echo -n . 104 | done 105 | echo " done" 106 | 107 | echo 108 | echo "TX query response:" 109 | query="$(printf '{"get_recipient_txs": {"recipient": "%s"}}' "$VALIDATOR")" 110 | neutrond query wasm contract-state smart "$contract_address" "$query" --node "$NEUTRON_NODE" --output json | jq 111 | --------------------------------------------------------------------------------