# Intro

Juno - Interoperable Smart Contract Network

Juno is a global, open source, permission-less network for decentralized interoperable applications.

Anyone can create & use inter-chain applications on Juno. The ecosystem is pioneering CosmWasm development and adoption, allowing developers to deploy secure & robust inter-chain smart contracts in Rust. The Juno proof of stake blockchain is built using the Cosmos SDK and reaches network agreement via Tendermint Consensus. The network is governed by delegators, who vote in changes via on-chain governance. All network processes are fueled by $JUNO the native asset of the network. Juno had its decentralized network launch on the 1st of October 2021. CosmWasm Smart Contracts went live on December 15th 2021.

<figure><img src="/files/WKZ2af17QeTUAdO1eoB8" alt=""><figcaption></figcaption></figure>

## **Grassroots Origin**

Juno originates & evolves from a **community driven initiative**, prompted by dozens of developers, validators & delegators in the Cosmos ecosystem. The shared vision is to **preserve the neutrality, performance & reliability** of the Cosmos Hub and offload smart contract deployment to a dedicated sister Hub.

Some of the founding principles centre around:

⚪️ Inception of the **worlds first permission-less, designated interoperable smart contract network.**

⚪️ Pioneering **CosmWasm development** **and adoption**.

⚪️ Eliminating common smart contract **L1 bottlenecks** (poor scalability, non-interoperability, high fees, concentrated governance control).

⚪️ **Sister Hub to the Cosmos Hub** - Preserving the neutrality of the Hub by offloading smart contract usage/congestion to a designated contract zone.

⚪️ **Governance by ATOM stakers which become JUNO stakers**. Stakedrop where 47% of the genesis supply goes to ATOM stakers on a 1:1 basis.

⚪️ **Eliminating potential legal limitations** (Juno has not/will not conduct any form of seed sale, private sale or public sale. All $JUNO entered circulation via the decentralized network launch on October 1st 2021).

***

***


# Home of CosmWasm

Juno is the neutral home of CosmWasm smart contracts and the InterWasm DAO. The ecosystem is pioneering CosmWasm development and adoption.

CosmWasm, enables [WebAssembly (WASM) virtual machines (VMs) in the Cosmos SDK](https://medium.com/@interchain_io/virtual-machines-take-off-in-the-cosmos-3d11bd6ae942).

Adding WebAssembly to the Cosmos SDK allows software written in [many languages](https://github.com/appcypher/awesome-wasm-langs/blob/master/README.md) to run securely on a blockchain. WASM serves as an intermediate language that compiles the developer’s language of choice into a portable virtual machine. This means that you can have a simple, secure and fast virtual machine set up to sandbox or partition your application’s actions for better testing, security, performance and speed.

The entrance of a new programming language to the Cosmos Network has several benefits for the overall developer ecosystem. First, this product allows developers to write modules in Rust that integrate seamlessly with the Cosmos SDK, so they can take advantage of the mainnet-proven Cosmos-SDK modules and BPoS Tendermint consensus algorithm while developing a largely Rust-based custom application logic. Second, the ability to upload code in transactions, rather than restarting the chain, allows for a much quicker deployment of new features; the Juno Hub upgrade procedure is necessary only when making changes in the core logic. This enables application-specific zones to freeze the staking logic and iterate quickly on their core value proposition through custom smart contracts. Especially if they limit contract deployment to governance, this can provide an easy way for the chain to ship code quickly. If we launch a chain with the default permissionless uploading of smart contracts, you can build an Ethereum alternative on Tendermint.

***The time is now*****.**

With the [v1.0.0-beta release](https://github.com/CosmWasm/cosmwasm/tree/v1.0.0-beta), we are establishing to build the future of all [Cosmos chains](https://cosmos.network/). Wasm [promises backwards compatibility](https://medium.com/cosmwasm/wen-cosmwasm-1-0-f83c3528187c) and easy upgrade paths from v1.0.0-beta to all future 1.x versions. With stable, polished APIs, and [huge performance improvements](https://medium.com/cosmwasm/wasmer-1-0-integrated-into-cosmwasm-2fa87437458c), we are providing fertile ground for a growing ecosystem of DeFi, NFTs, Governance, and more.

Don’t be too worried about the *beta* label. The APIs are stable and have been tested heavily in various testnets and even a mainnet or two. Confio is awaiting the result of a formal audit, that will start late October. Once the audit results arrive and any issues reported are fixed, Confio will make the official v1.0.0 tag, with *no other changes*.

## Why CosmWasm? <a href="#ea4f" id="ea4f"></a>

CosmWasm runs Web Assembly (Wasm) bytecode, with very mature bindings to develop in the Rust programming language. We are looking to add support for smart contracts in Golang by Q2 next year. This provides a safe, highly performant runtime for your contracts, and the ease of using mature tooling and test frameworks in well-established languages with large developer communities.

The APIs have been designed both for ease of development, as well as preventing the majority of security issues by design. While Solidity makes it easy to write a simple contract, it is very hard to write a complex contract without any security holes. While it takes a bit longer to get started, the architecture of CosmWasm [prevents most classes of attacks present in Solidity](https://docs.cosmwasm.com/docs/0.16/architecture/smart-contracts). Furthermore, the Rust programming language prevents many coding issues at compile-time. So there is no long gap where you produce functional but exploitable contracts.

Besides exploits like reentrancy attacks, faulty implementations of the business logic are a [huge cause of DeFi hacks](https://defirate.com/opyn-hack/). Years of computer engineering have shown that testing (whether unit testing, BDD tests, fuzz tests or TDD) are the best way to avoid such errors in your programs. CosmWasm makes it easy to test your contracts at many level of complexity — from [unit testing a contract in isolation](https://github.com/CosmWasm/cw-plus/blob/main/contracts/cw20-base/src/contract.rs#L786-L831) with mocked input, to native Rust tests [simulating complex cross-contract interactions](https://github.com/CosmWasm/cw-plus/blob/main/contracts/cw3-flex-multisig/src/contract.rs#L528-L572), to integration tests of a [contract inside a running blockchain](https://github.com/CosmWasm/wasmd/blob/master/x/wasm/keeper/staking_test.go#L225-L271). You can even write tests in TypeScript [to test cross-chain contract calls](https://github.com/confio/ts-relayer/blob/main/src/lib/cosmwasm.spec.ts#L152-L298) with local blockchain nodes.

In short, CosmWasm allows you to use familiar, powerful, and safe languages to write highly performant and secure smart contracts. These smart contracts can be deployed to a number of different blockchains and even communicate across blockchains via IBC.


# Contributors - Core Software

Core Root is a global developer collective.  Maintaining & advancing JUNO core software development.

<figure><img src="/files/FIAWhQydZBoOLjwCW0c8" alt=""><figcaption></figcaption></figure>

⚵ Official Twitter: <https://twitter.com/CoreRootHQ>

⚵ Public Forum: <https://discord.gg/Juno>

Reece Williams <https://twitter.com/Reecepbcups_>

Andrea Di Michele aka Dimi <https://twitter.com/dimiandre>

Blockcreators <https://twitter.com/CosmosChain>

Jake Hartnell aka Meow (DAODAO) <https://twitter.com/JakeHartnell>

Lobo aka Wolf (SG-1)[ https://twitter.com/LoboJuno](https://twitter.com/lobojuno)

Jack Zampolin (Strangelove) <https://twitter.com/jackzampolin>

Jacob Gadikian (Notional) <https://twitter.com/gadikian>

Max aka Wombat <https://twitter.com/max_maxsolo>

The Frey (Needlecast) <https://twitter.com/frey_needlecast>

Null aka nullmames (kingnodes) [https://twitter.com/nullmames](https://twitter.com/nullMames)

Tosch aka Toschdev (SG-1) <https://twitter.com/ToschDev>

Callum (DAODAO) <https://twitter.com/callum_and1>

Camel aka CamelJuno #7465

Ekez (DAODAO) <https://twitter.com/ekez___>

Ethereal (Strangelove) <https://twitter.com/Ethereal0ne>

Kevin Garrison (Oni Validator ⛩) <https://twitter.com/KevinGarrison>

Andrew Gouin @gnudrew25

Joe Abbey @joeabbey <https://twitter.com/JoeAbbey>

Boojamya @boojamya

Giansalex (Disperze) <https://twitter.com/giansalex>

Ben (Ben 2x4) <https://twitter.com/ben2x4>

Highlander (Highlander | ChainTools) <https://twitter.com/HighlanderCTs>

Orkun (DEUS Labs) <https://twitter.com/zl00ba>

Eliot Baker (elgorithm) elgorithm#0574

Ethan Frey (Confio) @ethansf

David Fortson (LOA Labs) <https://twitter.com/dave_fortson>

Zakaria Lounes (EZStaking) <https://twitter.com/zakarialounes>

catshark (Notional) <https://twitter.com/_cat_shark>

Sistla Abhishek (OmniFlix) <https://twitter.com/svabhishek>

Simon Warta (Confio) <https://twitter.com/simon_warta>

Denis Fadeev (Tendermint) <https://twitter.com/fadeev>

Wabam (SpacePotatoe) @spacepotayto

Paulo axpppp#2164

CyberObiOne (BroNBro) #4466

Awef awef #1883

shashankgoyal #3525

Nonsencecode nonsensetwice#3475

aswever aswever#4222

### Relayers (The unsung heroes of the Cosmos)

Cros-nest <https://twitter.com/crosnest_com>

CryptoCrew Validators <https://twitter.com/crypto_crew>

Cephalopod Equipment Corp <https://twitter.com/CephalopodEquip>

Notional <https://twitter.com/gadikian>

SpacePotato @spacepotayto

Imperator.co <https://twitter.com/imperator_co>

EZStaking.io <https://twitter.com/EZStaking>

Lavender.Five <https://www.lavenderfive.com/>

Pupmos <https://twitter.com/pupmos>

Golden Ratio Staking <https://twitter.com/GoldenStaking>

PostHuman <https://posthuman.digital/>

ChandraStation <https://www.chandrastation.com/>

Bro\_n\_bro <https://bronbro.io/>

Strangelove Ventures <https://www.strangelove.ventures/>

White Marlin Staking <https://twitter.com/WhiteMarlin4>

Polkachu <https://polkachu.com/>

IcyCRO <https://www.icycro.org/>

StakeLab <https://www.stakelab.fr/>

Witval <https://twitter.com/Vitwit_>

Consensus One <https://twitter.com/ConsensusOne>

Smart Stake <https://juno.smartstake.io/>

Silk Nodes <https://silknodes.io/>

Cosmos Spaces <https://twitter.com/Cosmos_spaces>

ChainTools <https://twitter.com/ChaintoolsT>

Stake\&Relax <https://linktr.ee/stakeandrelax>

Oni Validator ⛩ <https://twitter.com/OniValidator>

Kleomedes <https://kleomed.es>

The list is constantly expanding. If your name is not mentioned and your actively contributing please reach out to the core team.


# Brand Identity

**Assets**

{% file src="/files/5XuIz93zBMu4TFPxYffM" %}

{% file src="/files/cyLzlvzTDGGX8RFOPa4d" %}

{% file src="/files/ZpVL2dbJi859eWH87snb" %}

{% file src="/files/4wWciqcnESTQP3iGTISW" %}

{% file src="/files/4SDksqTh0pbmxxH7p2mB" %}

{% file src="/files/QU0LYHNC0e2w96KDPi5y" %}

{% file src="/files/w7nLMwUFH9eX3xyGc2YF" %}

{% file src="/files/byam7kPlFGxdLXvXZAjI" %}

{% file src="/files/hP0HpwLNvBw0waV8Nnv2" %}

{% file src="/files/hDNvihZKGH7FxvWu4FwA" %}

{% file src="/files/4reIvCpTgJwUSQ8q8fu5" %}

{% file src="/files/o21r05Q8Q1H5YxiIKxOl" %}

**Color Identity**

Primary Color: #FF7B7C

<figure><img src="/files/MyBujaQfmJgOJAXLxXVf" alt=""><figcaption></figcaption></figure>

Secondary Color: #270B0D

<figure><img src="/files/dRyZ8PVGe0KyQNTsmpPt" alt=""><figcaption></figcaption></figure>

Complementary Color: #FFEBD2

<figure><img src="/files/cf8hH10Fnn3A1snuUFja" alt=""><figcaption></figcaption></figure>

**Font Identity**

The Wordmark font is Gotham Medium.

![](/files/amSqTedyZlqA5nk6q2d7)


# Security Disclosures

Found a critical bug or need to report a security issue? Juno's disclosure process is documented alongside the source code, but is also reproduced here.

{% hint style="danger" %}
If you have a vulnerability or critical issue to disclose, follow responsible disclosure practice and do not speak publicly about it. If it affects other CosmWasm chains, then notify them as well. Typically, chains maintain a `SECURITY.md` document alongside their source code with instructions for notifying the team.
{% endhint %}

Juno's [SECURITY.md file can be found here](https://github.com/CosmosContracts/juno/blob/main/SECURITY.md), and is reproduced below:

## Juno bug reporting

The Juno core development team uses GitHub to manage feature requests and bugs. This is done via GitHub Issues.

### Triage and progress 🔜

Issues added to GitHub will be triaged as they come in.

Tracking of in-flight issues will be done through the Juno Core project board, but of course we reserve the right to not make a public issue if there is a security implication in doing so.

### Feature request 🚀

For a feature request, e.g. module inclusion, please make a GitHub issue. Clearly state your use case and what value it will bring to other users or developers on Juno.

If it is something that can be handled by a param change, discuss it on Discord in the `#governance` channel, and consider a governance proposal.

### Standard priority bug 🐛

For a bug that is non-sensitive and/or operational in nature rather than a critical vulnerability, please add it as a GitHub issue.

If it is not triaged in a couple of days, feel free to tag `@the-frey` or `@jakehartnell`.

### Critical bug or security issue 💥

If you're here because you're trying to figure out how to notify us of a security issue, go to [Discord](https://discord.gg/wHdzjS5vXx), and alert the core engineers:

* Jake (Meow) `Meow Stargaze ✨🔭#1736`
* Dimi `dimi 🦙#2998`
* Alex (the-frey) `the-frey#8626`
* Jacob `jacobgadikian#9883`

Please avoid opening public issues on GitHub that contain information about a potential security vulnerability as this makes it difficult to reduce the impact and harm of valid security issues.

#### Coordinated Vulnerability Disclosure Policy

We ask security researchers to keep vulnerabilities and communications around vulnerability submissions private and confidential until a patch is developed. In addition to this, we ask that you:

* Allow us a reasonable amount of time to correct or address security vulnerabilities.
* Avoid exploiting any vulnerabilities that you discover.
* Demonstrate good faith by not disrupting or degrading Juno’s network, data, or services.

#### Vulnerability Disclosure Process

Juno uses the following disclosure process:

* Once a security report is received, the Juno core development team works to verify the issue.
* Patches are prepared for eligible releases in private repositories.
* We notify the community that a security release is coming, to give users time to prepare their systems for the update. Notifications can include Discord messages, tweets, and emails to partners and validators.
* 24 hours following this notification, the fixes are applied publicly and new releases are issued.
* Once releases are available for Juno, we notify the community, again, through the same channels as above. We also publish a Security Advisory on Github and publish the CVE, as long as neither the Security Advisory nor the CVE include any information on how to exploit these vulnerabilities beyond what information is already available in the patch itself.
* Once the community is notified, we will pay out any relevant bug bounties to submitters.
* One week after the releases go out, we will publish a post with further details on the vulnerability as well as our response to it.

This process can take some time. Every effort will be made to handle the bug in as timely a manner as possible. However, it's important that we follow the process described above to ensure that disclosures are handled consistently and to keep Juno and the projects running on it secure.


# Economic Overview

Juno´s economic system is designed to foster a self-sustaining economy where incentives are aligned to drive security and decentralization of the Juno Network.

Participants in this economy include validators, developers and delegators.

The native network incentive structures is pre-set in the Juno Protocol at genesis but subject to change based on the flexible evolution of the economy. All changes to the structure can be voted in or out by Juno delegators and validators. Not only does the native asset secure the network but gives onchain governance voting rights. Incentives follow a pre-set game-theory model that has been crafted to strongly incentivize early adopters and gradually decreases as fees generated by p2p transactions and usage of decentralized applications on Juno make up for the decrease over time. These protocol-based rewards are distributed across the active delegated stake/validator set. More structural details can be found in the incentive structure tab (Below the economic overview).

Developers play a crucial role in the Juno economy. They are a core economic driver and deliver value by building out the network infrastructure/tooling and open source decentralized applications. For this reason the community pool has one of the biggest genesis allocations in the entire Cosmos ecosystem. The primary role of the community pool is to support these initiatives by providing a funding kickstart not to be confused with funding independent projects entirely that could use alternative ways of allocating capital to a cause. Support may go to initiatives that directly add long-term value to the Juno Network native asset and its participants at large.


# Disclaimer

Juno is the native utility asset of the decentralized Juno Network.

The asset has the following properties:

1. Unlocks access to on-chain governance
2. Transport fuel for all processes on the network ie. gas to cover tx fees.
3. Medium used to deploy smart contracts
4. Key to securing the proof of stake network

All Juno that exist today entered circulation via the decentralized network launch on October 1st, 2021. There has never been a seed, private or public sale. All circulating Juno were given away for free by the network itself at genesis (genesis block), to ATOM stakers on a 1:1 basis (Stargate Snapshot).

No promises of monetary returns from the distribution of Juno were ever made by anyone in the Juno ecosystem.

No centralized exchange listing was ever paid for by anyone in the ecosystem nor does any liquidity come from paid market makers. Instead all liquidity on decentralized exchanges is supplied by thousands of community members.

The asset has never been advertised, publicized nor was anyone ever encouraged to purchase or sell the native asset by the independent ecosystem developers.

As a decentralized network, Juno is controlled by 250000+ unique addresses ie. delegators that decide the direction of the blockchain via on-chain governance, and 150 validators that run nodes to secure the network (As of July 2022).


# Native Asset (JUNO)

## **Token Economics (Tokenomics)**

### **Summary**

Juno Network is a completely community owned and operated smart contract platform. Therefore, the majority of the genesis supply (Over 95%) was stake-dropped to atom stakers, committed to the community pool, and committed to the development reserve for ongoing development of the Juno Network features.

✅ Initial Circulating Supply: 33.036.534 $JUNO

✅ Initial Total Supply: 64.903.242 $JUNO‌

✅ Maximum Supply (Reached after 12 years (2033): 185.562.268 $JUNO

![](/files/wj3jkOFP6oqOV3sFqRzH)

### **Token Distribution Breakdown**

⚪️ **Community Stakedrop**: 30.663.193 $JUNO (Genesis Community Stakedrop - Unvested)

Free stakedrop to ATOM stakers at inception on October 1st 2021.

⚪️ **Community Pool:** 20.000.000 $JUNO (Genesis Community Pool Allocation / Non circulating at genesis)

At inception, 20 Million $JUNO were allocated to the community pool. Non-circulating and owned by the public JUNO commonwealth ie. all network stakers own these funds.

⚪️ **Hackathons**: 2.373.341 $JUNO (50% distributed post genesis via JunoHack 1)

Allocated to HackJuno smart contract challenges. These funds are managed by the Core-1 SubDAO and assigned to various Hackathons.

⚪️ **Core** **Software** **Development Reserve** (Community owned. Managed by Core 1 SubDAO)**:** 10.084.396 $JUNO (Vested 12 years / Periodic unlocks until year 12)

Genesis core software and infrastructure reserve. Owned by the public JUNO commonwealth. Managed by the Core-1 subDAO.

⚪️ **Core- 1 Developers** (Genesis allocations)**:** 1.782.312 $JUNO (Vested 12 years / Periodic unlocks until year 12)

Genesis core developer allocation.


# Incentive structure

### Reward Schedule <a href="#id-8ab1" id="id-8ab1"></a>

{% hint style="info" %}
The Juno rewards model distributes a fixed amount of $juno per block, which is calculated by the network and depends on the inflation rate as well as network block time. Variation in the network block time will cause variation in the calculable annual percentage rate (APR).
{% endhint %}

⚪️ **Phase 1**: Fixed inflation 40%

New Juno in year 1 = (+25.961.297)

Total supply after year 1 = 90.864.540 $JUNO

⚪️ **Phase 2**: Fixed inflation 20%

New Juno in year 2 = (+18.172.908)

Total supply after year 2 = 109.037.449 $JUNO

⚪️ **Phase 3**: Fixed inflation 10%

New Juno in year 3= (+10.903.744)

Total supply after year 3 = 119.941.194 $JUNO

> Once the inflation reaches 10% it gradually reduces on a fixed 1% basis each year.

⚪️ **Phase 4** = Fixed 9% (+10.794.707) Total supply = 130.735.901 $JUNO

⚪️ **Phase 5** = Fixed 8% (+10.458.872) Total supply = 141.194.773 $JUNO

⚪️ **Phase 6** = Fixed 7% (+9.883.634) Total supply = 151.078.407 $JUNO

⚪️ **Phase 7** = Fixed 6% (+9.064.704) Total supply = 160.143.112 $JUNO

⚪️ **Phase 8** = Fixed 5% (+8.007.155) Total supply = 168.150.267 $JUNO

⚪️ **Phase 9** = Fixed 4% (+6.726.010) Total supply = 174.876.278 $JUNO

⚪️ **Phase 10** = Fixed 3% (+5.246.288) Total supply = 180.122.566 $JUNO

⚪️ **Phase 11** = Fixed 2% (+3.602.451) Total supply = 183.725.018 $JUNO

⚪️ **Phase 12** = Fixed 1% (+1.837.250) Max supply = 185.562.268 $JUNO


# Supply API - Data

The following API endpoints provide information about JUNO current circulating supply as well as the total available supply:

* [Circulating Supply](https://supply-api.junonetwork.io/circulating-supply) (<https://supply-api.junonetwork.io/circulating-supply>)
* [Total Supply](https://supply-api.junonetwork.io/total-supply) (<https://supply-api.junonetwork.io/total-supply>)


# CosmWasm Contracts


# Compile a Contract

How to Compile CosmWasm Smart Contracts

[This guide is from the official CosmWasm/rust-optimizer repository](https://github.com/CosmWasm/rust-optimizer). This method of compiling the contract will optimize the final build so that it reduces gas consumption.

Example contracts for this can be found at <https://github.com/CosmWasm/cw-examples>. This repository [requires this section to compile](#multiple-contract-repository-mono-repo) since multiple contracts are involved in a single repository.

{% hint style="info" %}
If you have ZERO experience with smart contracts, you need to check out [book.cosmwasm.com](https://book.cosmwasm.com) for setting up your environment, testnet, and the basics of CosmWasm.\
\
For all great CosmWasm tools, <https://github.com/CosmWasm/awesome-cosmwasm>
{% endhint %}

## Single Contract Repository

The easiest way is to simply use the [published docker image](https://hub.docker.com/r/cosmwasm/rust-optimizer). You must run this in the root of the smart contract repository you wish to compile. It will produce an `artifacts` directory with `<crate_name>.wasm` and `contracts.txt` containing the hashes. This is just one file.

```bash
docker run --rm -v "$(pwd)":/code \
  --mount type=volume,source="$(basename "$(pwd)")_cache",target=/code/target \
  --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \
  cosmwasm/rust-optimizer:0.12.11

# If you you use an ARM machine (Ex: Mac M1), you need to use the following
# This is experimental and should not be used for production use

docker run --rm -v "$(pwd)":/code \
  --mount type=volume,source="$(basename "$(pwd)")_cache",target=/code/target \
  --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \
  cosmwasm/rust-optimizer-arm64:0.12.11
```

By running this in the root of your project, it will compile your contract into an artifacts/ folder. From here you can upload it to chain, collect the store code, and interact with it as you design

## Multiple Contract Repository (Mono Repo)

Sometime you want many contracts to be related and import common functionality. This is exactly the case of [`cosmwasm-plus`](https://github.com/CosmWasm/cosmwasm-plus). In such a case, we can often not just compile from root, as the compile order is not deterministic and there are feature flags shared among the repos. This has lead to [issues in the past](https://github.com/CosmWasm/rust-optimizer/issues/21).

For this use-case there is second docker image, which will compile all the `contracts/*` folders inside the workspace and do so one-by-one in alphabetical order. It will then add all the generated wasm files to an `artifacts` directory with a checksum, just like the basic docker image (same output format).

To compile all contracts in the workspace deterministically, you can run:

```bash
docker run --rm -v "$(pwd)":/code \
  --mount type=volume,source="$(basename "$(pwd)")_cache",target=/code/target \
  --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \
  cosmwasm/workspace-optimizer:0.12.11

# If you you use an ARM machine (Ex: Mac M1), you need to use the following
# This is experimental and should not be used for production use

docker run --rm -v "$(pwd)":/code \
  --mount type=volume,source="$(basename "$(pwd)")_cache",target=/code/target \
  --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \
  cosmwasm/workspace-optimizer-arm64:0.12.11
```

**NOTE**: See the difference with **workspace-optimizer** vs **rust-optimizer** in the previous single contract example.\\


# Deploy a Contract

Submit the code of a smart contract to chain and get its code id

## PreRequisite

Make sure you follow the [compile a contract](/developer-guides/cosmwasm-contracts/compile-a-contract) guide first for your project. Once you have a contract compiled in the artifacts/\*.wasm directory, you are ready for this guide.

This guide will show you how to deploy and interact with a contract using CLI. For scripting using Rust, you can use [cw-orchestrator](/developer-guides/cosmwasm-contracts/cw-orchestrator).

## Upload

You need to upload the contract via the CLI to chain. To do this, perform the following

```bash
TXFLAGS="--chain-id=uni-6 --gas-prices=0.025ujunox --gas=auto --gas-adjustment 1.3"

junod tx wasm store artifacts/CONRTACT_NAME.wasm \
    --from <KEY> $TXFLAGS -y --broadcast-mode=block
```

This will then return a transaction hash. With this data, you need to query it to get the code id of the contract on chain

```bash
junod q tx 38330E909CD219B80927009DA37FD69D334D19B2AD4EC47456A24E85034F0085 --output=json
```

This will return the data about the transaction, and give us the code id of our contract

```json
{
  "height": "294601",
  "txhash": "38330E909CD219B80927009DA37FD69D334D19B2AD4EC47456A24E85034F0085",
  "codespace": "",
  "code": 0,
  "data": "0A460A1E2F636F736D7761736D2E7761736D2E76312E4D736753746F7265436F64651224080D12203318E74E8C68DBCC6E0317C42B8DB0AB642B61AEFAD487DEDB6ECB54FFED4D72",
  "raw_log": "[{\"events\":[{\"type\":\"message\",\"attributes\":[{\"key\":\"action\",\"value\":\"/cosmwasm.wasm.v1.MsgStoreCode\"},{\"key\":\"module\",\"value\":\"wasm\"},{\"key\":\"sender\",\"value\":\"juno1hj5fveer5cjtn4wd6wstzugjfdxzl0xps73ftl\"}]},{\"type\":\"store_code\",\"attributes\":[{\"key\":\"code_checksum\",\"value\":\"3318e74e8c68dbcc6e0317c42b8db0ab642b61aefad487dedb6ecb54ffed4d72\"},{\"key\":\"code_id\",\"value\":\"13\"}]}]}]",
  "logs": [
    {
      "msg_index": 0,
      "log": "",
      "events": [
        {
          "type": "message",
          "attributes": [
            {
              "key": "action",
              "value": "/cosmwasm.wasm.v1.MsgStoreCode"
            },
            {
              "key": "module",
              "value": "wasm"
            },
            {
              "key": "sender",
              "value": "juno1hj5fveer5cjtn4wd6wstzugjfdxzl0xps73ftl"
            }
          ]
        },
        {
          "type": "store_code",
          "attributes": [
            {
              "key": "code_checksum",
              "value": "3318e74e8c68dbcc6e0317c42b8db0ab642b61aefad487dedb6ecb54ffed4d72"
            },
            {
              "key": "code_id",
              "value": "13"
            }
          ]
        }
      ]
    }
  }]
}
```

We can see both raw\_log and also logs\[0].events\[1].store\_code shows the code\_id being 13. If you wish the automate this return code in bash to a variable, you can

```bash
# ensure jq is installed
UPLOAD_TX_HASH=38330E909CD219B80927009DA37FD69D334D19B2AD4EC47456A24E85034F0085
CODE_ID=$(junod q tx $UPLOAD_TX_HASH --output json | jq -r '.logs[0].events[] | select(.type == "store_code").attributes[] | select(.key == "code_id").value') && echo "Code Id: $CODE_ID"
```

## Instantiate

With the code now being up on chain, we can now run logic to setup our own copy of the contract which we control. This will then give us a unique contract address for others to interact with in accordance with the contract logic. This example is from the [cosmwasm/cw-template](https://github.com/CosmWasm/cw-template).

Ensure you change CODE\_ID to match your code id from the store code

<pre class="language-sh"><code class="lang-sh"># Manual
CODE_ID=1
junod tx wasm instantiate "$CODE_ID" '{"count":0}' --label "some-contract" $FLAGS -y --admin &#x3C;your-address-here>
<strong># then query the tranasaction hash as we do above.
</strong>
# Automated return of the contract address
CODE_ID=1
TX_INIT=$(junod tx wasm instantiate "$CODE_ID" '{"count":0}' --label "contract" $FLAGS -y --admin &#x3C;your-address-here> | jq -r '.txhash') &#x26;&#x26; echo $TX_INIT
CONTRACT_ADDR=$($BINARY query tx $TX_INIT --output json | jq -r '.logs[0].events[0].attributes[0].value') &#x26;&#x26; echo "CONTRACT_ADDR: $CONTRACT_ADDR"
</code></pre>


# Guide: How to Upload a Smart Contract on the Juno Chain

Welcome to this tutorial on deploying a smart contract to the Juno testnet. This guide will show you how to deploy and interact with a contract using CLI. For scripting using Rust, you can use \[cw-orc

{% embed url="<https://youtu.be/e_-xxpfQfwU>" %}

## **Preparation:**

**Required Materials:** A computer with an internet connection, familiarity with GitHub, and basic knowledge of smart contracts.

## **Steps:**

1. **Find an Example Smart Contract:**

(Note: The steps here mainly involve browsing, no specific bash commands.)

In this tutorial we will be using [https://github.com/Reecepbcups/cw-clock-exampl](https://github.com/Reecepbcups/cw-clock-example)

2. **Connect to the Juno Testnet:**

Check out our new video that shows you how to deploy a local env

<https://github.com/Reecepbcups/cw-clock-example>

3. **Create a Juno Wallet:**

```json
bash junod keys add MyWalletName
```

**5. Claim junox Test Tokens:**

Head to Juno Discord <https://discord.com/invite/caEBtA4QDb> and find FAUCET section. In there you can get some using the API provided and inputting the wallet address you created in the previous step. <https://faucet.reece.sh/uni-6/JUNO_ADDRESS_HERE>

**6. Verify Token Receipt:**

```
junod query bank balances [YOUR_WALLET_ADDRESS]
```

**7. Configure the Juno Command Line:**

```json
bash junod config node [NODE_URL] 
junod config chain-id [CHAIN_ID] 
junod config gas auto 
junod config gas-prices 0.025ujuno
```

**8. Deploy the Smart Contract:**

Assuming you've downloaded clock\_example.wasm to your current directory

```
junod tx wasm store clock_example.wasm --from MyWalletName --gas 1500000 --chain-id [CHAIN_ID]
```

**9. Instantiate the Smart Contract:**

Replace \[CODE\_ID] with the code ID obtained from the previous step e.g 3785

```json
 junod tx wasm instantiate [CODE_ID] '{"count": 0}' --label "my-clock-instance" --from MyWalletName --amount 100ujuno
```

**10. Interact with the Smart Contract:**

Query the smart contract (replace \[CONTRACT\_ADDRESS] with the address from instantiation) junod query wasm contract \[CONTRACT\_ADDRESS]

```json

junod tx wasm execute [CONTRACT_ADDRESS] '{"increment": {}}' --from MyWalletName --amount 10ujuno
```

### **Conclusion:**

* You've now successfully uploaded, instantiated, and interacted with a smart contract on the Juno testnet.
* If you have further questions or ideas, join the Juno community on Discord, particularly the "developer lounge".

***

**Note:** Adjust the bash commands to fit your specific situation, and always double-check them, especially when working with real tokens or live environments.\\


# Use Cw-orchestrator to speed-up your development

Integrate you smart-contract with cw-orch and facilitate testing/development and maintenance of your project.

## Introduction

cw-orchestrator is the most advanced scripting, testing, and deployment framework for CosmWasm smart-contracts. It makes it easy to write cross-environment compatible code for [cw-multi-test](https://github.com/CosmWasm/cw-multi-test), [Test Tube](https://github.com/osmosis-labs/test-tube), [Starship](https://github.com/cosmology-tech/starship) (alpha), and live networks, significantly reducing code duplication and test-writing time.

Get ready to change the way you interact with contracts and simplify you smart-contracts journey. The following steps will allow you to integrate `cw-orch` and write clean code such as:

```rust,ignore
counter.upload()?;
counter.instantiate(&InstantiateMsg { count: 0 }, None, None)?;
counter.increment()?;

let count = counter.get_count()?;
assert_eq!(count.count, 1);
```

In this quick-start guide, we will review the necessary steps in order to integrate [`cw-orch`](https://github.com/AbstractSDK/cw-orchestrator) into a simple contract crate. [We review integration of rust-workspaces (multiple contracts) at the end of this page](#integration-in-a-workspace).

> **NOTE**: *Quicker than the quick start*
>
> If you're moving quicker than everybody else, we suggest looking at [a before-after review of this example integration](https://github.com/AbstractSDK/cw-orch-counter-example/compare/e0a54b074ca1a894bb6e58276944cf2013d152f2..main). This will help you catch the additions you need to make to your contract to be able to interact with it using cw-orchestrator.

> **NOTE**: If you want to go more in depth, [browse the full `cw-orch` documentation](https://orchestrator.abstract.money/).

## Summary

* [Introduction](#introduction)
* [Summary](#summary)
* [Single Contract Integration](#single-contract-integration)
  * [Adding `cw-orch` to your `Cargo.toml` file](#adding-cw-orch-to-your-cargotoml-file)
  * [Creating an Interface](#creating-an-interface)
  * [Interaction helpers](#interaction-helpers)
  * [Using the integration](#using-the-integration)
* [Integration in a workspace](#integration-in-a-workspace)
  * [Handling dependencies and features](#handling-dependencies-and-features)
  * [Creating an interface crate](#creating-an-interface-crate)
  * [Integrating single contracts](#integrating-single-contracts)
* [More examples and scripts](#more-examples-and-scripts)

## Single Contract Integration

Throughout this example, we will be using `cw-orch` to interact with a simple counter contract. All the steps below apply to any smart contract, no matter the complexity.

### Adding `cw-orch` to your `Cargo.toml` file

To use cw-orchestrator, you need to add `cw-orch` to your contract's TOML file. Run the command below in your contract's directory:

```shell
cargo add --optional cw-orch
```

Alternatively, you can add it manually in your `Cargo.toml` file as shown below:

```toml
[dependencies]
cw-orch = {version = "0.19.1", optional = true } # Latest version at time of writing
```

Now that we have added `cw-orch` as an optional dependency we will want to enable it through a feature-flag. This ensures that the code added by `cw-orch` is **not** included in the wasm artifact of the contract.

To do this add an `interface` feature to the `Cargo.toml` and enable `cw-orch` when it is enabled like so:

```toml
[features]
interface = ["dep:cw-orch"] # Enables cw-orch when the feature is enabled
```

> **NOTE**: If you are using `rust-analyzer`, you can add the following two lines in your `settings.json` to make sure the features get taken into account when checking the project:
>
> ```json
>  "rust-analyzer.cargo.features": "all",
>  "rust-analyzer.check.features": "all",
> ```

### Creating an Interface

When using a single contract, we advise creating an `interface.rs` file inside your contract's directory. You then need to add this module to your `lib.rs` file. Don't forget to *feature-flag* the module in order to be able to use `cw-orch` inside it.

```rust,ignore
#[cfg(feature = "interface")]
mod interface;
```

Then, inside that `interface.rs` file, you can define the interface for your contract:

```rust,ignore
use cw_orch::{interface, prelude::*};

use crate::msg::{ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg};

pub const CONTRACT_ID: &str = "counter_contract";

#[interface(InstantiateMsg, ExecuteMsg, QueryMsg, MigrateMsg, id = CONTRACT_ID)]
pub struct CounterContract;

impl<Chain: CwEnv> Uploadable for CounterContract<Chain> {
    /// Return the path to the wasm file corresponding to the contract
    fn wasm(&self) -> WasmPath {
        artifacts_dir_from_workspace!()
            .find_wasm_path("counter_contract")
            .unwrap()
    }
    /// Returns a CosmWasm contract wrapper
    fn wrapper(&self) -> Box<dyn MockContract<Empty>> {
        Box::new(
            ContractWrapper::new_with_empty(
                crate::contract::execute,
                crate::contract::instantiate,
                crate::contract::query,
            )
            .with_migrate(crate::contract::migrate),
        )
    }
}

```

Learn more about the content of the interface creation specifics in the [`cw-orch` documentation](https://orchestrator.abstract.money/contracts/interfaces.html#creating-an-interface)

> **NOTE**: It can be useful to re-export this struct to simplify usage (in `lib.rs`):
>
> ```rust,ignore
> #[cfg(feature = "interface")]
> pub use crate::interface::CounterContract;
> ```

### Interaction helpers

cw-orchestrator provides a additional macros that simplify contract calls and queries. The macro implements functions on the interface for each variant of the contract's `ExecuteMsg` and `QueryMsg`.

Enabling this functionality is very straightforward. Find your `ExecuteMsg` and `QueryMsg` definitions (in `msg.rs` in our example) and add the `ExecuteFns` and `QueryFns` derive macros to them like below:

```rust,ignore
#[cw_serde]
#[cfg_attr(feature = "interface", derive(cw_orch::ExecuteFns))] // Function generation
/// Execute methods for counter
pub enum ExecuteMsg {
    /// Increment count by one
    Increment {},
    /// Reset count
    Reset {
        /// Count value after reset
        count: i32,
    },
}

#[cw_serde]
#[cfg_attr(feature = "interface", derive(cw_orch::QueryFns))] // Function generation
#[derive(QueryResponses)]
/// Query methods for counter
pub enum QueryMsg {
    /// GetCount returns the current count as a json-encoded number
    #[returns(GetCountResponse)]
    GetCount {},
}

// Custom response for the query
#[cw_serde]
/// Response from get_count query
pub struct GetCountResponse {
    /// Current count in the state
    pub count: i32,
}
```

Find out more about the interaction helpers in the [`cw-orch` documentation](https://orchestrator.abstract.money/contracts/interfaces.html#entry-point-function-generation)

> **NOTE**: Again, it can be useful to re-export these generated traits to simplify usage (in `lib.rs`):
>
> ```rust,ignore
> #[cfg(feature = "interface")]
> pub use crate::msg::{ExecuteMsgFns as CounterExecuteMsgFns, QueryMsgFns as CounterQueryMsgFns};
> ```

### Using the integration

Now that all the setup is done, you can use your contract in tests, integration-tests or scripts.

Start by importing your crate, with the `interface` feature enabled. Depending on your use-case this will be in `[dependencies]` or `[dev-dependencies]`:

```toml
counter-contract = { path = "../counter-contract", features = ["interface"] }
```

You can now use:

```rust,ignore
use counter_contract::{
    msg::InstantiateMsg, CounterContract, CounterExecuteMsgFns, CounterQueryMsgFns,
};
use cw_orch::{anyhow, prelude::*, tokio};
use tokio::runtime::Runtime;

const LOCAL_MNEMONIC: &str = "clip hire initial neck maid actor venue client foam budget lock catalog sweet steak waste crater broccoli pipe steak sister coyote moment obvious choose";
pub fn main() -> anyhow::Result<()> {
    std::env::set_var("LOCAL_MNEMONIC", LOCAL_MNEMONIC);
    dotenv::dotenv().ok(); // Used to load the `.env` file if any
    pretty_env_logger::init(); // Used to log contract and chain interactions

    let rt = Runtime::new()?;
    let network = networks::LOCAL_JUNO;
    let chain = DaemonBuilder::default()
        .handle(rt.handle())
        .chain(network)
        .build()?;


    let counter = CounterContract::new(chain);

    counter.upload()?;
    counter.instantiate(&InstantiateMsg { count: 0 }, None, None)?;

    counter.increment()?;

    let count = counter.get_count()?;
    assert_eq!(count.count, 1);

    Ok(())
}
```

## Integration in a workspace

In this paragraph, we will use the `cw-plus` repository as an example. You can review:

* [The full integration code](https://github.com/AbstractSDK/cw-plus) with `cw-orch` added
* [The complete diff](https://github.com/cosmwasm/cw-plus/compare/main...abstractsdk:main) that shows you all integration spots (if you want to go fast)

### Handling dependencies and features

When using workspaces, you need to do the 2 following actions on all crates that include `ExecuteMsg` and `QueryMsg` used in your contracts:

1. Add `cw-orch` as an optional dependency
2. Add an `interface` feature (ensures `cw-orch` is not compiled into your `wasm` contract)

Refer above to [Adding `cw-orch` to your `Cargo.toml` file](#adding-cw-orch-to-your-cargotoml-file) for more details on how to do that.

For instance, for the `cw20_base` contract, you need to execute those 2 steps on the `cw20-base` contract (where the `QueryMsg` are defined) as well as on the `cw20` package (where the `ExecuteMsg` are defined).

### Creating an interface crate

When using a workspace, we advise you to create a new crate inside your workspace for defining your contract's interfaces. In order to do that, use:

```shell
cargo new interface --lib
cargo add cw-orch --package interface 
```

Add the interface package to your workspace `Cargo.toml` file

```toml
[workspace]
members = ["packages/*", "contracts/*", "interface"]
```

Inside this `interface` crate, we advise to integrate all your contracts 1 by 1 in separate files. Here is the structure of the `cw-plus` integration for reference:

```path
interface (interface collection)
├── Cargo.toml
└── src
    ├── cw1_subkeys.rs
    ├── cw1_whitelist.rs
    ├── cw20_base.rs
    ├── cw20_ics20.rs
    └── ..
```

When importing your crates to get the messages types, you can use the following command in the interface folder. Don't forget to activate the interface feature to be able to use the cw\_orch functionalities.

```shell
cargo add cw20-base --path ../contracts/cw20-base/ --features=interface
cargo add cw20 --path ../packages/cw20 --features=interface
```

### Integrating single contracts

Now that you workspace is setup, you can [integrate with single contracts](#single-contract-integration) using the above section

## More examples and scripts

You can find more example interactions on the `counter-contract` example directly in the `cw-orchestrator` repo:

* Some examples [showcase interacting with live chains](https://github.com/AbstractSDK/cw-orchestrator/blob/main/contracts/counter/examples/deploy.rs).
* Some other examples show [how to use the library for testing your contracts](https://github.com/AbstractSDK/cw-orchestrator/tree/main/contracts/counter/tests).

> **FINAL ADVICE**: Learn more and explorer our [full `cw-orch` documentation !](https://orchestrator.abstract.money)


# Query A Contract

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

## 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.

<pre class="language-sh"><code class="lang-sh">CONTRACT=juno1anh4pf98fe8uh64uuhaasqdmg89qe6kk5xsklxuvtjmu6rhpg53sj9uejj
junod q wasm contract-state smart $CONTRACT '{"abcde":{}}'

<strong># Error parsing into type 
</strong><strong>#    cw721_base::msg::QueryMsg&#x3C;cosmwasm_std::results::empty::Empty>
</strong>#    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`
</code></pre>

{% hint style="info" %}
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\
\
<https://github.com/CosmWasm/cw-nfts/blob/main/contracts/cw721-base/src/msg.rs>
{% endhint %}

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

```sh
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

```bash
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

```bash
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

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 <https://cosmos.directory/juno/nodes> 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 <https://github.com/cosmwasm/wasmd>.\
\
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\
<https://github.com/CosmWasm/wasmd/blob/main/proto/cosmwasm/wasm/v1/query.proto>\\

```protobuf
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}";
  }
  ...
```

{% hint style="info" %}
You must base64 encode the JSON payload for REST API Request. Just take your JSON payload and\
\
\- put it into <https://www.base64encode.org/>\
\- or use Mac / Linux built in command\
\
echo '{"all\_tokens":{}}' | base64\
\# eyJhbGxfdG9rZW5zIjp7fX0K
{% endhint %}

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.\
\
<https://api.juno.strange.love/cosmwasm/wasm/v1/contract/juno1anh4pf98fe8uh64uuhaasqdmg89qe6kk5xsklxuvtjmu6rhpg53sj9uejj/smart/eyJhbGxfdG9rZW5zIjp7fX0K>

```json
{
    "data": {
        "tokens": [
            "0",
            "1",
            "2",
            "3",
            "4",
            "5",
            "6",
            "7",
            "8"
        ]
    }
}
```

## Cosmology Smart Contract Query

Using [CosmWasm/ts-codegen](https://github.com/CosmWasm/ts-codegen), you can create an NPM module to make interactions and queries into dev-friendly Typescript classes to allow you to focus on shipping code.

Here are a few tutorials from cosmology:

* [ts-codegen overview for CosmWasm](https://cosmology.tech/learn/video/overview-of-cosmwasm-ts-codegen)
* [CosmWasm Contract to Typescript npm module](https://cosmology.tech/learn/video/turn-your-cosmwasm-smart-contracts-into-a-typescript-npm-module)
* [Configure CosmWasm ts-codegen in your Contracts repo](https://cosmology.tech/learn/video/configuring-cosmwasm-ts-codegen-to-create-sdks-for-your-smart-contracts)
* [Query a CosmWasm smart contract from ts-codegen](https://cosmology.tech/learn/video/how-to-query-cosmwasm-smart-contracts)
* [Enable React Query](https://cosmology.tech/learn/video/how-to-use-react-query-for-interacting-with-cosmwasm-smart-contracts)
* [Enable Recoil](https://cosmology.tech/learn/video/how-to-use-recoil-for-interacting-with-cosmwasm-smart-contracts)
* [Integrate Telescope with ts-codegen](https://cosmology.tech/learn/video/integrating-telescope-and-cosmwasm-ts-codegen)

## 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.


# Send Tokens to a Contract

## Command Line Interface

When you execute a message, a user can also pass through a flag which sends funds from their account to the contract to do logic. You can check if a user sends any funds in your contract's execute endpoint with the `info.funds` array of Coins sent by the user. These funds then get added to the contracts balance just like any other account. So it is up to you as the developer to ensure to save how many funds each user has sent via a BTreeMap or other object storage in state (if they can redeem funds back at a later time).

To send funds to a contract with some arbitrary endpoint, you use the `--amount` flag.

```sh
junod tx wasm execute CONTRACT '{"some_endpoint":{}}' --amount 1000000ujuno
```

{% hint style="info" %}
If the "some\_endpoint" execute errors on the contract, the funds will remain in the users account.
{% endhint %}

## Typescript

```typescript
import type {Coin} from "@cosmjs/stargate"
import { SigningStargateClient, StargateClient, type StdFee } from '@cosmjs/stargate';

import type { OfflineAminoSigner } from '@cosmjs/amino';
import type { OfflineDirectSigner } from '@cosmjs/proto-signing';

import { SigningCosmWasmClient } from '@cosmjs/cosmwasm-stargate';

let RPC = "https://rpc.juno.strange.love"

const get_wallet_for_chain = async (
    chain_id: string
): Promise<OfflineAminoSigner | OfflineDirectSigner> => {
	// open keplr
	const keplr = window as KeplrWindow;
	if (keplr === undefined) {			
		throw new Error('Keplr not found');
	}
	let signer = keplr.getOfflineSignerAuto;
	if (signer === undefined) {
		throw new Error('Keplr not found');
	}
	return signer(chain_id);
};

let wallet = await get_wallet_for_chain("juno-1");
let address = (await wallet.getAccounts())[0].address;

let from_client = await SigningCosmWasmClient.connectWithSigner(RPC, wallet, {
	prefix: "juno"
});

const msg = {"some_endpoint": {}}

let fee: StdFee = {
    amount: [{amount: "5000",denom: "ujuno"}],
    gas: "500000"
}

let send_amount: Coin = {
    amount: "100000",
    denom: "ujuno"
}

await from_client.execute(
	address,
	REVIEWS_CONTRACT_ADDRESS,
	msg,
	fee,
	"memo",
	send_amount,
).then((res) => {
    console.log(`Success @ height ${res.height}\n\nTxHash: ${res.transactionHash}`)
});
```

## ts-codegen

The cosmology toolkit has some useful typescript tools for interacting with your smart contracts. The repo can be found at <https://github.com/CosmWasm/ts-codegen>, with setup and query tutorials in [Query A Contract section of this documentation](/developer-guides/cosmwasm-contracts/query-a-contract#cosmology-smart-contract-query).

Here are some video tutorials:

* [How to Execute a cosmwasm smart contract](https://cosmology.tech/learn/video/how-to-execute-cosmwasm-smart-contract-messages)
* [Advanced execution with a cosmwasm message composer](https://cosmology.tech/learn/video/how-to-compose-messages-for-interacting-with-cosmwasm-smart-contracts)


# Miscellaneous

This section contains miscellaneous short form guides to better interact and explore the Juno network blockchain.


# Conversions

How to convert between different aspects of data for

## Token Denominations

In Cosmos, every denomination amount is formatted as an unsigned integer. With this, the chain does not have to deal with fractions. For an EVM chain this amount is typically `10**18` power, while Juno and other native Cosmos chains use the `10**6` power. This means if I want to send you 1 JUNO, I am actually sending 1,000,000 of the smaller token.\
\
You can figure out which power a token uses by its prefix character in the denomination. In the case of JUNO, the actual denomination is shown as `ujuno`. This u signals that it is using any amount times `10**6` to get the human readable amount.

{% hint style="info" %}
10JUNO = 10,000,000ujuno\
0.5 JUNO = 500,000ujuno\
0.00001 JUNO = 10ujuno\
\
This means the smallest amount anyone can send is 0.000001 JUNO
{% endhint %}

## Address Conversions

### Valoper -> Base

Convert the validator operator wallet to a standard base address

```typescript
// npm i @cosmjs/encoding
import {toBech32, fromBech32} from '@cosmjs/encoding'

let toPrefix = "juno"

let initial = "junovaloper196ax4vc0lwpxndu9dyhvca7jhxp70rmcqcnylw"
let converted = toBech32(toPrefix, fromBech32(initial).data)

console.log(converted)
// juno196ax4vc0lwpxndu9dyhvca7jhxp70rmcl99tyh
```

### Juno -> Other Chain

{% hint style="info" %}
You can only convert between the same cointype, so converting a JUNO (118) to EVM address such as Terra's 330 will not properly convert. This is not possible to do without their private key
{% endhint %}

#### Web UI

* <https://bech32.scrtlabs.com/>

#### Typescript

```typescript
// Typescript
// npm i @cosmjs/encoding
import {toBech32, fromBech32} from '@cosmjs/encoding'

let toPrefix = "cosmos"

let initial = "juno196ax4vc0lwpxndu9dyhvca7jhxp70rmcl99tyh"
let converted = toBech32(toPrefix, fromBech32(initial).data)

console.log(converted)
// cosmos196ax4vc0lwpxndu9dyhvca7jhxp70rmcfhxsrt
```

#### Python

```python
# pip install bech32 - https://pypi.org/project/bech32/
import bech32

address = "juno196ax4vc0lwpxndu9dyhvca7jhxp70rmcl99tyh"

def address_convert(address=address, prefix="cosmos"):
    _, data = bech32.bech32_decode(address)
    return bech32.bech32_encode(prefix, data)

converted_addr = address_convert(address, "cosmos")
print(converted_addr)
# cosmos196ax4vc0lwpxndu9dyhvca7jhxp70rmcfhxsrt
```

#### CLI

```sh
junod debug bech32-convert juno196ax4vc0lwpxndu9dyhvca7jhxp70rmcl99tyh -p cosmos
# cosmos196ax4vc0lwpxndu9dyhvca7jhxp70rmcfhxsrt
```

### Hex -> Valcons

```typescript
// npm i @cosmjs/encoding
import {fromHex, toBech32} from '@cosmjs/encoding'

// where junovalcons is the wallet prefix for the chain + valcons
const prefix = "junovalcons"

let addr = toBech32(prefix, fromHex("1470B9237056641663CB4DFDEC86B064578B29BF"))
console.log(addr)

// This outputs junovalcons1z3ctjgms2ejpvc7tfh77ep4sv3tck2dl30r3mx 
// which matches their page
// https://ping.pub/juno/staking/junovaloper196ax4vc0lwpxndu9dyhvca7jhxp70rmcqcnylw
```

With this, you can now make a mapping between a junovaloper and signing junovalcons address

### Hex -> Bech32

Convert juno address between `hex` and `bech32` format.

```
junod debug addr [address] [flags]
```

{% hint style="info" %}
**TIP**

The command will accept either `hex` or `bech32` coded address as the `[address]` argument. The command will return the same output for either.
{% endhint %}

{% hint style="info" %}
**TIP**

Your `bech32` encoded juno local addresses can be queried with `junod keys list`
{% endhint %}

Example usage:

```sh
# query bech32 encoded address
junod debug addr juno1ludczrvlw36fkur9vy49lx4vjqhppn30h42ufg

# query hex address
junod debug addr FF1B810D9F74749B7065612A5F9AAC902E10CE2F
```

Returns:

```
Address: [255 27 129 13 159 116 116 155 112 101 97 42 95 154 172 144 46 16 206 47]
Address (hex): FF1B810D9F74749B7065612A5F9AAC902E10CE2F
Bech32 Acc: juno1ludczrvlw36fkur9vy49lx4vjqhppn30h42ufg
Bech32 Val: junovaloper1ludczrvlw36fkur9vy49lx4vjqhppn30ggunj3
```

### Raw Bytes -> Hex

Convert raw bytes output (eg. \[10 21 13 127]) to `hex`.

```
junod debug raw-bytes <raw-bytes>
```

Example command:

```
junod debug raw-bytes "10 21 13 127"
```

Returns:

```
0A150D7F
```

### Public Key -> Valcons

Convert a validators public key to the validator consensus tendermint address

{% hint style="info" %}

```
You can get the Public Key from the REST/LCD endpoint:
    cosmos/staking/v1beta1/validators

https://api.juno.strange.love/cosmos/staking/v1beta1/validators
&
https://.../cosmos/staking/v1beta1/validators/<junovaloper...>
```

{% endhint %}

```typescript
// npm i @cosmjs/encoding
import {fromBase64, toBech32} from '@cosmjs/encoding'
// npm i @cosmjs/crypto
import { sha256 } from '@cosmjs/crypto'

let prefix = "junovalcons"

// Chain Format: 
// {
//    "@type":"/cosmos.crypto.ed25519.PubKey",
//    "key":"/O7BtNW0pafwfvomgR4ZnfldwPXiFfJs9mHg3gwfv5Q="
// }

// we just need the .key string from the object
let pubKey = "/O7BtNW0pafwfvomgR4ZnfldwPXiFfJs9mHg3gwfv5Q="
const addr = toBech32(prefix, sha256(fromBase64(pubKey)).slice(0, 20))

console.log(addr)
// junovalcons1z3ctjgms2ejpvc7tfh77ep4sv3tck2dl30r3mx
```

### PubKey -> Hex, Base64, or Bech32

Decode a ED25519 pubkey from `hex`, `base64`, or `bech32`.

```
junod debug pubkey [pubkey] [flags]
```

{% hint style="info" %}
**TIP**

The command will accept `hex`, `base64` or `bech32` coded keys as `[pubkey]` argument. The command will return the same output for any of these inputs.
{% endhint %}

{% hint style="info" %}
**TIP**

Your `bech32` encoded validator pubkey can be queried with `junod tendermint show-validator`
{% endhint %}

Example usage:

```
# query hex address
junod debug pubkey F2AF5F796A1626C8BB51535E361F2E4B66A61B9AAD177B83452E0FCD5A14690DE

# query base64 encoded address
junod debug pubkey 8q9feWoWJsi7UVNeNh8uS2amG5qtF3uDRS4PzVoUaQ0=

# query base32 encoded address
junod debug pubkey junopub1zcjduepq72h477t2zcnv3w632d0rv8ewfdn2vxu645thhq699c8u6ks5dyxs7f2qt6Returns something similar to:
```

Returns:

```
Address: A50DF747BBF892E0FB0BCBAE6C3E2A5AE4A17D5A
Hex: F2AF5F796A1626C8BB51535E361F2E4B66A61B9AAD177B83452E0FCD5A14690D
JSON (base64): {"type":"tendermint/PubKeyEd25519","value":"8q9feWoWJsi7UVNeNh8uS2amG5qtF3uDRS4PzVoUaQ0="}
Bech32 Acc: junopub1zcjduepq72h477t2zcnv3w632d0rv8ewfdn2vxu645thhq699c8u6ks5dyxs7f2qt6
Bech32 Validator Operator: junovaloperpub1zcjduepq72h477t2zcnv3w632d0rv8ewfdn2vxu645thhq699c8u6ks5dyxssaf8x6
Bech32 Validator Consensus: junovalconspub1zcjduepq72h477t2zcnv3w632d0rv8ewfdn2vxu645thhq699c8u6ks5dyxsahwpfj
```


# Multi Message Transaction

Understand how to perform multiple actions at the same time in a single block.

## Transactions Vs Messages

A message is a unit of data that represents a single action or intent to perform an action, such as sending tokens from one account to another, creating a new validator, or executing a smart contract function. Messages are the basic building blocks of transactions and are used to describe the specific action that is being requested. (You can think of these as "sub transactions or commits" bundled up into 1 master transaction push).

A transaction, on the other hand, is a collection of one or more messages that are grouped together and signed by a single account. When a transaction is broadcast to the network, it is validated by the nodes on the blockchain, and if it is deemed valid, the requested actions specified in the messages are executed. Transactions provide a way to ensure that multiple actions can be performed atomically, meaning that either all of the actions are executed successfully or none of them are.

One transaction per block, with a transaction being multiple messages.

## Transaction Limitation / Account Sequence

By default, you can only submit 1 transaction per block. In doing this, it will increase your wallets account sequence by one. If you try to submit multiple transactions in the same block, it will error with a account sequence mismatch error. This means there is a pending transaction for your account already in the on chain pending pool (mempool of transactions). Once this transaction goes through and all messages are successfully executed, you can submit another transaction in the following block.

## Multi Message Transaction (bank)

To generate a multiple message transaction, you will need to slight scripting knowledge to assist for your needs. This works for any module in Juno, and you can add as many different messages to the same transaction within the gas limit. (Gas is a deterministic number describing the amount of computer a given action takes on a node).

First, you need to generate a default single message transaction from the command line. Ensure that the from address is an address you have the key access too.

{% hint style="info" %}
NOTE: ujunox is used on the uni-6 chain-id, while ujuno is used on the mainnet juno1 chain-id.\
\
You can find uni-6 testnet nodes on <https://testnet.cosmos.directory/junotestnet/nodes>
{% endhint %}

```sh
junod tx bank send juno16g2r... juno1t8e... 1000000ujunox \
    --generate-only --fees=5000ujunox \
    --chain-id=uni-6 --node=https://rpc.uni.junonetwork.io:443 [flags] > bankmsgs.json
```

```json
{
  "body": {
    "messages": [
      {
        "@type": "/cosmos.bank.v1beta1.MsgSend",
        "from_address": "juno16g2rahf5846rxzp3fwlswy08fz8ccuwk03k57y",
        "to_address": "juno1t8ehvswxjfn3ejzkjtntcyrqwvmvuknzy3ajxy",
        "amount": [
          {
            "denom": "ujuno",
            "amount": "1000000"
          }
        ]
      }
    ],
    "memo": "",
    "timeout_height": "0",
    "extension_options": [],
    "non_critical_extension_options": []
  },
  "auth_info": {
    "signer_infos": [],
    "fee": {
      "amount": [
          {
              "denom": "ujunox",
              "amount": "5000"
          }
      ],
      "gas_limit": "200000",
      "payer": "",
      "granter": ""
    }
  },
  "signatures": []
}
```

Here we are interested in the body -> messages section. In this array, we can put any amount of actions (within the gas limitation) for this transaction to execute with a single execute. So if I wanted to send another amount to a different address at the same time as well, we can manually alter the array of messages to add this new message like so

```json
{
  "body": {
    "messages": [
      {
        "@type": "/cosmos.bank.v1beta1.MsgSend",
        "from_address": "juno16g2rahf5846rxzp3fwlswy08fz8ccuwk03k57y",
        "to_address": "juno1t8ehvswxjfn3ejzkjtntcyrqwvmvuknzy3ajxy",
        "amount": [
          {
            "denom": "ujuno",
            "amount": "1000000"
          }
        ]
      },
      {
        "@type": "/cosmos.bank.v1beta1.MsgSend",
        "from_address": "juno16g2rahf5846rxzp3fwlswy08fz8ccuwk03k57y",
        "to_address": "juno1ka8v934kgrw6679fs9cuu0kesyl0ljjy4tmycx",
        "amount": [
          {
            "denom": "ujuno",
            "amount": "5000000"
          }
        ]
      }
    ],
    "memo": "",
    "timeout_height": "0",
    "extension_options": [],
    "non_critical_extension_options": []
  },
  "auth_info": {
    "signer_infos": [],
    "fee": {
      "amount": [
          {
              "denom": "ujunox",
              "amount": "5000"
          }
      ],
      "gas_limit": "200000",
      "payer": "",
      "granter": ""
    }
  },
  "signatures": []
}
```

In this case, we send 5JUNO to juno1ka... as well as the original account, at the same time. (Reminder: ujuno is a 6th exponent representation of human readable form). So in the above messages, we in total send 6JUNO.

**NOTE**: If our account only has less than 6JUNO, the entire above transaction would fail (non 0 return code) for not enough balance. Even through the first message is only 1JUNO, all messages in a transaction do not execute unless they are all successful. This is a safety mechanism!

Then we can sign and broadcast it

```bash
# Sign the message from the account who is sending the tokens
# This creates a new file which adds a signature to the signatures array
junod tx sign bankmsgs.json \
    --chain-id=uni-6 --from KEY [flags]
    

# take the output from here and paste it into a file named
# signed_bankmsgs.json. 
# You can also try doing &> signed_bankmsgs.json or > signed_bankmsgs.json
touch signed_bankmsgs.json # create the file


# Broadcast the message to the chain after it is successfully signed
junod tx broadcast signed_bankmsgs.json \
    --from KEY --chain-id=uni-6 [flags]

# Query to ensure it went through well (enough gas and fees)
junod q tx 12A4D888F6737130CE03CEC6BBAFD98855462E81D5AF871949E1EDE1B0B1A14B --node https://rpc.uni.junonetwork.io:443
```

## Multi Message NFT Mint (CosmWasm)

After reading the above guide, the same steps can be applied to mint cosmwasm based NFTs (CW721s). This requires you to submit an NFT contract to chain first, and setup with your collections values before moving on to this step. We will link to that guide HERE in the future.

```sh
# generate the initial Transaction structure
junod tx wasm execute juno1za0uemnhzwkjrqwguy34w45mqdlzfm9hl4s5gp5jtc0e4xvkrwjs6s2rt4 \
    '{"mint":{"token_id":"1","owner":"juno16g2rahf5846rxzp3fwlswy08fz8ccuwk03k57y","token_uri":"https://domain.com/image1.png"}}' \
    --output json --chain-id=uni-6 --yes --generate-only --from juno16g2rahf5846rxzp3fwlswy08fz8ccuwk03k57y > nft_multi_msg.json
```

```json
{
  "body": {
    "messages": [
      {
        "@type": "/cosmwasm.wasm.v1.MsgExecuteContract",
        "sender": "juno16g2rahf5846rxzp3fwlswy08fz8ccuwk03k57y",
        "contract": "juno1za0uemnhzwkjrqwguy34w45mqdlzfm9hl4s5gp5jtc0e4xvkrwjs6s2rt4",
        "msg": {
          "mint": {
            "token_id": "1",
            "owner": "juno16g2rahf5846rxzp3fwlswy08fz8ccuwk03k57y",
            "token_uri": "https://domain.com/image1.png"
          }
        },
        "funds": []
      }
    ],
    "memo": "",
    "timeout_height": "0",
    "extension_options": [],
    "non_critical_extension_options": []
  },
  "auth_info": {
    "signer_infos": [],
    "fee": {
      "amount": [
             {
              "denom": "ujunox",
              "amount": "5000"
          }
      ],
      "gas_limit": "200000",
      "payer": "",
      "granter": ""
    }
  },
  "signatures": []
}

```

Once again we are interested in the body -> messages section. In this array, we can put any amount of actions (within the gas limitation) for this transaction to execute with a single execute. So if I wanted to mint another within the same tx we can do the following manually.

```json
{
  "body": {
    "messages": [
      {
        "@type": "/cosmwasm.wasm.v1.MsgExecuteContract",
        "sender": "juno16g2rahf5846rxzp3fwlswy08fz8ccuwk03k57y",
        "contract": "juno1za0uemnhzwkjrqwguy34w45mqdlzfm9hl4s5gp5jtc0e4xvkrwjs6s2rt4",
        "msg": {
            "mint": {
                "token_id": "1",
                "owner": "juno16g2rahf5846rxzp3fwlswy08fz8ccuwk03k57y",
                "token_uri": "https://domain.com/image1.png"
            }
        },
        "funds": []
      },
      {
        "@type": "/cosmwasm.wasm.v1.MsgExecuteContract",
        "sender": "juno16g2rahf5846rxzp3fwlswy08fz8ccuwk03k57y",
        "contract": "juno1za0uemnhzwkjrqwguy34w45mqdlzfm9hl4s5gp5jtc0e4xvkrwjs6s2rt4",
        "msg": {
            "mint": {
                "token_id": "2",
                "owner": "juno16g2rahf5846rxzp3fwlswy08fz8ccuwk03k57y",
                "token_uri": "https://domain.com/image2.png"
            }
        },
        "funds": []
      }
    ],
    "memo": "",
    "timeout_height": "0",
    "extension_options": [],
    "non_critical_extension_options": []
  },
  "auth_info": {
    "signer_infos": [],
    "fee": {
      "amount": [
          {
              "denom": "ujunox",
              "amount": "5000"
          }
      ],
      "gas_limit": "200000",
      "payer": "",
      "granter": ""
    }
  },
  "signatures": []
}
```

```bash
# Sign the message from the account who is minting the NFT
# This creates a new file which adds a signature to the signatures array
junod tx sign nft_multi_msg.json \
    --chain-id=uni-6 --from KEY --fees=5000ujunox [flags]
    

# take the output from here and paste it into a file named
# signed_nft_multi_msg.json. 
# You can also try doing &> signed_mft_multi_msg.json or > signed_nft_multi_msg.json
touch signed_nft_multi_msg.json # create the file


# Broadcast the message to the chain after it is successfully signed
junod tx broadcast signed_nft_multi_msg.json \
    --from KEY --chain-id=uni-6 [flags]

# Query to ensure it went through well (enough gas and fees)
junod q tx <TX HASH> --node https://rpc.uni.junonetwork.io:443
```

## Automate Minting Example

Here is a python example for how to automate minting NFTs for a contract based off some parameters. This is only the base logic to get you started in the right direction

```python
import json, os

# VARIABLES
START_IDX = 1
NFT_CW721_ADDRESS = "juno1za0uemnhzwkjrqwguy34w45mqdlzfm9hl4s5gp5jtc0e4xvkrwjs6s2rt4"
OWNER_WALLET = "juno16g2rahf5846rxzp3fwlswy08fz8ccuwk03k57y"
links = [
    "https://ipfs.io/ipfs/QmNLoezbXkk37m1DX5iYADRwpqvZ3yfu5UjMG6sndu1AaQ",
    "https://ipfs.io/ipfs/QmNLjZSFV3GUMcusj8keEqVtToEE3ceTSguNom7e4S6pbJ",
    "https://ipfs.io/ipfs/QmNLijobERK4VhSDZdKjt5SrezdRM6k813qcSHd68f3Mqg",
]

current_dir = os.path.dirname(os.path.abspath(__file__))

# LOGIC
msgFmt: dict = {
    "body": {
        "messages": [],
        "memo": f"Minting {len(links)} NFTs",
        "timeout_height": "0",
        "extension_options": [],
        "non_critical_extension_options": [],
    },
    "auth_info": {
        "signer_infos": [],
        "fee": {"amount": [], "gas_limit": "10000000", "payer": "", "granter": ""},
        "tip": None,
    },
    "signatures": [],
}

for idx, link in enumerate(links, START_IDX):
    msgFmt["body"]["messages"].append(
        {
            "@type": "/cosmwasm.wasm.v1.MsgExecuteContract",
            # The wallet who has permission to mint on the CW721 contract
            "sender": f"{OWNER_WALLET}",
            "contract": f"{NFT_CW721_ADDRESS}",
            "msg": {
                "mint": {
                    # Token ID Should be a number starting at 1 and incrementing
                    "token_id": f"{idx}",
                    # Who owns this NFT originally at the time of mint.
                    "owner": f"{OWNER_WALLET}",
                    # the link to the image itself (IPFS, etc.)
                    "token_uri": f"{link}",
                }
            },
            "funds": [],
        }
    )

with open(os.path.join(current_dir, "mint_nfts.json"), "w") as f:
    json.dump(msgFmt, f, indent=4)
```

This saves a file named `mint_nfts.json` to the directory this script is saved in. From here you can do the following to execute it on chain

```sh
# Sign the message from the account who is minting
junod tx sign mint_nfts.json \
    --chain-id=uni-6 --from KEY [flags] &> signed_mint_images.json

# Broadcast the message to the chain after it is successfully signed
junod tx broadcast signed_mint_images.json \
    --from KEY --chain-id=uni-6 [flags]
```


# Get & Decode Transactions

## Get Transactions

You can get a blocks transactions both via the RPC and REST API. You can find other public endpoints on the <https://cosmos.directory/juno/nodes> website

### Get with RPC:

URL: <https://rpc.juno.strange.love/block>\
Transaction Array: result.block.data.txs\[]

### Get with REST API:

URL: <https://api.juno.strange.love/cosmos/base/tendermint/v1beta1/blocks/latest>\
Transaction Array: block.data.txs\[]

### Get with CLI:

```sh
# apt install jq     |  pacman -S jq
junod q block | jq .block.data.txs
```

## Decode: Command Line

You can decode transaction data using the `junod` command:

```sh
junod tx decode <base64-amino-byte-string> --output=json
```

For example

```sh
junod tx decode CoMECvwBCiQvY29zbXdhc20ud2FzbS52MS5Nc2dFeGVjdXRlQ29udHJhY3QS0wEKK2p1bm8xaHRzOGdnMHdudXhxazl4ZXJ1a3djNHB4ZG1ncmdoZG5qdjhnZGcSP2p1bm8xZzVqOXZkNzZjcXQ3ZnNxMjJuZTdqcWZrejR2OXB0a3ZoNGprbnN2d2NocGo3NTNhdHdmczk0MmEyNRpOeyJzd2FwIjp7ImlucHV0X3Rva2VuIjoiVG9rZW4yIiwiaW5wdXRfYW1vdW50IjoiNDUyOTAwMDAwMCIsIm1pbl9vdXRwdXQiOiIwIn19KhMKBXVqdW5vEgo0NTI5MDAwMDAwCoECCiQvY29zbXdhc20ud2FzbS52MS5Nc2dFeGVjdXRlQ29udHJhY3QS2AEKK2p1bm8xaHRzOGdnMHdudXhxazl4ZXJ1a3djNHB4ZG1ncmdoZG5qdjhnZGcSP2p1bm8xZThuNmNoN21za3M0ODdlY3pueWVhZ216ZDVtbDJwcTl0Z2VkcXQydTYzdnJhMHEwcjltcXJqeTZ5cxpUeyJzd2FwIjp7ImlucHV0X3Rva2VuIjoiVG9rZW4xIiwiaW5wdXRfYW1vdW50IjoiNDUyOTAwMDAwMCIsIm1pbl9vdXRwdXQiOiI2MDAwMDAwIn19KhIKBXVqdW5vEgk5NjkwMDAwMDASZgpQCkYKHy9jb3Ntb3MuY3J5cHRvLnNlY3AyNTZrMS5QdWJLZXkSIwohA2IKqvhI5iJwjhzNfy90VKT/UKcn7hQtmJD2WtPxiIY5EgQKAggBGEsSEgoMCgV1anVubxIDNjAwEMOaDBpAh+kKHSm07sTOYe8K/m7GhSGgmciMjGPD7eTLtLHX2x1Rp5e0m+cHK2rFB9f9ZNRITrf0L7E/emsOKjdFkUFbnA== --output json
```

returns

```json
{
   "body":{
      "messages":[
         {
            "@type":"/cosmwasm.wasm.v1.MsgExecuteContract",
            "sender":"juno1hts8gg0wnuxqk9xerukwc4pxdmgrghdnjv8gdg",
            "contract":"juno1g5j9vd76cqt7fsq22ne7jqfkz4v9ptkvh4jknsvwchpj753atwfs942a25",
            "msg":{
               "swap":{
                  "input_token":"Token2",
                  "input_amount":"4529000000",
                  "min_output":"0"
               }
            },
            "funds":[
               {
                  "denom":"ujuno",
                  "amount":"4529000000"
               }
            ]
         },
         {
            "@type":"/cosmwasm.wasm.v1.MsgExecuteContract",
            "sender":"juno1hts8gg0wnuxqk9xerukwc4pxdmgrghdnjv8gdg",
            "contract":"juno1e8n6ch7msks487ecznyeagmzd5ml2pq9tgedqt2u63vra0q0r9mqrjy6ys",
            "msg":{
               "swap":{
                  "input_token":"Token1",
                  "input_amount":"4529000000",
                  "min_output":"6000000"
               }
            },
            "funds":[
               {
                  "denom":"ujuno",
                  "amount":"969000000"
               }
            ]
         }
      ],
      "memo":"",
      "timeout_height":"0",
      "extension_options":[
         
      ],
      "non_critical_extension_options":[
         
      ]
   },
   "auth_info":{
      "signer_infos":[
         {
            "public_key":{
               "@type":"/cosmos.crypto.secp256k1.PubKey",
               "key":"A2IKqvhI5iJwjhzNfy90VKT/UKcn7hQtmJD2WtPxiIY5"
            },
            "mode_info":{
               "single":{
                  "mode":"SIGN_MODE_DIRECT"
               }
            },
            "sequence":"75"
         }
      ],
      "fee":{
         "amount":[
            {
               "denom":"ujuno",
               "amount":"600"
            }
         ],
         "gas_limit":"200003",
         "payer":"",
         "granter":""
      }
   },
   "signatures":[
      "h+kKHSm07sTOYe8K/m7GhSGgmciMjGPD7eTLtLHX2x1Rp5e0m+cHK2rFB9f9ZNRITrf0L7E/emsOKjdFkUFbnA=="
   ]
}
```

## Decode with Python (junod)

Using junod and python, we can save this JSON data for later using the following example.\
This excerpt was taken from the [juno-analysis repo](https://github.com/Reecepbcups/juno-analysis/blob/main/main.py)

```python
# python3 -m pip install httpx
import httpx, json, os

RPC_URL = "https://rpc.juno.strange.love:443"
height = 7_000_000

client = httpx.Client()
tx_data: dict[int, dict] = {}

def run_cmd(cmd) -> str:
    return os.popen(cmd).read()


def get_block_transactions(height: int) -> list[str]:
    block = client.get(f"{RPC_URL}/block?height={height}").json()
    block_txs = block["result"]["block"]["data"]["txs"]
    return block_txs


def main():
    version = run_cmd("junod version")
    if len(version) == 0:
        print("Junod not installed. Please install junod and try again.")
        exit(1)

    txs = get_block_transactions(height=height)

    for tx in txs:
        txs_json = json.loads(run_cmd(f"junod tx decode {tx} --output json"))
        tx_data[height] = txs_json.get("body", {}).get("messages", [])

    # Do something with that tx data here
    print(tx_data)

if __name__ == "__main__":
    main()
```

## Decode with Python (protobuf)

If you have experience with protobuf, you can use cosmospy to decode transaction data and decode is from base64 strings

```python
# python -m pip install cosmospy-protobuf
import base64
import cosmospy_protobuf.cosmos.tx.v1beta1.tx_pb2 as tx_pb2

tx = "CpMBCpABChwvY29zbW9zLmJhbmsudjFiZXRhMS5Nc2dTZW5kEnAKLWNvc21vczEweGw5cXV1Z2N2amhsMGdsamplaG1oeHhhN3cwaDM5ZTJ2aGFndhItY29zbW9zMThsemp0NWpwcjdtd3U0dHlkbGNmZ2N1dHI2Z25ycGsweWo4ZnNjGhAKBXVhdG9tEgcxMDAwMDAwEmcKUApGCh8vY29zbW9zLmNyeXB0by5zZWNwMjU2azEuUHViS2V5EiMKIQM+g5XXnqLLelLxz8CTy+vG5aO7SohNKS78OtL9ysdcEhIECgIIARgCEhMKDQoFdWF0b20SBDIyNzUQ+MYFGkBbTDHP0mn8d2hxQnNUE/SeudBrXMgjyRO5Bv12D4iWgk4cPsczc6EaDQD3v7cqqD22HL8ZZXVMF3GKi1SNAGNT"
decode64 = base64.b64decode(tx)
tx = tx_pb2.Tx()
tx.ParseFromString(decode64)

print(tx)
# print(tx.body.messages)
```


# Get Token Prices

Get the price of a token from a variety of sources

In your webapp, you may want to show the current price of a token in the ecosystem or other ecosystems. Here are a few ways to get these prices to display. These should **NOT** be used for logic. If you wish to use token prices for logic, you will need to use an Oracle from multiple sources.

## Coingecko

Coingecko is the most popular source for Crypto price feeds. It is free to use, and allows 1 query per 6 seconds by default. This should only be used for decoration, and no logic should be built off of it.

### Python

```python
# https://pypi.org/project/pycoingecko/
# pip install pycoingecko
from pycoingecko import CoinGeckoAPI

ids = "juno-network,bitcoin"
currencies = "usd,eur"

def main():
    cg = Coingecko()
    print(cg.pretty_prices())

class Coingecko:
    # https://www.coingecko.com/en/api/documentation
    def __init__(self):
        api_key = ""
        if len(api_key) > 0:
            self.cg = CoinGeckoAPI(api_key=api_key)
        else:
            self.cg = CoinGeckoAPI()

    def __get_symbols(self):
        values = {}
        for _id in ids.split(","):
            data = self.cg.get_coin_by_id(_id)
            symbol = data.get("symbol", "")
            values[_id] = symbol
        return values

    def get_prices(self) -> dict:
        return self.cg.get_price(ids=ids, vs_currencies=currencies)

    def pretty_prices(self):
        updated_coins = {}
        symbols = self.__get_symbols()
        for k, v in self.get_prices().items():
            symbol = str(symbols.get(k, k)).upper()
            updated_coins[symbol] = {"coingecko-id": k, "prices": v}
        return updated_coins


if __name__ == "__main__":
    main()
```

```json
{
    'BTC': {
        'coingecko-id': 'bitcoin', 
        'prices': {'usd': 23270, 'eur': 21999}}, 
    'JUNO': {
        'coingecko-id': 'juno-network', 
        'prices': {'usd': 1.13, 'eur': 1.068}
    }
}
```

### Typescript

{% hint style="info" %}
Example Typescript price Querier program\
<https://github.com/Reecepbcups/wasm-oracle/tree/main/data-feeders-examples/crypto-prices>
{% endhint %}

```typescript
// npm i coingecko-api-v3
import { CoinGeckoClient } from 'coingecko-api-v3';

export interface Data {
    id: string;
    value: number;
}
export interface Provider {
    name: string;
    getPrices(): Promise<Data[]>;    
    isEnabled(): boolean;
}

const REQUESTED_SYMBOLS = {"juno-network":"JUNO","bitcoin":"BTC"}

export class CoinGeckoProvider implements Provider {
    name: string;
    coingecko: CoinGeckoClient;

    constructor() {
        this.name = "CoinGecko";
        this.coingecko = new CoinGeckoClient({
            timeout: 10000,
            autoRetry: true,
        });
    }

    isEnabled(): boolean {
        return true;
    }

    async getPrices(): Promise<Data[]> {
        const ids = Object.keys(REQUESTED_SYMBOLS).join(',');

        const v = await this.coingecko.simplePrice({ vs_currencies: 'usd', ids });

        let data_arr: Data[] = []
        for (const key of Object.keys(v)) {
            let value = Number(v[key].usd);

            // if key not in COINGECKO_DENOM_MAP, then use key as id
            let id = key;
            if (key in REQUESTED_SYMBOLS) {
                id = REQUESTED_SYMBOLS[key];
            }                    

            data_arr.push({
                id,
                value
            });
        }

        return data_arr;
    }
}

```

## Wynd Dex (Juno)

{% embed url="<https://api.wynddao.com/assets/prices>" %}

## Osmosis Dex

{% embed url="<https://api-osmosis.imperator.co/tokens/v2/juno>" %}


# Get Account Transactions

Query an accounts past transactions

{% hint style="info" %}
Most cosmos nodes will only hold 30 days worth of data. If you need more, you will have to run your own node with > 1TB of storage, or talk with node providers to pay for a private service.
{% endhint %}

Here is the rest endpoint which queries transactions from a given user. It is URL Encoded so single quotes become %27\
<https://api-juno.pupmos.network/cosmos/tx/v1beta1/txs?events=transfer.recipient=%27juno12fzv0wrkllkzkwfv9tch07s3gj9ajhyesersy4%27>

### Other Event Types

Other event types can be found in the tendermint 34 documentation <https://docs.tendermint.com/v0.34/rpc/> such as `tm.event='NewBlock'` if you subscribe via the websocket.


# IBC Transfer

How to transfer tokens from networks in Cosmos

One of the highlighted features of CosmosSDK chains is the ability to transfer tokens permissionless to other chains in the network. This is also possible with Juno to and from other chains.\
\
If you are just looking for a simple frontend to transfer tokens, [Osmosis](https://app.osmosis.zone/) and [Wynd Dex](https://app.wynddao.com/) frontends both have deposit and withdraw UIs to do this. If you need to transfer tokens between Juno and another chain that does not have a frontend, or is new, you can use [ibc-anywhere](https://ibc.reece.sh/) to seamlessly transfer between networks.

## Typescript

If you wish to make a IBC transfer between chains, you will need to leverage cosmos directory & [Cosmology's stack in your webapp](https://github.com/cosmology-tech/cosmos-kit).

* [CosmJS sendIBCTokens Docs](https://cosmos.github.io/cosmjs/latest/stargate/classes/SigningStargateClient.html#sendIbcTokens)
* [Example in Action from ibc-anywhere-webapp](https://github.com/Reecepbcups/ibc-anywhere-webapp/blob/main/src/routes/%2Bpage.svelte#L290)

```typescript
// Pseudo Code Example of the Flow
import { assets, chains, ibc } from 'chain-registry';
import { Tendermint34Client } from '@cosmjs/tendermint-rpc';
import { setupIbcExtension, QueryClient } from '@cosmjs/stargate';
import type {IbcExtension} from '@cosmjs/stargate/build/modules/ibc/queries';

const JUNO_RPC = "https://rpc.juno.strange.love"

const get_wallet_for_chain = async (
    chain_id: string
): Promise<OfflineAminoSigner | OfflineDirectSigner> => {
    // open keplr
    const keplr = window as KeplrWindow;
    if (keplr === undefined) {
        toast.error(`Keplr not found`, toast_style);
        throw new Error('Keplr not found');
    }
    // ledger support
    let signer = keplr.getOfflineSignerAuto;
    if (signer === undefined) {
        throw new Error('Keplr not found');
    }
    return signer(chain_id);
};


const tm_client = await Tendermint34Client.connect(JUNO_RPC);
let temp = QueryClient.withExtensions(tm_client);
let query_client: IbcExtension = setupIbcExtension(temp);

let from_wallet = await get_wallet_for_chain("juno-1");
let to_wallet = await get_wallet_for_chain("osmosis-1");

let from_client: SigningStargateClient | undefined;
from_client = await SigningStargateClient.connectWithSigner(
    JUNO_RPC, 
    from_wallet,
    {prefix: "juno"}
);

const addr = (await wallet.getAccounts())[0].address;

const from_addr = (await from_wallet.getAccounts())[0].address;
const to_addr = (await to_wallet.getAccounts())[0].address;

const channel_id = 0 // JUNO->OSMOSIS is channel 0
const timeout_time = current_time + 300; // 5 minutes
const gas = 300000;

from_client
    .sendIbcTokens(
        from_addr,
        to_addr,
        { denom: "ujuno", amount: "1000000" },
        'transfer',
        channel_id,
        undefined,
        timeout_time,
        { amount: [], gas: gas.toString() },
        `memo: IBC Transfer of 1000000 ujuno to osmosis chain`
    )
    .then((tx) => {
        console.log(tx);
        if (tx.code == 0) {
            alert(
                `IBC transfer from ${chain.pretty_name} successful\n\nTxHash: ${tx.transactionHash}`
            )
        }				
    })
```


# State Export / Airdrop

Getting all balances with some token held. Useful for airdrops.

{% hint style="info" %}
This guide will require you to understand some basic scripting through JSON files to calculate the logic you want for tokens in the format you wish. If you need a website version of this, you can use <https://juno.tools/airdrops/>
{% endhint %}

## Native (JUNO) Export

To airdrop, you will need a state export file. These come from a full node that is synced up to the network and stopped. These nodes typically only hold 30 days' worth of data, so ensure you take an export between now and 30 days ago. You can ensure your height is within this time by checking [Mintscan](https://hub.mintscan.io/).

Automatic exports can be found here for convenience <https://exports.reece.sh/juno/>. Downloading from here allows you to skip the rest of this guide.\
\
[For this guide, you will need to setup a node from this guide](/validators/joining-mainnet#junod-installation). You do not need a validator to do this. Once your node is running and at the latest block, do the following.

```sh
# stop the juno node from running then
cd ~/.juno/
junod export HEIGHT-HERE > juno_state_export.json
# Where HEIGHT-HERE is the block height you want, for example 7000000
```

{% hint style="info" %}
Some exports require > and others require 2>, this is due to an SDK bug that outputs it to STDERR. If you see it throwing out the text to your screen, try using the other ">" or "2>" operator. We want it to get formatted into the file.\
\
This can take upwards of 30 minutes to complete, so be patient.
{% endhint %}

Once the command exits, check your file size. It should be large. If it only shows 4KB, then you have not exported the state correctly due to an issue with height or version. This will have been output in the file itself, so follow the error to fix the reason it could not export correctly. You can check the file size like so

```
du -sh juno_state_export.json
```

Then check to ensure the file is valid and no extra logs got into your JSON. If the below fails, there is likely text at the top of your file that you need to remove from logs

```
cat juno_state_export.json | python -c "import sys,json;json.loads(sys.stdin.read());print 'OK'"
```

Once the above is complete, you are ready to follow the write scripts to parse, edit, and get the data into a format for your needs. You most likely need to stream the file in most languages due to the size. [Here is an example in python for streaming the sections](https://github.com/Reecepbcups/airdrop-tools/blob/main/export-sort/utils.py).

## CW20 Balances

This section will require you to run 2 scripts which gets all balances held at a select block on chain.\\

```sh
# script1.sh
CW20_CONTRACT="juno1hnftys64ectjfynm6qjk9my8jd3f6l9dq9utcd3dy8ehwrsx9q4q7n9uxt"
LIMIT="500"
REST_NODE="https://api.juno.strange.love:443"

# make dir CW20s if not already made
mkdir -p CW20s

# the block height we want to query at
HEIGHT=7131467

next_pag_key=""
urlencode() {
    # urlencode <string>
    old_lc_collate=$LC_COLLATE
    LC_COLLATE=C
    
    local length="${#1}"
    for (( i = 0; i < length; i++ )); do
        local c="${1:$i:1}"
        case $c in
            [a-zA-Z0-9.~_-]) printf '%s' "$c" ;;
            *) printf '%%%02X' "'$c" ;;
        esac
    done

    LC_COLLATE=$old_lc_collate
}

# Loop through until we dont have any more pages
while true; do
    # get a random UUID for this file to merge later
    UUID=$(uuidgen) && FILENAME="CW20s/cw20-$UUID.json"

    # check if next_pag_key is empty
    if [[ -z $next_pag_key ]]; then
        echo "no key = 1st run"        
        curl -X GET "$REST_NODE/cosmwasm/wasm/v1/contract/$CW20_CONTRACT/state?pagination.limit=$LIMIT" -H  "accept: application/json" -H "x-cosmos-block-height: $HEIGHT" > $FILENAME
    else
        echo "Running with page key: $next_pag_key"
        URL_CODE=$(urlencode $next_pag_key)        
        curl -X GET "$REST_NODE/cosmwasm/wasm/v1/contract/$CW20_CONTRACT/state?pagination.key=$URL_CODE&pagination.limit=$LIMIT" -H  "accept: application/json" -H "x-cosmos-block-height: $HEIGHT" > $FILENAME        
    fi

    # echo "Getting all keys from $FILENAME"
    next_pag_key=`jq -r '.pagination.next_key' $FILENAME`
    # if next_pag_key if null, then we are done
    if [[ $next_pag_key == "null" ]]; then
        echo "No more pages, Finished!"
        break
    fi
done

echo "Please run script2.py now to convert the CW20s folder files -> balances.json"
```

```python
# script2.py
import base64
import json
import os

current_dir = os.path.dirname(os.path.realpath(__file__))
CW20s = os.path.join(current_dir, "CW20s")
def hex_string_to_uft8(hex_string):
    return bytearray.fromhex(hex_string).decode()
def base64_to_uft8(base64_string):
    return base64.b64decode(base64_string).decode()


balances = {}
total_balances = 0
for file in os.listdir(CW20s):
    # read the file
    with open(os.path.join(CW20s, file), "r") as f:
        data = json.load(f)
        # get models key if found
        if "models" not in data:
            continue
        modules = list(data["models"])
        for m in modules:
            key = hex_string_to_uft8(m["key"])
            if "balance" not in key:
                break
            address = str(
                # you may have to edit the replace statement depending on the contract
                key.replace("balance", "").replace("\u0000\u0007", "")
            )  # balancejuno1000xz25ydz8h9rwgnv30l9p0x500dvj0s9yyc9 -> juno1000xz25ydz8h9rwgnv30l9p0x500dvj0s9yyc9

            balance = int(
                base64_to_uft8(m["value"]).replace('"', "")
            )
            if balance <= 0:
                continue

            balances[address] = balance
            total_balances += balance

# save balances to a file as JSON
with open(os.path.join(current_dir, "balances.json"), "w") as f:
    balances = {
        k: v for k, v in sorted(balances.items(), key=lambda x: x[1], reverse=True)
    }
    json.dump(balances, f, indent=2)
    print("Balances saved to balances.json. Total Value: {total_balances:.0f}")
```


# Juno Modules


# FeeShare

Juno's x/FeeShare module: Gas Fee Split for Contract Developers

## x/FeeShare

The FeeShare module was [proposed in prop 51](https://www.mintscan.io/juno/proposals/51). If you’re a smart contract developer on Juno, you can now earn a cut of all gas fees generated on your contract.

If a transaction interacts with a smart contract, half of the transaction’s fees are set aside for any contract(s) a wallet has interacted with. The first 50% goes to delegators as usual (community pool), with the other 50% being split among each opted-in contract. *This opt-in requirement is only for tax purposes, it is permission-less to do*. You can opt-in and set the withdrawal contract to any other wallet, for example, a personal wallet, a DAO treasury, or a module account.\
\
These fees are paid instantly to the withdraw wallet every block (6 seconds) as interactions take place.

{% hint style="info" %}
At this time, sub messages are not applicable to feesharing due to possible abuse. The team is working to find a solution to this use case for a future version of the module.
{% endhint %}

## Spec

You can view latest specification in the [Juno github](https://github.com/CosmosContracts/juno/tree/main/x/feeshare/spec). Here it describes how to register and update your contract. It also provides the details on queries, events, and different parameters which can be changed by Juno's governance system.

## Register A Contract

The `junod tx feeshare register` command allows you to register the withdrawal address for a contract. This means that any interaction fees generated by the contract will be sent to the specified address.

To use this command, you need to specify the following parameters:

* `contract_bech32`: The bech32 address of the contract whose interaction fees will be shared.
* `withdraw_bech32`: The bech32 address where the interaction fees will be sent every block.
* `--from [key]`: The name or address of the key to sign the transaction.

The withdraw\_bech32 parameter cannot be set to the community pool address because of an SDK limitation.\
\
Only the contract's admin can use this command. If there's no admin, only the creator can use it.

#### Register Contract Message JSON

{% hint style="info" %}
junod tx feeshare register \[contract] \[withdraw] --from \[your\_address] --generate-only
{% endhint %}

<pre class="language-json"><code class="lang-json"><strong>{
</strong>  "@type": "/juno.feeshare.v1.MsgRegisterFeeShare",
  "contract_address": "juno1d7yjapmwerm6qxaxtuyefmcns45x9x6d78gys9uhfsdpkfs4dxfssgw7ap",
  "deployer_address": "juno10r39fueph9fq7a6lgswu4zdsg8t3gxlq670lt0",
  "withdrawer_address": "juno1hj5fveer5cjtn4wd6wstzugjfdxzl0xps73ftl"
}
</code></pre>

### Registering Factory Contracts

For contracts **created or administered by a contract factory** *(contract instantiates contract)*, the withdrawal address can only be registered to itself (the instantiated child contract). This is useful for SubDAOs and public goods to save fees in the treasury / another wallet while still being owned by a contract. \\

This can be a little confusing so here is the flow

```
User -> Factory -> instantiates child contract
-> Register Child to FeeShare CLI command to itself 
-> In child contract, set an external address (via a contract manager saved in state)
-> Set a message to move funds from the child contract to external address OR manager

This requires you to set the withdraw address 
- via instantiate
- or with a contract manmager who can then set the withdraw address to some account
(If the manager is a DAO, this is the best outcome. else they can withdraw anywhere)

*Manager is some address you save in the contract Config or state. This is entirely
internal for permissioned actions on the contract logic.
```

Example:

* Factory instantiates Contract A, where the creator and admin is Factory
* Anyone can now `junod tx feeshare register contract-a contract-a`
* With this, all feeshare funds are saved in the contract-a balance
* To move these funds, your child contract needs a way to set a withdraw address. For example `ExecuteMsg::SetWithdrawAddress{address:juno123...}}` or do this on instantiate through the factory message payload. Just some other adderss we can withdraw the funds to
* The child contract then has `ExecuteMsg::GetFeeShare{}` which takes the contracts balance minus any funds which are meant to be in the contract (ex: proposal deposits), and sends those tokens to the `juno123...` address set earlier

## Update Contract Withdraw Address

The `junod tx feeshare update` command lets you update a contract's withdrawal address, so any interaction fees go to the new address. You must provide:

* `contract`: The address of the contract whose withdrawal address will be updated.
* `new_withdraw_address`: The new bech32 address where the interaction fees will be sent every block.

Only the contract's admin or creator can use this command. It cannot be used if the contract was created or administered by another factory contract (like a DAO), and contracts cannot change their own withdrawal address directly. If ownership changes, the new owner can update the withdrawal address.

#### Update Contract Message JSON

Where deployer\_address is the contract admin (or creator if there is no admin), and withdrawal is the address you want funds to go to.

{% hint style="info" %}
junod tx feeshare update \[contract] \[withdraw] --from \[your\_address] --generate-only
{% endhint %}

```json
{
  "@type": "/juno.feeshare.v1.MsgUpdateFeeShare",
  "contract_address": "contract",
  "deployer_address": "your_address",
  "withdrawer_address": "withdraw"
}
```

## Governance Action for FeeShare

Juno's FeeShare module lets governance control the distribution of transaction fees to developers of contracts. Key actions include:

1. Enable/Disable: Governance can turn the FeeShare module on/off, stopping fees from going to developers and preventing updates to contracts.
2. Set Developer Shares: Governance can set the percentage of fees that developers receive, encouraging contract creation and maintenance. The default is 50%.
3. Define Allowed Denominations: Governance can specify which coins are allowed for fees and paid to developers. Without any specifications, all fees are split among developers. Currently, only JUNO token is shared.

By managing fees, governance incentivizes developers to create and maintain high-quality contracts, increasing the network's value and attracting more users.


# TokenFactory

Your own native token on the JUNO chain! Better UI, UX, and Developer Experience

The Cosmos stack has a native x/bank module which allows for the minting and sending of tokens without having to follow the CW20 (from ERC20) spec.

#### CW20 Migrations & Contract Minting

If you already have a tokenfactory denomination made OR want to migrate your CW20 token, then you can [skip to this section here](#tokenfactory-core-contract) for the Core Middleware contract.

## Improvements

* Airdrops are many times easier for users holding DAO tokens from a state export, rather than slow paginated CW20 queries
* Frontends such as Keplr and Mintscan will be able to show off your tokens via a single query, rather than RPC querying every CW20 contract (inefficient!)
* Contract developers no longer have to add support for CW20 when all contracts already have native tokens support built in to work with Juno!
* CLI based users will be able to send any token via the standard *junod tx bank send* instead of wasm execute CW20 message passthroughs with base64 encoded data

## Create A Native Token Transaction

To get started, you will need to create a new denomination from the factory. At the time of writing (March 3, 2023) the cost to create a new token is 1 JUNO. This is to deter spamming of tokens. You can create this token like so:

```
junod tx tokenfactory create-denom [denom-name] [flags]
```

This will create a denomination you are the admin of which will follow the format `factory/juno1addresshere/denom1`. This ensures there are no namespace conflicts.

## What tokens do I control

You can view the tokens you control with the following:

```shellscript
junod q tokenfactory denoms-from-creator juno1address... [flags]
```

This command will return a list of all denominations created by the account with address

## Update Token Metadata

You can modify the token metadata to include a human readable ticker symbol, description, and the exponent of the token. We recommend setting these for your denomination before deploying out into production.

```shellscript
junod tx tokenfactory modify-metadata \
    factory/juno1/denom1 SYMBOL "https://description.com" 6 [flags]
```

Where `SYMBOL` is the Ticker symbol for your token. Usually this should be the all capitalized version after the last / in your factory. Example: If your token is `factory/juno1/ugold` your tokens symbol should likely be `GOLD` for it to show up as `$GOLD` in frontends such as Mintscan and Keplr.

The description is an area to link to your website, ipfs, discord, or any other data which is useful to describe what the token does.

Finally the exponent section is helpful for frontends to display your token as expected. Typically this will be `6` for most cosmos tokens. If you do not know what value to give it, stay with `6`. This means 1TOKEN in human readable form is actually 1x(10^6) tokens (1\_000\_000) to allow for fractional tokens. Without this, each token has no ability to handle fraction like values.

{% hint style="info" %}
If you are creating this token to be used as a GAMM, Liquidity Pool, or EVM compatible denomination, you should use\*\*`18`\*\*.
{% endhint %}

## Query Token Metadata

You can query the token metadata via the x/bank module query

```
junod query bank denom-metadata --denom [denom-name] --output=json [flags]
```

Where denom-name is the entire denomination value `factory/juno1.../denom`.

```json
{
  "metadatas": [
    {
      "description": "my description here https://domain.com",
      "denom_units": [
        {
          "denom": "factory/juno1hj5fveer5cjtn4wd6wstzugjfdxzl0xps73ftl/denom1",
          "exponent": 0,
          "aliases": [
            "SYMBOL"
          ]
        },
        {
          "denom": "SYMBOL",
          "exponent": 6,
          "aliases": [
            "factory/juno1hj5fveer5cjtn4wd6wstzugjfdxzl0xps73ftl/denom1"
          ]
        }
      ],
      "base": "factory/juno1hj5fveer5cjtn4wd6wstzugjfdxzl0xps73ftl/denom1",
      "display": "factory/juno1hj5fveer5cjtn4wd6wstzugjfdxzl0xps73ftl/denom1",
      "name": "factory/juno1hj5fveer5cjtn4wd6wstzugjfdxzl0xps73ftl/denom1",
      "symbol": "SYMBOL"
    }
  ],
  "pagination": {
    "next_key": null,
    "total": "1"
  }
}
```

## Mint Token

You can only mint a token you control. To allow a contract to mint tokens for you / your DAO, skip to the [contract section.](#tokenfactory-core-contract)

```sh
junod tx tokenfactory mint 100factory/juno1.../denom1 --from key [flags]
```

## Send Token

```shellscript
junod tx bank send [key] juno1addresshere 10factory/juno1.../denom1 [flags]
```

## Tokenfactory Core Contract

One of the biggest use cases for a tokenfactory token is to allow a contract to mint on the behalf of other contracts / DAOs. This is possible with the [Token Factory Core Middleware Contract](https://github.com/CosmosContracts/tokenfactory-contracts/tree/main/contracts/tokenfactory_core) on github. This contract can:

* Mint tokens on behalf of whitelisted contracts addresses via WasmMsg
* Allows an address to add / remove addresses from minting on its behalf
* Burn tokenfactory tokens

This means a DAO/SubDAO/Mutlisig is the manager of the contract. On its behalf, the middleware contract is the direct admin of the tokenfactory denominations so it can mint tokens. Then the DAO/SubDAO/Multisig can add or remove deployed contracts from minting tokens on its behalf. Without this, every contract you control would need its own denomination, which is too limiting if you want to use the same denomination on 2 or more contracts.

[To add support for your contract to mint tokens, just follow the Middleware guide found on the github.](https://github.com/CosmosContracts/tokenfactory-contracts/tree/main/contracts/tokenfactory_core) This also includes contracts to convert CW20 tokens to native tokens in a 1:1 ratio.

An [example contract can be found HERE](https://github.com/CosmosContracts/tokenfactory-contracts/tree/main/contracts/tf_example/src) which showcases the direct implementation of the middleware contract.


# API Endpoints

Schema for Juno node interaction (GET and POST requests).

Mainnet: <https://cosmos.directory/juno/nodes>\
Testnet: [https://testnet.cosmos.directory/junotestnet/nodes](https://cosmos.directory/juno/nodes)

Click on the "Nodes" tab, then "REST" for publicly provided infrastructure. If you wish to run your own non rate limited node, [check out our guide here](/validators/joining-mainnet)


# Cosmos


# Tx


# V1beta1


# Simulate

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/tx/v1beta1/simulate" method="post" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Txs

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/tx/v1beta1/txs" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/tx/v1beta1/txs" method="post" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/tx/v1beta1/txs/{hash}" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Block

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/tx/v1beta1/txs/block/{height}" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Params


# V1beta1


# Params

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/params/v1beta1/params" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Bank


# V1beta1


# Balances

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/bank/v1beta1/balances/{address}" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# By denom

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/bank/v1beta1/balances/{address}/by\_denom" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Denoms metadata

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/bank/v1beta1/denoms\_metadata" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/bank/v1beta1/denoms\_metadata/{denom}" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Params

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/bank/v1beta1/params" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Spendable balances

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/bank/v1beta1/spendable\_balances/{address}" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Supply

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/bank/v1beta1/supply" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/bank/v1beta1/supply/{denom}" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Upgrade


# V1beta1


# Applied plan

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/upgrade/v1beta1/applied\_plan/{name}" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Current plan

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/upgrade/v1beta1/current\_plan" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Module versions

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/upgrade/v1beta1/module\_versions" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Upgraded consensus state

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/upgrade/v1beta1/upgraded\_consensus\_state/{last\_height}" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Auth


# V1beta1


# Accounts

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/auth/v1beta1/accounts" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/auth/v1beta1/accounts/{address}" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Module accounts

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/auth/v1beta1/module\_accounts/{name}" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Params

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/auth/v1beta1/params" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Staking


# V1beta1


# Delegations

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/staking/v1beta1/delegations/{delegator\_addr}" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Historical info

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/staking/v1beta1/historical\_info/{height}" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Params

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/staking/v1beta1/params" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Pool

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/staking/v1beta1/pool" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Validators

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/staking/v1beta1/validators" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/staking/v1beta1/validators/{validator\_addr}" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Delegations

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/staking/v1beta1/validators/{validator\_addr}/delegations" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/staking/v1beta1/validators/{validator\_addr}/delegations/{delegator\_addr}" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Unbonding delegation

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/staking/v1beta1/validators/{validator\_addr}/delegations/{delegator\_addr}/unbonding\_delegation" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Unbonding delegations

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/staking/v1beta1/validators/{validator\_addr}/unbonding\_delegations" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Delegators


# Redelegations

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/staking/v1beta1/delegators/{delegator\_addr}/redelegations" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Unbonding delegations

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/staking/v1beta1/delegators/{delegator\_addr}/unbonding\_delegations" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Validators

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/staking/v1beta1/delegators/{delegator\_addr}/validators" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/staking/v1beta1/delegators/{delegator\_addr}/validators/{validator\_addr}" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Evidence


# V1beta1


# Evidence

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/evidence/v1beta1/evidence" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/evidence/v1beta1/evidence/{evidence\_hash}" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Mint


# V1beta1


# Annual provisions

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/mint/v1beta1/annual\_provisions" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Inflation

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/mint/v1beta1/inflation" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Params

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/mint/v1beta1/params" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Feegrant


# V1beta1


# Allowance

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/feegrant/v1beta1/allowance/{granter}/{grantee}" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Allowances

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/feegrant/v1beta1/allowances/{grantee}" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Issued

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/feegrant/v1beta1/issued/{granter}" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Gov


# V1beta1


# Params

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/gov/v1beta1/params/{params\_type}" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Proposals

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/gov/v1beta1/proposals" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/gov/v1beta1/proposals/{proposal\_id}" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Deposits

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/gov/v1beta1/proposals/{proposal\_id}/deposits" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/gov/v1beta1/proposals/{proposal\_id}/deposits/{depositor}" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Tally

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/gov/v1beta1/proposals/{proposal\_id}/tally" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Votes

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/gov/v1beta1/proposals/{proposal\_id}/votes" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/gov/v1beta1/proposals/{proposal\_id}/votes/{voter}" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Distribution


# V1beta1


# Community pool

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/distribution/v1beta1/community\_pool" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Params

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/distribution/v1beta1/params" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Delegators


# Rewards

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/distribution/v1beta1/delegators/{delegator\_address}/rewards" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/distribution/v1beta1/delegators/{delegator\_address}/rewards/{validator\_address}" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Validators

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/distribution/v1beta1/delegators/{delegator\_address}/validators" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Withdraw address

{% openapi src="/files/KEXXszJcXC55jWRkPqo5" path="/cosmos/distribution/v1beta1/delegators/{delegator\_address}/withdraw\_address" method="get" %}
[openapi (7).yml](https://2329221139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZiFiIZH5IkEYsWMUO4%2Fuploads%2Fgit-blob-99db90eeaa4d5ca922e1071d243b134f593f92d4%2Fopenapi%20\(7\).yml?alt=media)
{% endopenapi %}


# Validators




---

[Next Page](/llms-full.txt/1)

