Swap Direction
Understanding X→Y vs Y→X swaps in DLMM. Token ordering determines swap direction and affects how you interact with pairs.
Token Ordering in DLMM
In every pair:
Token X: The token with the smaller address (sorted)
Token Y: The token with the larger address
This ordering is permanent and automatic
// Example ordering
TokenX: "0x2::sui::SUI" // Smaller address
TokenY: "0xabc...::usdc::USDC" // Larger address
// SUI is always X, USDC is always Y in this pair
Understanding Swap Directions
X→Y Swap (xtoy = true)
Selling Token X
Buying Token Y
Price moves UP (more Y per X)
Y→X Swap (xtoy = false)
Selling Token Y
Buying Token X
Price moves DOWN (less Y per X)
Checking Token Order
const pair = await sdk.Pair.getPair(pairAddress);
console.log("Token X:", pair.tokenXType);
console.log("Token Y:", pair.tokenYType);
// Determine what xtoy means for this pair
if (pair.tokenXType.includes("SUI")) {
console.log("xtoy=true: Sell SUI for USDC");
console.log("xtoy=false: Sell USDC for SUI");
}
Common Patterns
Swap by Token Type
async function swapTokens(
pair: LBPair,
inputToken: string,
amount: bigint
) {
// Determine direction based on input token
const xtoy = inputToken === pair.tokenXType;
return await sdk.Swap.prepareSwap(pair, {
amount,
xtoy
});
}
User-Friendly Wrapper
// Helper for intuitive swapping
async function swap(
pair: LBPair,
fromToken: string,
toToken: string,
amount: bigint
) {
// Validate tokens belong to pair
const hasTokens =
(fromToken === pair.tokenXType || fromToken === pair.tokenYType) &&
(toToken === pair.tokenXType || toToken === pair.tokenYType);
if (!hasTokens) {
throw new Error("Invalid token pair");
}
// Set direction
const xtoy = fromToken === pair.tokenXType;
return await sdk.Swap.prepareSwap(pair, {
amount,
xtoy
});
}
Price Movement
// How swaps affect price
if (xtoy) {
// Selling X for Y
// Depletes Y reserves in bins
// Price moves to higher bins
// X becomes cheaper relative to Y
} else {
// Selling Y for X
// Depletes X reserves in bins
// Price moves to lower bins
// X becomes more expensive relative to Y
}
Quick Reference
Want to
Token In
Token Out
Use
Buy SUI
USDC (Y)
SUI (X)
xtoy: false
Sell SUI
SUI (X)
USDC (Y)
xtoy: true
Buy USDC
SUI (X)
USDC (Y)
xtoy: true
Sell USDC
USDC (Y)
SUI (X)
xtoy: false
Common Mistakes
// ❌ Wrong: Assuming token order
const tx = await sdk.Swap.prepareSwap(pair, {
amount,
xtoy: true // Assumes first token is X
});
// ✅ Correct: Check actual order
const sellingTokenX = inputToken === pair.tokenXType;
const tx = await sdk.Swap.prepareSwap(pair, {
amount,
xtoy: sellingTokenX
});
Related Topics
Execute Swap - Perform swaps
Get Single Pair - Check token order
Calculate Swap Output - Preview results
Last updated