> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hydro.markets/llms.txt
> Use this file to discover all available pages before exploring further.

# Integration examples

> CosmJS examples to read the hATOM rate, mint with ATOM or staked ATOM, and burn hATOM for staked ATOM.

## Why integrate hATOM

* **One chain.** hATOM is a token on the Cosmos Hub, issued by one contract on the Hub. Reading its rate, minting and burning are Hub queries and Hub transactions. There is no IBC channel, relayer or second chain to follow.
* **A rate you can read on chain.** The `Rate` query returns the exact value of hATOM in ATOM, from the contract's own books.
* **An instant exit to staked ATOM.** A burn pays LSM shares in the same transaction. Redeemed, they are delegations in the holder's name.
* **Simulations.** Each mint and burn has a simulation query that runs the same pricing as the execution.

## Setup

The examples use CosmJS 0.39 and `moonkittjs`, a TypeScript library generated for the Cosmos Hub, including gaia's `x/liquid` module. Messages to the hATOM contract are plain JSON sent with CosmJS `execute`. `moonkittjs` is only needed for the Hub's `x/liquid` messages: tokenizing a delegation and redeeming LSM shares.

> [!NOTE]
>
> A Hydro JS library (planned) will cover these flows.

```bash theme={null}
npm install @cosmjs/cosmwasm@^0.39 @cosmjs/proto-signing@^0.39 @cosmjs/stargate@^0.39 moonkittjs
```

```ts setup.ts theme={null}
import { CosmWasmClient, SigningCosmWasmClient, wasmTypes } from "@cosmjs/cosmwasm";
import { DirectSecp256k1HdWallet, Registry } from "@cosmjs/proto-signing";
import { GasPrice, defaultRegistryTypes } from "@cosmjs/stargate";
import {
  MessageComposer as LiquidMsgs,
  registry as liquidRegistry,
} from "moonkittjs/dist/codegen/gaia/liquid/v1beta1/tx.registry";
import { MsgTokenizeSharesResponse } from "moonkittjs/dist/codegen/gaia/liquid/v1beta1/tx";

const RPC_ENDPOINT = "<Hub RPC endpoint>";
const HATOM = "<hATOM contract address>";
const GAS_PRICE = "<gas price>uatom";

// Use your wallet's OfflineSigner in an app. A mnemonic is only for scripts.
const wallet = await DirectSecp256k1HdWallet.fromMnemonic("<mnemonic>", { prefix: "cosmos" });
const [{ address }] = await wallet.getAccounts();

// The default CosmJS types, the wasm types and the x/liquid types.
const registry = new Registry([...defaultRegistryTypes, ...wasmTypes, ...liquidRegistry]);

const client = await SigningCosmWasmClient.connectWithSigner(RPC_ENDPOINT, wallet, {
  registry,
  gasPrice: GasPrice.fromString(GAS_PRICE),
});

// Read the hATOM denom from the contract, never hardcode it.
const { denom: hatomDenom } = await client.queryContractSmart(HATOM, { config: {} });
```

The hATOM contract address is `cosmos1uwn9dv2tqzw5kzqyvksjygukkguwdpqwyu5u0fn239jaeckczltq960spc`. See [Contract addresses](https://docs.hydro.markets/hatom/developers/addresses.md) for the denom and the other accounts.

## Read the rate

`Rate` doesn't query the validators, so it is the cheapest query. A read-only client is enough.

```ts theme={null}
const reader = await CosmWasmClient.connect(RPC_ENDPOINT);
const { exchange_rate, supply, holders_value } = await reader.queryContractSmart(HATOM, { rate: {} });

// exchange_rate: ATOM per hATOM, as a decimal string.
// For an exact amount, use the integers: u hATOM units are worth floor(u × holders_value / supply).
const units = 1_000_000n; // 1 hATOM
const value = (units * BigInt(holders_value)) / BigInt(supply);
```

Things to know about the rate:

* Reward gains enter it at each `Compound` and are released over at least `release_floor_s`, so it rises smoothly.
* Rewards since the last `Compound` are not in it yet.
* A slash lowers it. A plain bank transfer of ATOM to the contract raises it at once.
* Never compute the rate from bank balances. Use the query.

### On-chain data

| Data | Query |
| - | - |
| Rate, supply | `{ "rate": {} }` |
| Delegations, idle, imbalance pool, locked gain, last `Compound`, pause and bonus state | `{ "state": {} }` |
| Each validator's weight, delegation and records | `{ "basket": {} }` |
| Denom, fee, roles, settings | `{ "config": {} }` |

Every operation emits a `wasm` event with an `action` attribute: `mint_from_native`, `mint_from_lsm`, `burn`, `compound`, `report_jailed`, `sweep`, `set_basket`, `set_fee`, and so on. A mint's event has `minted` and `recipient`. A burn's has `burned`, `value`, `out` and one `lsm_share` per share paid. A `Compound`'s has `rewards`, `fee` and `fee_minted`.

## Mint with ATOM

Simulate first, then send the mint with a `min_out` a little below the simulation.

```ts theme={null}
const amount = "10000000"; // 10 ATOM, in uatom

const sim = await client.queryContractSmart(HATOM, { simulate_mint_native: { amount } });
const minOut = ((BigInt(sim.minted) * 995n) / 1000n).toString(); // 0.5% margin

const res = await client.execute(
  address,
  HATOM,
  { mint_from_native: { min_out: minOut } },
  "auto",
  undefined,
  [{ denom: "uatom", amount }],
);
```

## Mint with staked ATOM

Use this when you already have a delegation to a basket validator. You keep your stake with that validator and skip any unbonding.

**1. Tokenize the delegation**

Send the Hub's `MsgTokenizeShares` with `moonkittjs`. The response carries the LSM share coin.

```ts theme={null}
const validator = "<valoper address of a basket validator>";
const tokens = "5000000"; // 5 ATOM, in uatom

const tokenize = LiquidMsgs.withTypeUrl.tokenizeShares({
  delegatorAddress: address,
  validatorAddress: validator,
  amount: { denom: "uatom", amount: tokens },
  tokenizedShareOwner: address,
});
const tx = await client.signAndBroadcast(address, [tokenize], "auto");
if (tx.code !== 0) throw new Error(tx.rawLog);

const { amount: share } = MsgTokenizeSharesResponse.decode(tx.msgResponses[0].value);
// share.denom is "<valoper address>/<record id>"
```

**2. Simulate the deposit**

Quote one unit less than the tokens tokenized: a share can redeem one unit short.

```ts theme={null}
const sim = await client.queryContractSmart(HATOM, {
  simulate_deposit: { shares: [{ validator, amount: (BigInt(tokens) - 1n).toString() }] },
});
```

**3. Send the shares to the contract**

```ts theme={null}
const res = await client.execute(
  address,
  HATOM,
  { mint_from_lsm: { min_out: sim.minted } },
  "auto",
  undefined,
  [share],
);
```

The validator must be in the basket, bonded, and at or under the commission maximum, or the contract refuses the shares. Check with the `basket` query first.

## Burn for staked ATOM

A burn pays LSM shares. Redeem them to hold the delegations in your own name. To get liquid ATOM, undelegate them afterwards and wait for the Hub's unbonding period.

**1. Simulate and burn**

```ts theme={null}
const amount = "4000000"; // 4 hATOM, in base units (6 decimals)

const sim = await client.queryContractSmart(HATOM, { simulate_burn: { amount } });
const minOut = ((BigInt(sim.out) * 995n) / 1000n).toString();

const res = await client.execute(
  address,
  HATOM,
  { burn: { min_out: minOut } },
  "auto",
  undefined,
  [{ denom: hatomDenom, amount }],
);
```

**2. Collect the shares paid**

Each share paid is a `lsm_share` attribute of the `wasm` event, as `<amount><denom>`.

```ts theme={null}
const shares = res.events
  .filter((e) => e.type === "wasm")
  .flatMap((e) => e.attributes)
  .filter((a) => a.key === "lsm_share")
  .map((a) => {
    const [, amount, denom] = a.value.match(/^(\d+)(.+)$/)!;
    return { amount, denom };
  });
```

**3. Redeem the shares**

Send the Hub's `MsgRedeemTokensForShares` with `moonkittjs`, one per share.

```ts theme={null}
const redeems = shares.map((coin) =>
  LiquidMsgs.withTypeUrl.redeemTokensForShares({ delegatorAddress: address, amount: coin }),
);
const tx = await client.signAndBroadcast(address, redeems, "auto");
```

> [!WARNING]
>
> If you burn with a different `recipient`, set `share_owner` to whoever will hold the shares. The Hub pays the rewards the shares earn until they are redeemed to the record's owner, not to the holder.

## Handle refusals

| Error | What to do |
| - | - |
| `BelowMinimum` | the price moved since your simulation. Simulate again. |
| `Paused` | the contract is paused. Simulations fail too. `rate` still answers. |
| `ImbalanceTooHigh` | the mint would pay more than `max_fee_bps`. Use a smaller amount or another validator. |
| `NoMintTarget` | no basket validator can take new stake now. The admin must set a new basket. |
| `InsufficientDelegation` | the delegations can't cover the burn yet, usually because idle ATOM is waiting to be delegated. Retry after a `Compound`, which anyone can send. |
| `OpInProgress` | retry in a later transaction. |

## Send a Compound

Anyone can compound. Keepers and integrators can send it, for example before a large burn.

```ts theme={null}
await client.execute(address, HATOM, { compound: {} }, "auto");
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.