How OsmosisSqsQueryClient Integrates with the Osmosis Sidecar Query Service
The OsmosisSqsQueryClient is a TypeScript HTTP wrapper that constructs REST requests, handles query parameters, and deserializes JSON responses from the Osmosis Sidecar Query Service (SQS) into strongly-typed interfaces.
The OsmosisSqsQueryClient serves as the primary bridge between the osmosis-agent-toolkit SDK and the Osmosis Sidecar Query Service. This lightweight client abstracts the complexity of URL construction, parameter encoding, and response parsing, exposing three high-level methods for fetching swap quotes and token prices. Higher-level components such as OsmosisAgentToolkit and the swap tools consume these methods to obtain live market data without managing HTTP plumbing.
What Is the Osmosis Sidecar Query Service?
The Osmosis Sidecar Query Service (SQS) is a RESTful API endpoint maintained by Osmosis that exposes real-time price quotes, routing information, and token price data for the Osmosis AMM. It accepts parameters for token denominations and amounts, calculates optimal swap routes, and returns JSON payloads containing estimated outputs, price impact, and fee breakdowns.
OsmosisSqsQueryClient Architecture and Design
Core Responsibilities
The client, defined in packages/core/src/queries/sqs/client.ts, encapsulates three critical functions:
- URL Construction: Builds endpoints for
/router/quoteand/tokens/priceswith the base URLhttps://sqsprod.osmosis.zone. - Parameter Encoding: Automatically appends
humanDenoms=falseto ensure raw minimal denominations are used, and formats token amounts as concatenated strings (e.g.,1000000uosmo). - Type-Safe Deserialization: Casts JSON responses to TypeScript interfaces defined in
router.tsandprices.ts.
Type Safety with router.ts
The packages/core/src/queries/sqs/router.ts file defines the contract between the client and the SQS API:
export type SidecarOutGivenInQuoteResponse = {
amount_in: { denom: string; amount: string };
amount_out: string;
// …additional fields (fee, price impact, route, etc.)
};
export type SidecarInGivenOutQuoteResponse = {
amount_out: { denom: string; amount: string };
amount_in: string;
// …additional fields (fee, price impact, route, etc.)
};
These types guarantee that callers receive predictable object shapes when processing swap quotes.
How OsmosisSqsQueryClient Communicates with SQS
Constructing Out-Given-In Quotes
The getOutGivenInQuote method in client.ts fetches the expected output for a specified input:
async getOutGivenInQuote(tokenIn, tokenOutDenom) {
const url = this.url('/router/quote');
url.searchParams.set('tokenIn', `${tokenIn.amount}${tokenIn.denom}`);
url.searchParams.set('tokenOutDenom', tokenOutDenom);
const response = await fetch(url);
return (await response.json()) as SidecarOutGivenInQuoteResponse;
}
This method concatenates the amount and denomination into a single string (e.g., 1000000uosmo) and sets it as the tokenIn query parameter.
Constructing In-Given-Out Quotes
Conversely, getInGivenOutQuote calculates the required input for a desired output:
async getInGivenOutQuote(tokenOut, tokenInDenom) {
const url = this.url('/router/quote');
url.searchParams.set('tokenOut', `${tokenOut.amount}${tokenOut.denom}`);
url.searchParams.set('tokenInDenom', tokenInDenom);
const response = await fetch(url);
return (await response.json()) as SidecarInGivenOutQuoteResponse;
}
Both methods use the same /router/quote endpoint but vary the parameters to specify the direction of the quote calculation.
Fetching Token Prices
The getPrices method retrieves USD-denominated prices for a list of token denominations:
async getPrices(denoms: string[]) {
const url = this.url('/tokens/prices');
url.searchParams.set('base', denoms.join(','));
const response = await fetch(url);
const priceMap = (await response.json()) as PriceMap;
return denoms.reduce((acc, denom) => {
acc[denom] = getPrice(priceMap, denom) ?? '0';
return acc;
}, {} as Record<string, string>);
}
This method joins the denomination array into a comma-separated string for the base parameter, then uses the getPrice helper from prices.ts to extract individual prices from the nested response map.
Integration with OsmosisAgentToolkit
The OsmosisAgentToolkit class in packages/core/src/toolkit.ts orchestrates the client lifecycle:
export class OsmosisAgentToolkit {
protected readonly _sqsClient = new OsmosisSqsQueryClient();
constructor(mnemonic: string) {
this._account = new Account(mnemonic);
this._accountTool = new AccountTool(this._account, this._sqsClient);
this._swapQuoteInGivenOutTool = new SwapQuoteInGivenOutTool(
this._sqsClient,
this._quoteAmountOutMemory,
);
// …other tools receive the same client instance
}
get sqsClient() { return this._sqsClient; }
}
By instantiating a single OsmosisSqsQueryClient and injecting it into AccountTool, SwapQuoteInGivenOutTool, and SwapQuoteOutGivenInTool, the toolkit ensures consistent configuration and connection pooling across all market data operations.
Practical Code Examples
Getting an Out-Given-In Quote
import { OsmosisSqsQueryClient } from 'osmosis-agent-toolkit/packages/core/src/queries/sqs/client.js';
const sqs = new OsmosisSqsQueryClient();
const tokenIn = { amount: '1000000', denom: 'uosmo' }; // 1 OSMO
const tokenOutDenom = 'ibc/498A0751C798A0D9A389AA3691123DADA57DAA4FE165D5C75894505B876BA6E4'; // Noble USDC
sqs.getOutGivenInQuote(tokenIn, tokenOutDenom)
.then(quote => {
console.log('Expected output amount:', quote.amount_out);
console.log('Route:', quote.route);
})
.catch(err => console.error('Quote failed:', err));
Getting an In-Given-Out Quote
const tokenOut = { amount: '500000', denom: 'ibc/498A0751C798A0D9A389AA3691123DADA57DAA4FE165D5C75894505B876BA6E4' }; // 0.5 USDC
const tokenInDenom = 'uosmo';
sqs.getInGivenOutQuote(tokenOut, tokenInDenom)
.then(quote => console.log('Required OSMO amount:', quote.amount_in));
Fetching Token Prices
const denoms = [
'uosmo',
'ibc/498A0751C798A0D9A389AA3691123DADA57DAA4FE165D5C75894505B876BA6E4',
];
sqs.getPrices(denoms).then(prices => {
console.log('OSMO price:', prices['uosmo']);
console.log('USDC price:', prices['ibc/498A0751C798A0D9A389AA3691123DADA57DAA4FE165D5C75894505B876BA6E4']);
});
Key Source Files Reference
| File | Purpose | Link |
|---|---|---|
packages/core/src/queries/sqs/client.ts |
Implements OsmosisSqsQueryClient with HTTP logic for Sidecar endpoints. |
client.ts |
packages/core/src/queries/sqs/router.ts |
TypeScript interfaces SidecarOutGivenInQuoteResponse and SidecarInGivenOutQuoteResponse for type-safe deserialization. |
router.ts |
packages/core/src/queries/sqs/prices.ts |
PriceMap type and getPrice helper for extracting USD-denominated values from Sidecar price responses. |
prices.ts |
packages/core/src/toolkit.ts |
OsmosisAgentToolkit class that instantiates and injects the SQS client into higher-level tools. |
toolkit.ts |
packages/core/src/tools/swap.ts |
Swap quote tools (SwapQuoteInGivenOutTool, SwapQuoteOutGivenInTool) that consume the SQS client. |
swap.ts |
packages/core/src/tools/account.ts |
AccountTool that retrieves token price data via the SQS client for balance calculations. |
account.ts |
Summary
The OsmosisSqsQueryClient serves as the dedicated HTTP adapter for the Osmosis Sidecar Query Service within the osmosis-agent-toolkit SDK. Key integration points include:
- Direct REST Communication: Constructs URLs for
/router/quoteand/tokens/pricesendpoints, automatically appendinghumanDenoms=falsefor raw denomination handling. - Type-Safe Deserialization: Leverages
SidecarOutGivenInQuoteResponse,SidecarInGivenOutQuoteResponse, andPriceMapinterfaces to ensure compile-time safety. - Singleton Pattern:
OsmosisAgentToolkitinstantiates a single client instance and injects it intoAccountTool,SwapQuoteInGivenOutTool, andSwapQuoteOutGivenInTool, ensuring consistent configuration across the SDK. - Three Core Methods: Exposes
getOutGivenInQuote,getInGivenOutQuote, andgetPricesto fetch live swap estimates and USD-denominated token values.
Frequently Asked Questions
How does OsmosisSqsQueryClient handle authentication?
The OsmosisSqsQueryClient does not require authentication for read-only operations. It communicates with the public Osmosis Sidecar Query Service endpoint at https://sqsprod.osmosis.zone, which exposes market data without API keys. The client simply constructs the request URL and performs an unauthenticated fetch call.
What is the difference between getOutGivenInQuote and getInGivenOutQuote?
getOutGivenInQuote calculates how much of a target token you will receive given a specific input amount and denomination. It sets the tokenIn and tokenOutDenom query parameters. getInGivenOutQuote performs the inverse calculation, determining how much input token is required to obtain a specific output amount, using tokenOut and tokenInDenom parameters instead.
How does the client ensure type safety when parsing SQS responses?
The client uses TypeScript interfaces defined in packages/core/src/queries/sqs/router.ts to cast JSON responses. Methods like getOutGivenInQuote explicitly return SidecarOutGivenInQuoteResponse, while getInGivenOutQuote returns SidecarInGivenOutQuoteResponse. This compile-time typing prevents property access errors and ensures consumers receive objects with guaranteed fields like amount_out, amount_in, and route.
Can I use OsmosisSqsQueryClient independently of OsmosisAgentToolkit?
Yes, the OsmosisSqsQueryClient is a standalone class that can be instantiated directly without the full toolkit. You can import it from packages/core/src/queries/sqs/client.ts and call its methods directly, as shown in the practical code examples. This is useful when you only need price data or swap quotes without the full agent toolkit functionality like transaction signing or account management.
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 →