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:
- Simulate the swap to see what you will receive.
- Turn the simulation into a
belief_priceand pick amax_spread. - Send the swap: native tokens are attached to the
swapmessage, CW20 tokens are sent with a CW20sendthat 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.
| Name | Value |
|---|---|
| Pool (LUNA/USDC, Terra) | terra1v3lqxl0eyte9x3nhdgcj8hwvjq76aupnnzz0yll8mxs5cckc29pqvg2scu |
| LUNA | uluna (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).
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
_21import { CosmWasmClient, SigningCosmWasmClient } from "@cosmjs/cosmwasm-stargate";_21import { DirectSecp256k1HdWallet } from "@cosmjs/proto-signing";_21import { stringToPath } from "@cosmjs/crypto";_21import { GasPrice } from "@cosmjs/stargate";_21_21const rpc = "https://terra-rpc.publicnode.com";_21const pair = "terra1v3lqxl0eyte9x3nhdgcj8hwvjq76aupnnzz0yll8mxs5cckc29pqvg2scu";_21const usdc = "ibc/2C962DAB9F57FE0921435426AE75196009FAA1981BF86991203C8411F8980FDB";_21_21// Read-only client for queries_21const client = await CosmWasmClient.connect(rpc);_21_21// Signing client for transactions. Terra uses coin type 330; Neutron uses the default (118)._21const wallet = await DirectSecp256k1HdWallet.fromMnemonic(process.env.MNEMONIC, {_21 prefix: "terra",_21 hdPaths: [stringToPath("m/44'/330'/0'/0/0")],_21});_21const [{ address: sender }] = await wallet.getAccounts();_21const 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}
| Field | Description |
|---|---|
return_amount | What you receive, after fees |
spread_amount | The price impact of this swap size, in ask asset units |
commission_amount | The 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 aDecimalstring 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 to0.005(0.5%) and can't be more than0.5(50%).
The pool checks them after computing the swap:
- With
belief_price: the pool computesexpected_return = offer_amount / belief_priceand fails the swap (Operation exceeds max spread limit) ifreturn_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 sendbelief_pricefor real trades.
Calculating belief_price
Use the simulation result from above:
_8offer_amount = 10000000 (10 LUNA)_8return_amount = 394395 (0.394395 USDC)_8_8belief_price = 10000000 / 394395 = 25.355291015352628710_8max_spread = 0.01_8_8expected_return = 10000000 / 25.355291015352628710 = 394395_8swap fails if the pool would return less than 394395 * 0.99 = 390451.05
In code:
_12const offerAmount = "10000000"; // 10 LUNA_12_12const 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)_12const beliefPrice = (Number(offerAmount) / Number(sim.return_amount)).toFixed(18);_12const maxSpread = "0.01";
- Don't invert it.
belief_priceis offer per ask (offer / return). Usingreturn / offermakes 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_amountitself 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_pricederived 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), derivebelief_pricefrom 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}
| Parameter | Type | Description |
|---|---|---|
offer_asset | Asset | The asset and amount you offer |
ask_asset_info | Option<AssetInfo> | The asset you want. Optional in two-asset pools |
belief_price | Option<Decimal> | Expected price, offer per ask, in base units |
max_spread | Option<Decimal> | Largest accepted shortfall against belief_price (default 0.005, max 0.5) |
to | Option<String> | Recipient of the ask asset, if not the sender |
_17const 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_17console.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:
_23import { toBinary } from "@cosmjs/cosmwasm-stargate";_23_23const cw20Token = "terra1...token"; // the CW20 you are selling_23const cw20Pool = "terra1...pool"; // a pool that holds this CW20_23_23const 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}
Links
- Pool contracts: full message reference for each pool type
- Common Types:
AssetandAssetInfo - Multi-hop Routing: swaps across several pools with Router 2.0
- Pair message types in astroport-core