How Slippage Calculation Works in Osmosis Swap Transactions
Slippage calculation in Osmosis swap transactions applies a user-specified percentage tolerance to adjust the maximum input amount (for exact-out swaps) or minimum output amount (for exact-in swaps), using ceiling and floor rounding to maintain integer token units.
The osmosis-agent-toolkit provides a TypeScript interface for executing swaps on the Osmosis decentralized exchange. Understanding how slippage calculation works is essential for protecting trades against price movements between quote retrieval and transaction broadcast. The toolkit implements distinct formulas for exact-in and exact-out swap directions, with a default tolerance of 0.5% when users do not specify otherwise.
Understanding Slippage in Decentralized Exchanges
Slippage represents the difference between the expected price of a trade and the actual price when the transaction executes. In automated market maker (AMM) environments like Osmosis, prices shift as liquidity pools rebalance. When a user requests a swap quote from the Osmosis Sidecar Query Server (SQS), the response reflects the pool state at that exact moment. By the time the transaction reaches the chain, market conditions may have changed, potentially resulting in unfavorable execution prices without proper slippage protection.
How Slippage Calculation Works in the Osmosis Agent Toolkit
The toolkit processes slippage differently depending on whether the user specifies the input amount (exact-in) or the desired output amount (exact-out). Both calculations occur in packages/core/src/tx/swap.ts before constructing the final transaction message.
Quote-Derived Amounts
Before applying slippage calculations, the toolkit retrieves raw amounts from the Osmosis SQS:
- Exact-in quotes (
SidecarOutGivenInQuoteResponse) provideamount_out— the expected tokens received - Exact-out quotes (
SidecarInGivenOutQuoteResponse) provideamount_in— the expected tokens required
These values represent the zero-slippage scenario and serve as the baseline for tolerance calculations.
Exact-Out Swaps: Calculating Maximum Input
When executing an exact-out swap (where the user knows how much they want to receive), slippage calculation determines the maximum amount of input tokens the user is willing to spend. This protects against the input token becoming more expensive relative to the output.
According to packages/core/src/tx/swap.ts lines 17-19, the formula is:
tokenInMaxAmount = Math.ceil(amount_in * (1 + slippagePercent / 100))
The Math.ceil operation ensures the value rounds up to the nearest whole token unit, preventing transaction failures due to fractional amounts while ensuring the user never spends more than the calculated maximum.
Exact-In Swaps: Calculating Minimum Output
For exact-in swaps (where the user specifies how much to spend), slippage calculation establishes the minimum amount of output tokens the user will accept. This guards against the output token losing value before execution.
As implemented in packages/core/src/tx/swap.ts lines 52-54:
tokenOutMinAmount = Math.floor(amount_out * (1 - slippagePercent / 100))
The Math.floor operation rounds down to ensure the user receives at least the calculated minimum, accounting for the conservative nature of slippage protection.
Default Slippage Tolerance Settings
The toolkit provides sensible defaults when users omit slippage parameters. Both swap directions default to 0.5% tolerance:
- Exact-out transactions:
SendSwapInGivenOutQuoteTxToolinpackages/core/src/tools/swap.ts(lines 38-42) usesparams.slippageTolerancePercent ?? 0.5 - Exact-in transactions:
SendSwapOutGivenInQuoteTxToolinpackages/core/src/tools/swap.ts(lines 91-95) applies the same default
These defaults strike a balance between protection against normal market volatility and transaction success rates.
Implementation Details and Code Examples
Exact-Out Swap with Custom Slippage
When executing a swap where you specify the desired output amount, apply custom slippage tolerance as follows:
import { SwapQuoteInGivenOutTool, SendSwapInGivenOutQuoteTxTool } from '@osmosis-agent-toolkit/core';
// 1. Retrieve quote for exact-out swap
const quoteTool = new SwapQuoteInGivenOutTool(sqsClient, memory);
const quote = await quoteTool.call({
tickerIn: 'OSMO',
amountOut: '100', // Want to receive 100 OSMO
tickerOut: 'ATOM',
});
// 2. Execute with 1% slippage tolerance
const sendTool = new SendSwapInGivenOutQuoteTxTool(account, memory);
const { txHash } = await sendTool.call({
quoteId: quote.id,
slippageTolerancePercent: 1, // 1% maximum slippage
});
console.log('Transaction hash:', txHash);
The SendSwapInGivenOutQuoteTxTool internally calls makeSwapExactAmountOutEncodeObject, which calculates tokenInMaxAmount using Math.ceil(quote.amount_in * 1.01).
Exact-In Swap with Default Slippage
For standard swaps where you specify the input amount, omit the slippage parameter to use the 0.5% default:
import { SwapQuoteOutGivenInTool, SendSwapOutGivenInQuoteTxTool } from '@osmosis-agent-toolkit/core';
// Get quote for spending 50 ATOM
const quoteTool = new SwapQuoteOutGivenInTool(sqsClient, memory);
const quote = await quoteTool.call({
tickerIn: 'ATOM',
amountIn: '50',
tickerOut: 'OSMO',
});
// Execute with default 0.5% slippage
const sendTool = new SendSwapOutGivenInQuoteTxTool(account, memory);
const { txHash } = await sendTool.call({
quoteId: quote.id,
// slippageTolerancePercent omitted - defaults to 0.5
});
console.log('Swap executed:', txHash);
Here, makeSwapExactAmountInEncodeObject applies Math.floor(quote.amount_out * 0.995) to determine the minimum acceptable output.
Key Source Files and Functions
Understanding the complete slippage calculation workflow requires familiarity with these specific files in the jonator/osmosis-agent-toolkit repository:
| File | Purpose | Key Sections |
|---|---|---|
packages/core/src/tx/swap.ts |
Core transaction encoder that applies slippage formulas to raw quotes. | Token-in maximum calculation (L17-L19), token-out minimum calculation (L52-L54), makeSwapExactAmountOutEncodeObject, makeSwapExactAmountInEncodeObject. |
packages/core/src/tools/swap.ts |
High-level tool implementations that handle default slippage values and transaction broadcasting. | Default 0.5% tolerance in SendSwapInGivenOutQuoteTxTool (L38-L42) and SendSwapOutGivenInQuoteTxTool (L91-L95). |
packages/core/src/queries/sqs/router.ts |
Type definitions for SQS quote responses. | SidecarOutGivenInQuoteResponse (exact-in quotes), SidecarInGivenOutQuoteResponse (exact-out quotes). |
packages/core/src/utils/number.ts |
Precision utilities for converting human-readable amounts to smallest-unit integers. | mulPrecision helper used before slippage calculations. |
These files work sequentially: the query layer retrieves raw amounts, the tool layer applies default tolerances, and the transaction layer encodes the final slippage-protected messages for broadcast.
Summary
- Slippage calculation in the Osmosis Agent Toolkit protects users from price movements between quote retrieval and transaction execution by adjusting acceptable input or output bounds.
- Exact-out swaps calculate a maximum input amount using
Math.ceil(amount_in * (1 + slippage/100))to prevent over-spending. - Exact-in swaps calculate a minimum output amount using
Math.floor(amount_out * (1 - slippage/100))to guarantee minimum receipts. - Default tolerance is 0.5% when not specified, applied in
SendSwapInGivenOutQuoteTxToolandSendSwapOutGivenInQuoteTxTool. - Core implementation resides in
packages/core/src/tx/swap.ts, with formulas at lines 17-19 and 52-54.
Frequently Asked Questions
What is the default slippage tolerance in osmosis-agent-toolkit?
The default slippage tolerance is 0.5% (0.5 percent). This value is automatically applied when executing swaps through SendSwapInGivenOutQuoteTxTool or SendSwapOutGivenInQuoteTxTool if the caller does not explicitly provide a slippageTolerancePercent parameter.
How does slippage calculation differ between exact-in and exact-out swaps?
For exact-out swaps (where you specify the desired output amount), slippage increases the calculated input amount using Math.ceil(amount_in * (1 + slippage/100)) to set a maximum spend limit. For exact-in swaps (where you specify the input amount), slippage decreases the expected output using Math.floor(amount_out * (1 - slippage/100)) to establish a minimum receipt guarantee.
Why does the toolkit use Math.ceil and Math.floor for slippage calculations?
The toolkit uses Math.ceil for exact-out swaps to round the maximum input amount upward to the nearest whole token unit, ensuring the transaction will not fail due to insufficient input if the price moves against the user. Conversely, Math.floor is used for exact-in swaps to round the minimum output amount downward, guaranteeing the user receives at least the calculated minimum even if the pool price shifts unfavorably. Both operations ensure amounts remain integers in the token's smallest unit (e.g., uatom).
Where is the slippage calculation implemented in the source code?
The core slippage formulas are implemented in packages/core/src/tx/swap.ts at lines 17-19 (for exact-out swaps calculating tokenInMaxAmount) and lines 52-54 (for exact-in swaps calculating tokenOutMinAmount). The default 0.5% tolerance values are defined in packages/core/src/tools/swap.ts at lines 38-42 and 91-95 within the SendSwapInGivenOutQuoteTxTool and SendSwapOutGivenInQuoteTxTool classes respectively.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →