Skip to main content

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.

NameValue
ChainNeutron (neutron-1)
Pool (ASTRO/NTRN)neutron1rnz97pgxe0u2a0fduxz4kxape7x32lveu85nl5euf6qhgawkpv7qsmwtd0
NTRNuntrn (6 decimals)
ASTROfactory/neutron1ffus553eet978k024lmssw0czsxwr97mggyv85lpcsdkft8v9ufsz3sa07/astro (6 decimals)
NOTE

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​


_1
npm install @cosmjs/cosmwasm-stargate @cosmjs/proto-signing @cosmjs/stargate

Step 2: Connect​


_16
import { SigningCosmWasmClient } from "@cosmjs/cosmwasm-stargate";
_16
import { DirectSecp256k1HdWallet } from "@cosmjs/proto-signing";
_16
import { GasPrice } from "@cosmjs/stargate";
_16
_16
const rpc = "https://neutron-rpc.polkachu.com";
_16
const pool = "neutron1rnz97pgxe0u2a0fduxz4kxape7x32lveu85nl5euf6qhgawkpv7qsmwtd0";
_16
const astro = "factory/neutron1ffus553eet978k024lmssw0czsxwr97mggyv85lpcsdkft8v9ufsz3sa07/astro";
_16
_16
const wallet = await DirectSecp256k1HdWallet.fromMnemonic(process.env.MNEMONIC, {
_16
prefix: "neutron",
_16
});
_16
const [{ address: sender }] = await wallet.getAccounts();
_16
_16
const 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​


_10
const offerAmount = "1000000"; // 1 NTRN, in base units
_10
_10
const 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
_10
console.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.


_2
const beliefPrice = (Number(offerAmount) / Number(sim.return_amount)).toFixed(18);
_2
const 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:


_17
const 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
_17
console.log(result.transactionHash);

Complete Script​


_50
import { SigningCosmWasmClient } from "@cosmjs/cosmwasm-stargate";
_50
import { DirectSecp256k1HdWallet } from "@cosmjs/proto-signing";
_50
import { GasPrice } from "@cosmjs/stargate";
_50
_50
const rpc = "https://neutron-rpc.polkachu.com";
_50
const pool = "neutron1rnz97pgxe0u2a0fduxz4kxape7x32lveu85nl5euf6qhgawkpv7qsmwtd0";
_50
const astro = "factory/neutron1ffus553eet978k024lmssw0czsxwr97mggyv85lpcsdkft8v9ufsz3sa07/astro";
_50
_50
const 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
_50
main().catch((error) => {
_50
console.error("Swap failed:", error);
_50
process.exit(1);
_50
});

Run it with MNEMONIC="..." node swap.mjs.