Swapping with CosmJS
Overview
This tutorial is a complete script that swaps NTRN for ASTRO in the NTRN/ASTRO pool on Neutron with CosmJS. It simulates the swap, derives a belief_price from the simulation and sends the swap.
For an explanation of every parameter, CW20 swaps and Terra examples, see Swapping. For routes through several pools, see Multi-hop Routing.
| Name | Value |
|---|---|
| Chain | Neutron (neutron-1) |
| Pool (ASTRO/NTRN) | neutron1rnz97pgxe0u2a0fduxz4kxape7x32lveu85nl5euf6qhgawkpv7qsmwtd0 |
| NTRN | untrn (6 decimals) |
| ASTRO | factory/neutron1ffus553eet978k024lmssw0czsxwr97mggyv85lpcsdkft8v9ufsz3sa07/astro (6 decimals) |
This tutorial reads the mnemonic from an environment variable to keep the example short. Use proper key management for anything beyond testing, and never commit a mnemonic.
Step 1: Install the Libraries
_1npm install @cosmjs/cosmwasm-stargate @cosmjs/proto-signing @cosmjs/stargate
Step 2: Connect
_16import { SigningCosmWasmClient } from "@cosmjs/cosmwasm-stargate";_16import { DirectSecp256k1HdWallet } from "@cosmjs/proto-signing";_16import { GasPrice } from "@cosmjs/stargate";_16_16const rpc = "https://neutron-rpc.polkachu.com";_16const pool = "neutron1rnz97pgxe0u2a0fduxz4kxape7x32lveu85nl5euf6qhgawkpv7qsmwtd0";_16const astro = "factory/neutron1ffus553eet978k024lmssw0czsxwr97mggyv85lpcsdkft8v9ufsz3sa07/astro";_16_16const wallet = await DirectSecp256k1HdWallet.fromMnemonic(process.env.MNEMONIC, {_16 prefix: "neutron",_16});_16const [{ address: sender }] = await wallet.getAccounts();_16_16const client = await SigningCosmWasmClient.connectWithSigner(rpc, wallet, {_16 gasPrice: GasPrice.fromString("0.0053untrn"),_16});
On Terra, use prefix: "terra", the HD path m/44'/330'/0'/0/0 (hdPaths: [stringToPath("m/44'/330'/0'/0/0")] from @cosmjs/crypto) and a uluna gas price. See Network for endpoints.
Step 3: Simulate the Swap
_10const offerAmount = "1000000"; // 1 NTRN, in base units_10_10const sim = await client.queryContractSmart(pool, {_10 simulation: {_10 offer_asset: { info: { native_token: { denom: "untrn" } }, amount: offerAmount },_10 ask_asset_info: { native_token: { denom: astro } },_10 },_10});_10_10console.log(sim); // { return_amount: "...", spread_amount: "...", commission_amount: "..." }
Step 4: Derive belief_price
belief_price is the offer amount per unit of the return amount, both in base units. It is a decimal string; do not scale it.
_2const beliefPrice = (Number(offerAmount) / Number(sim.return_amount)).toFixed(18);_2const maxSpread = "0.01"; // fail if we would receive more than 1% less than the simulation
For example, if the simulation returns 363866 (0.363866 ASTRO) for 1000000 untrn, then belief_price = 1000000 / 363866 = 2.748264470986571979 and the swap fails if the pool would return less than 363866 * 0.99 = 360227.34.
Step 5: Swap
Attach the offer amount as funds:
_17const result = await client.execute(_17 sender,_17 pool,_17 {_17 swap: {_17 offer_asset: { info: { native_token: { denom: "untrn" } }, amount: offerAmount },_17 ask_asset_info: { native_token: { denom: astro } },_17 belief_price: beliefPrice,_17 max_spread: maxSpread,_17 },_17 },_17 "auto",_17 "",_17 [{ denom: "untrn", amount: offerAmount }]_17);_17_17console.log(result.transactionHash);
Complete Script
_50import { SigningCosmWasmClient } from "@cosmjs/cosmwasm-stargate";_50import { DirectSecp256k1HdWallet } from "@cosmjs/proto-signing";_50import { GasPrice } from "@cosmjs/stargate";_50_50const rpc = "https://neutron-rpc.polkachu.com";_50const pool = "neutron1rnz97pgxe0u2a0fduxz4kxape7x32lveu85nl5euf6qhgawkpv7qsmwtd0";_50const astro = "factory/neutron1ffus553eet978k024lmssw0czsxwr97mggyv85lpcsdkft8v9ufsz3sa07/astro";_50_50const main = async () => {_50 const wallet = await DirectSecp256k1HdWallet.fromMnemonic(process.env.MNEMONIC, {_50 prefix: "neutron",_50 });_50 const [{ address: sender }] = await wallet.getAccounts();_50 const client = await SigningCosmWasmClient.connectWithSigner(rpc, wallet, {_50 gasPrice: GasPrice.fromString("0.0053untrn"),_50 });_50_50 const offerAmount = "1000000"; // 1 NTRN_50 const offerInfo = { native_token: { denom: "untrn" } };_50 const askInfo = { native_token: { denom: astro } };_50_50 const sim = await client.queryContractSmart(pool, {_50 simulation: { offer_asset: { info: offerInfo, amount: offerAmount }, ask_asset_info: askInfo },_50 });_50_50 const beliefPrice = (Number(offerAmount) / Number(sim.return_amount)).toFixed(18);_50_50 const result = await client.execute(_50 sender,_50 pool,_50 {_50 swap: {_50 offer_asset: { info: offerInfo, amount: offerAmount },_50 ask_asset_info: askInfo,_50 belief_price: beliefPrice,_50 max_spread: "0.01",_50 },_50 },_50 "auto",_50 "",_50 [{ denom: "untrn", amount: offerAmount }]_50 );_50_50 console.log(`Swapped. Expected ${sim.return_amount} base units of ASTRO, tx ${result.transactionHash}`);_50};_50_50main().catch((error) => {_50 console.error("Swap failed:", error);_50 process.exit(1);_50});
Run it with MNEMONIC="..." node swap.mjs.