Skip to main content

Swapping

Overview​

Every Astroport pool (xyk, stableswap, PCL, transmuter) exposes the same swap endpoint and the same simulation and reverse_simulation queries. This page shows how to swap in a single pool directly:

  1. Simulate the swap to see what you will receive.
  2. Turn the simulation into a belief_price and pick a max_spread.
  3. Send the swap: native tokens are attached to the swap message, CW20 tokens are sent with a CW20 send that embeds the swap.

To swap through several pools in one transaction, use the Router instead: see Multi-hop Routing.

The examples use the Terra LUNA/USDC pool and CosmJS. The same messages work on Neutron with Neutron addresses and denoms. Contract addresses for both chains are listed on the Contract Addresses page.

NameValue
Pool (LUNA/USDC, Terra)terra1v3lqxl0eyte9x3nhdgcj8hwvjq76aupnnzz0yll8mxs5cckc29pqvg2scu
LUNAuluna (6 decimals)
USDC (Noble)ibc/2C962DAB9F57FE0921435426AE75196009FAA1981BF86991203C8411F8980FDB (6 decimals)

You can look up the pool for any pair of assets with the factory's pair query (see Creating a Pair).

NOTE

Some Neutron pools are withdraw-only (exit-only) and refuse swaps. Check a pool before you route trades through it: an exit-only pool answers the simulation query with an error.

Setup​


_21
import { CosmWasmClient, SigningCosmWasmClient } from "@cosmjs/cosmwasm-stargate";
_21
import { DirectSecp256k1HdWallet } from "@cosmjs/proto-signing";
_21
import { stringToPath } from "@cosmjs/crypto";
_21
import { GasPrice } from "@cosmjs/stargate";
_21
_21
const rpc = "https://terra-rpc.publicnode.com";
_21
const pair = "terra1v3lqxl0eyte9x3nhdgcj8hwvjq76aupnnzz0yll8mxs5cckc29pqvg2scu";
_21
const usdc = "ibc/2C962DAB9F57FE0921435426AE75196009FAA1981BF86991203C8411F8980FDB";
_21
_21
// Read-only client for queries
_21
const client = await CosmWasmClient.connect(rpc);
_21
_21
// Signing client for transactions. Terra uses coin type 330; Neutron uses the default (118).
_21
const wallet = await DirectSecp256k1HdWallet.fromMnemonic(process.env.MNEMONIC, {
_21
prefix: "terra",
_21
hdPaths: [stringToPath("m/44'/330'/0'/0/0")],
_21
});
_21
const [{ address: sender }] = await wallet.getAccounts();
_21
const signingClient = await SigningCosmWasmClient.connectWithSigner(rpc, wallet, {
_21
gasPrice: GasPrice.fromString("0.015uluna"),
_21
});

For Neutron, use prefix: "neutron", drop hdPaths, and use an untrn gas price (for example 0.0053untrn). See Network for endpoints.

Simulating a Swap​

The simulation query takes the offer_asset (asset and amount, in base units) and, optionally, the ask_asset_info. ask_asset_info can be left out in a two-asset pool; it is required in pools with more assets.


_17
{
_17
"simulation": {
_17
"offer_asset": {
_17
"info": {
_17
"native_token": {
_17
"denom": "uluna"
_17
}
_17
},
_17
"amount": "10000000"
_17
},
_17
"ask_asset_info": {
_17
"native_token": {
_17
"denom": "ibc/2C962DAB9F57FE0921435426AE75196009FAA1981BF86991203C8411F8980FDB"
_17
}
_17
}
_17
}
_17
}

The response is a SimulationResponse. All amounts are in base units of the ask asset.


_5
{
_5
"return_amount": "394395",
_5
"spread_amount": "1627",
_5
"commission_amount": "461"
_5
}

FieldDescription
return_amountWhat you receive, after fees
spread_amountThe price impact of this swap size, in ask asset units
commission_amountThe swap fee taken from the ask asset

In this example 10 LUNA (10000000 uluna) returns 0.394395 USDC. Your numbers will differ: they depend on the pool's state when you query it.

To ask the opposite question (how much do I need to offer to receive a given amount), use reverse_simulation:


_17
{
_17
"reverse_simulation": {
_17
"offer_asset_info": {
_17
"native_token": {
_17
"denom": "uluna"
_17
}
_17
},
_17
"ask_asset": {
_17
"info": {
_17
"native_token": {
_17
"denom": "ibc/2C962DAB9F57FE0921435426AE75196009FAA1981BF86991203C8411F8980FDB"
_17
}
_17
},
_17
"amount": "1000000"
_17
}
_17
}
_17
}

It returns offer_amount, spread_amount and commission_amount.

Price Protection: belief_price and max_spread​

The swap message takes two optional parameters that bound the price you get:

  • belief_price: the price you expect, expressed as offer amount per one unit of ask amount, both in base units: belief_price = offer_amount / expected_return_amount. It is a Decimal string such as "25.355291015352628710", not a micro-scaled integer.
  • max_spread: the largest shortfall you accept, as a fraction ("0.01" is 1%). It defaults to 0.005 (0.5%) and can't be more than 0.5 (50%).

The pool checks them after computing the swap:

  • With belief_price: the pool computes expected_return = offer_amount / belief_price and fails the swap (Operation exceeds max spread limit) if return_amount < expected_return * (1 - max_spread).
  • Without belief_price: the pool only checks its own price impact, spread_amount / (return_amount + spread_amount) <= max_spread. This compares the trade against the pool's current price, so it does not protect you if the pool's price has already moved (for example, because another transaction traded in front of yours). Always send belief_price for real trades.

Calculating belief_price​

Use the simulation result from above:


_8
offer_amount = 10000000 (10 LUNA)
_8
return_amount = 394395 (0.394395 USDC)
_8
_8
belief_price = 10000000 / 394395 = 25.355291015352628710
_8
max_spread = 0.01
_8
_8
expected_return = 10000000 / 25.355291015352628710 = 394395
_8
swap fails if the pool would return less than 394395 * 0.99 = 390451.05

In code:


_12
const offerAmount = "10000000"; // 10 LUNA
_12
_12
const sim = await client.queryContractSmart(pair, {
_12
simulation: {
_12
offer_asset: { info: { native_token: { denom: "uluna" } }, amount: offerAmount },
_12
ask_asset_info: { native_token: { denom: usdc } },
_12
},
_12
});
_12
_12
// offer / return, as a decimal string (Decimal accepts up to 18 fractional digits)
_12
const beliefPrice = (Number(offerAmount) / Number(sim.return_amount)).toFixed(18);
_12
const maxSpread = "0.01";

Common mistakes
  • Don't invert it. belief_price is offer per ask (offer / return). Using return / offer makes the expected return far too high or too low, so the swap either always fails or is not protected.
  • Don't scale it. Don't multiply the price by 10^6 or pass return_amount itself as the price.
  • Mind decimals. Both amounts are in base units. When the two tokens have the same number of decimals (as LUNA and USDC do, 6 each), the base-unit ratio equals the display price. When they differ (for example a 6-decimal token against an 18-decimal token), the base-unit ratio is what the pool expects, not the display price.
  • A simulation is only as good as the moment it was taken. A belief_price derived from a simulation protects you against the price moving between your query and your transaction. If you have a price you trust from elsewhere (your own quote, an oracle), derive belief_price from that instead.

Native Swap​

When the offer asset is a native token (uluna, untrn, IBC and tokenfactory denoms), call swap on the pool and attach the offer amount as funds. The attached amount must equal offer_asset.amount.


_19
{
_19
"swap": {
_19
"offer_asset": {
_19
"info": {
_19
"native_token": {
_19
"denom": "uluna"
_19
}
_19
},
_19
"amount": "10000000"
_19
},
_19
"ask_asset_info": {
_19
"native_token": {
_19
"denom": "ibc/2C962DAB9F57FE0921435426AE75196009FAA1981BF86991203C8411F8980FDB"
_19
}
_19
},
_19
"belief_price": "25.355291015352628710",
_19
"max_spread": "0.01"
_19
}
_19
}

ParameterTypeDescription
offer_assetAssetThe asset and amount you offer
ask_asset_infoOption<AssetInfo>The asset you want. Optional in two-asset pools
belief_priceOption<Decimal>Expected price, offer per ask, in base units
max_spreadOption<Decimal>Largest accepted shortfall against belief_price (default 0.005, max 0.5)
toOption<String>Recipient of the ask asset, if not the sender

_17
const result = await signingClient.execute(
_17
sender,
_17
pair,
_17
{
_17
swap: {
_17
offer_asset: { info: { native_token: { denom: "uluna" } }, amount: offerAmount },
_17
ask_asset_info: { native_token: { denom: usdc } },
_17
belief_price: beliefPrice,
_17
max_spread: maxSpread,
_17
},
_17
},
_17
"auto",
_17
"",
_17
[{ denom: "uluna", amount: offerAmount }] // funds: the offer asset
_17
);
_17
_17
console.log(result.transactionHash);

CW20 Swap​

When the offer asset is a CW20 token, you don't call the pool directly. Instead, call send on the CW20 token contract with the pool as contract and a base64-encoded swap hook as msg. The hook has the same fields as swap except offer_asset: the token and amount come from the send itself.

The decoded hook message:


_11
{
_11
"swap": {
_11
"ask_asset_info": {
_11
"native_token": {
_11
"denom": "uluna"
_11
}
_11
},
_11
"belief_price": "0.039439500000000000",
_11
"max_spread": "0.01"
_11
}
_11
}

The send message on the CW20 contract (the msg value is the hook above, JSON-encoded and then base64-encoded):


_7
{
_7
"send": {
_7
"contract": "terra1...pool",
_7
"amount": "1000000",
_7
"msg": "eyJzd2FwIjp7ImFza19hc3NldF9pbmZvIjp7Im5hdGl2ZV90b2tlbiI6eyJkZW5vbSI6InVsdW5hIn19LCJiZWxpZWZfcHJpY2UiOiIwLjAzOTQzOTUwMDAwMDAwMDAwMCIsIm1heF9zcHJlYWQiOiIwLjAxIn19"
_7
}
_7
}

With CosmJS, toBinary does the encoding:


_23
import { toBinary } from "@cosmjs/cosmwasm-stargate";
_23
_23
const cw20Token = "terra1...token"; // the CW20 you are selling
_23
const cw20Pool = "terra1...pool"; // a pool that holds this CW20
_23
_23
const result = await signingClient.execute(
_23
sender,
_23
cw20Token, // the message goes to the token contract, not the pool
_23
{
_23
send: {
_23
contract: cw20Pool,
_23
amount: "1000000",
_23
msg: toBinary({
_23
swap: {
_23
ask_asset_info: { native_token: { denom: "uluna" } },
_23
belief_price: cw20BeliefPrice, // offer (CW20) per ask (uluna), from a simulation of this pool
_23
max_spread: "0.01",
_23
},
_23
}),
_23
},
_23
},
_23
"auto"
_23
);

For the simulation, describe a CW20 with the token variant of AssetInfo:


_12
{
_12
"simulation": {
_12
"offer_asset": {
_12
"info": {
_12
"token": {
_12
"contract_addr": "terra1...token"
_12
}
_12
},
_12
"amount": "1000000"
_12
}
_12
}
_12
}