Junø
WebDiscordGithubTwitter
  • Juno
    • Intro
    • Home of CosmWasm
    • Contributors - Core Software
    • Brand Identity
    • Security Disclosures
    • Economic Overview
      • Disclaimer
      • Native Asset (JUNO)
      • Incentive structure
      • Supply API - Data
  • Developer Guides
    • CosmWasm Contracts
      • Compile a Contract
      • Deploy a Contract
      • Guide: How to Upload a Smart Contract on the Juno Chain
      • Use Cw-orchestrator to speed-up your development
      • Query A Contract
      • Send Tokens to a Contract
    • Miscellaneous
      • Conversions
      • Multi Message Transaction
      • Get & Decode Transactions
      • Get Token Prices
      • Get Account Transactions
      • IBC Transfer
      • State Export / Airdrop
    • Juno Modules
      • FeeShare
      • TokenFactory
    • API Endpoints
      • Cosmos
        • Tx
          • V1beta1
            • Simulate
            • Txs
              • Block
        • Params
          • V1beta1
            • Params
        • Bank
          • V1beta1
            • Balances
              • By denom
            • Denoms metadata
            • Params
            • Spendable balances
            • Supply
        • Upgrade
          • V1beta1
            • Applied plan
            • Current plan
            • Module versions
            • Upgraded consensus state
        • Auth
          • V1beta1
            • Accounts
            • Module accounts
            • Params
        • Staking
          • V1beta1
            • Delegations
            • Historical info
            • Params
            • Pool
            • Validators
              • Delegations
                • Unbonding delegation
              • Unbonding delegations
            • Delegators
              • Redelegations
              • Unbonding delegations
              • Validators
        • Evidence
          • V1beta1
            • Evidence
        • Mint
          • V1beta1
            • Annual provisions
            • Inflation
            • Params
        • Feegrant
          • V1beta1
            • Allowance
            • Allowances
            • Issued
        • Gov
          • V1beta1
            • Params
            • Proposals
              • Deposits
              • Tally
              • Votes
        • Distribution
          • V1beta1
            • Community pool
            • Params
            • Delegators
              • Rewards
              • Validators
              • Withdraw address
            • Validators
              • Commission
              • Outstanding rewards
              • Slashes
        • Slashing
          • V1beta1
            • Params
            • Signing infos
        • Authz
          • V1beta1
            • Grants
              • Grantee
              • Granter
        • Base
          • Tendermint
            • V1beta1
              • Blocks
                • Latest
              • Node info
              • Syncing
              • Validatorsets
                • Latest
          • Node
            • V1beta1
              • Config
      • Cosmwasm
        • Wasm
          • V1
            • Code
              • Contracts
            • Contract
              • History
              • Raw
              • Smart
              • State
            • Codes
              • Params
              • Pinned
            • Contracts
              • Creator
      • Juno
        • Feeshare
          • V1
            • Fee shares
            • Params
        • Tokenfactory
          • V1beta1
            • Denoms from creator
            • Params
            • Denoms
              • Authority metadata
      • Ibc
        • Apps
          • Router
            • V1
              • Params
      • API Specification
    • Local Interchain
      • Local Interchain Rust Example
    • Junod Local Dev Setup
    • Integrate Leap wallet
    • SubQuery Indexer
  • Governance
    • Before submitting a proposal
    • Submitting a Proposal (CLI)
      • Formatting Proposal Markdown
  • Command-Line Interface (CLI)
    • Introduction
    • Useful CLI Commands
    • Module Reference
      • bank
      • distribution
      • gov
      • keys
      • params
      • slashing
      • staking
      • status
      • tendermint
      • upgrade
      • wasm
  • Nodes & Validators
    • Junod Installation and setup
    • Setting up Cosmovisor
    • Mainnet Setup and Tooling
    • Joining Mainnet
      • Sync from Snapshot
      • Sync with state-sync
      • Mainnet Upgrades
    • Joining Testnet
    • Relaying
    • Juno Delegations Program
Powered by GitBook
On this page
  • Command Line Interface
  • Rest API Query
  • Cosmology Smart Contract Query
  • CosmJS Query
  • Internal

Was this helpful?

  1. Developer Guides
  2. CosmWasm Contracts

Query A Contract

Describes how to query a cosmwasm smart contract with the CLI & REST API.

PreviousUse Cw-orchestrator to speed-up your developmentNextSend Tokens to a Contract

Last updated 2 years ago

Was this helpful?

Command Line Interface

The most common way to query a cosmwasm smart contract is within the junod wasm smart query command. This follows the following format where query is a JSON string with no spaces. By default, the least amount of data this can be is an empty JSON payload '{}'.

junod query wasm contract-state smart [contract_bech32] [query] [flags]

For this example, we are going to use a random NFT contract on the juno chain. This will show you how to brute force query a contract if you have no idea what the query schema of the contract is. At this time, there is no way to query the format of a contract's requests, but this is something many are actively working on.

Now we attempt to query this contract address and extract some data from it and get which queries are allowed. As you can see, we pass through a random payload for abcde so that the contract will return actual valid query requests

NOTE: A Query can never be empty such as '{}' given you need to specify the path of data you want to reach.

CONTRACT=juno1anh4pf98fe8uh64uuhaasqdmg89qe6kk5xsklxuvtjmu6rhpg53sj9uejj
junod q wasm contract-state smart $CONTRACT '{"abcde":{}}'

# Error parsing into type 
#    cw721_base::msg::QueryMsg<cosmwasm_std::results::empty::Empty>
#    unknown variant `abcde`, 
#    expected one of `owner_of`, `approval`, `approvals`, `all_operators`, 
#    `num_tokens`, `contract_info`, `nft_info`, `all_nft_info`, `tokens`, 
#    `all_tokens`, `minter`, `extension`

The query shows CW721 Base is this contracts name. As this is a standard contract, all messages can be found in the CosmWasm/cw-nfts repository on github

From this, we now know all of the query endpoints and can requests something more specific from the contract for our usage. Let's get

CONTRACT=juno1anh4pf98fe8uh64uuhaasqdmg89qe6kk5xsklxuvtjmu6rhpg53sj9uejj
junod q wasm contract-state smart $CONTRACT '{"all_tokens":{}}'

data:
  tokens:
  - "0"
  - "1"
  - "2"
  - "3"
  - "4"
  - "5"
  - "6"
  - "7"
  - "8"
  
# You can use --output=json to read it via JSON form
# junod q wasm contract-state smart $CONTRACT '{"all_tokens":{}}' --output=json | jq .data

Here we can see there are 8 tokens in this set. Lets query one of the NFTs information

CONTRACT=juno1anh4pf98fe8uh64uuhaasqdmg89qe6kk5xsklxuvtjmu6rhpg53sj9uejj
junod q wasm contract-state smart $CONTRACT '{"nft_info":{}}'

# missing field `token_id`: query wasm contract failed

Just like the first query, we can see that the payload needs more information. It returned an error that we need to specify the token_id we want the nft_info for. Note, Uint128 sized numbers are read as a string

CONTRACT=juno1anh4pf98fe8uh64uuhaasqdmg89qe6kk5xsklxuvtjmu6rhpg53sj9uejj
junod q wasm contract-state smart $CONTRACT '{"nft_info":{"token_id":"8"}}'

# data:
#   extension: null
#   token_uri: ipfs://bafyreib42csdu7426ki7mxk6firvbz4uk3fo4dxpjy2kkskzdhtgj3rriq/metadata.json

Rest API Query

option go_package = "github.com/CosmWasm/wasmd/x/wasm/types";
option (gogoproto.goproto_getters_all) = false;
option (gogoproto.equal_all) = false;

// Query provides defines the gRPC querier service
service Query {
   ...
  // SmartContractState get smart query result from the contract
  rpc SmartContractState(QuerySmartContractStateRequest)
      returns (QuerySmartContractStateResponse) {
    option (google.api.http).get =
        "/cosmwasm/wasm/v1/contract/{address}/smart/{query_data}";
  }
  ...
{
    "data": {
        "tokens": [
            "0",
            "1",
            "2",
            "3",
            "4",
            "5",
            "6",
            "7",
            "8"
        ]
    }
}

Cosmology Smart Contract Query

Here are a few tutorials from cosmology:

CosmJS Query

TODO: Add how to query a smart contract data with Typescript + Example through the RPC endpoint (proto encoded) & httpbatch tendermint client

Internal

TODO: internal rust impl of how to WasmQuery a contract and get some data back.

If you wish to query the data more programmatically with an application such as Python, you may be better suited to use the rest API. You can find these endpoints on in the REST section.

This query endpoint can be found via Juno's SwaggerUI. However, some modules you will not be able to easily find the endpoint. To do this, you will need to search through the proto files. Here we know we want to query the cosmwasm module, which is called wasmd on chain. This repo is found at . In this module, you can see the proto folder in the root of the repo. This will house the endpoints the module exposes so we can find the above path which. This is a query so we find the query proto file \

You must base64 encode the JSON payload for REST API Request. Just take your JSON payload and - put it into - or use Mac / Linux built in command echo '{"all_tokens":{}}' | base64 # eyJhbGxfdG9rZW5zIjp7fX0K

With this, we can now query the contract and gather the data. You can use your web browser, or a library like httpx / requests in Python for automated bots. Be aware that many API providers will late limit the number of requests you can make.

Using , you can create an NPM module to make interactions and queries into dev-friendly Typescript classes to allow you to focus on shipping code.

https://github.com/CosmWasm/cw-nfts/blob/main/contracts/cw721-base/src/msg.rs
https://cosmos.directory/juno/nodes
https://github.com/cosmwasm/wasmd
https://github.com/CosmWasm/wasmd/blob/main/proto/cosmwasm/wasm/v1/query.proto
https://www.base64encode.org/
https://api.juno.strange.love/cosmwasm/wasm/v1/contract/juno1anh4pf98fe8uh64uuhaasqdmg89qe6kk5xsklxuvtjmu6rhpg53sj9uejj/smart/eyJhbGxfdG9rZW5zIjp7fX0K
CosmWasm/ts-codegen
ts-codegen overview for CosmWasm
CosmWasm Contract to Typescript npm module
Configure CosmWasm ts-codegen in your Contracts repo
Query a CosmWasm smart contract from ts-codegen
Enable React Query
Enable Recoil
Integrate Telescope with ts-codegen