@sperax/tool-swap
v0.2.1
Published
Swap tokens across DEXs with best pricing and MEV protection — an agent tool for SperaxOS.
Maintainers
Readme
@sperax/tool-swap
Swap tokens across DEXs with best pricing and MEV protection
Swap is an agent tool from SperaxOS, packaged headless so you can call
it from any agent framework. It ships two things: the manifest — a JSON-Schema function
definition a model can call — and the executor that runs the call against the real API.
There is no UI layer and no framework lock-in. It works anywhere TypeScript runs.
Install
npm install @sperax/tool-swapUsage
Call it directly
import { swapExecutor } from '@sperax/tool-swap';
const result = await swapExecutor.invoke('getQuote', {"amount":"<amount>","chainId":1}, {
messageId: 'msg-1',
});
console.log(result.content); // prose summary written for the model to read
console.log(result.state); // typed data payload for your own UIGive it to a model
import Anthropic from '@anthropic-ai/sdk';
import { SwapManifest, swapExecutor } from '@sperax/tool-swap';
const client = new Anthropic();
const response = await client.messages.create({
model: 'claude-opus-4-8',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Ask something this tool can answer' }],
tools: SwapManifest.api.map((api) => ({
name: api.name,
description: api.description,
input_schema: api.parameters,
})),
});
for (const block of response.content) {
if (block.type !== 'tool_use') continue;
const result = await swapExecutor.invoke(block.name, block.input, { messageId: response.id });
console.log(result.content);
}SwapManifest.api is already in JSON-Schema form, so it maps onto any tool-calling API —
Anthropic, OpenAI, the Vercel AI SDK, or an MCP server — without translation.
Every executor returns a BuiltinToolResult — { success, content, state }. content is
prose written for the model to read; state is the typed data payload for your own code.
Executors never throw: a failed call comes back as { success: false, content: '<reason>' },
so a network blip degrades the answer instead of crashing the agent loop.
Configuration — required
This tool needs a backend you control. It will not work on a bare npm install alone.
The upstream API requires a secret key. That key is deliberately not bundled here —
shipping it in an npm package would leak it to every consumer. Instead the executor calls
a SperaxOS /webapi/* route, which holds the key server-side and injects it. That route
is session-authenticated, so the public deployment at https://chat.sperax.io (the
default origin) answers 401 to anonymous callers.
To use this tool you need one of:
- a SperaxOS deployment of your own, or
- any HTTP endpoint that implements the same request shape and supplies the key.
Point the package at it before importing the tool — the URL is resolved once, when the module first loads:
SPERAX_API_BASE_URL=https://my-speraxos.example.comor in code:
import { configureSperaxApi } from '@sperax/agent-tools-core';
configureSperaxApi({ baseUrl: 'https://my-speraxos.example.com' });
// import the tool only after configuring, so the path resolves against your origin
const { swapExecutor } = await import('@sperax/tool-swap');Inside a browser that already serves those routes at its own origin, requests stay same-origin and no configuration is needed.
If you want a tool that runs with zero setup, use one of the standalone tools — those call public APIs directly and need no key, no origin, and no backend.
Tool identifier
sperax-swap
API reference
getQuote
Get a swap quote showing the best price for exchanging one token for another. Returns rate, gas cost, price impact, and minimum received. Always use this before executing a swap.
| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| amount | string | yes | Amount of source token to swap (human-readable, e.g. "1.5" for 1.5 ETH). |
| chainId | number | no | Chain ID (1=Ethereum, 42161=Arbitrum, 137=Polygon, 8453=Base, 10=Optimism). Default: 42161 (Arbitrum). |
| fromToken | string | yes | Source token symbol (e.g. "ETH", "USDC", "SPA"). |
| slippage | number | no | Slippage tolerance in percent (e.g. 0.5 for 0.5%). Default: 0.5. |
| toChainId | number | no | Destination chain ID for cross-chain swaps/bridges. Defaults to same as chainId (same-chain swap). Example: swap ETH on Ethereum (chainId=1) to USDC on Arbitrum (toChainId=42161). |
| toToken | string | yes | Destination token symbol (e.g. "USDC", "ETH", "USDs"). |
executeSwap
Execute a previously quoted swap. Requires the quoteId from getQuote and the user wallet address. ONLY call this after the user has explicitly confirmed the swap. The quoteData field is automatically populated from the quote state for serverless resilience.
| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| quoteData | object | no | Embedded quote parameters for serverless resilience. Automatically populated from getQuote state. Contains fromChain, toChain, fromToken, toToken, fromAmount, slippage. |
| quoteId | string | yes | Quote ID returned from getQuote. |
| walletAddress | string | yes | User wallet address (0x...). |
getSwapStatus
Check the status of a swap transaction by its hash.
| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chainId | number | no | Chain ID where the swap was executed. |
| txHash | string | yes | Transaction hash (0x...). |
getSupportedChains
Get the list of blockchain networks supported for swapping.
Takes no parameters.
getSupportedTokens
Get supported tokens for swapping on a specific chain. Optionally filter by search query.
| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chainId | number | no | Chain ID to list tokens for. Default: 42161 (Arbitrum). |
| search | string | no | Search query to filter tokens by name or symbol. |
checkBridgeRoute
Check if a cross-chain bridge route exists between two chains for a given token and amount. Returns route availability, estimated time, gas cost, and bridge name. Use this when a user asks "can I bridge X from chain A to chain B?".
| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| amount | string | yes | Amount to bridge in human-readable units (e.g. "100"). |
| chainId | number | yes | Source chain ID (e.g. 1=Ethereum, 42161=Arbitrum, 137=Polygon). |
| fromToken | string | yes | Source token symbol (e.g. "USDC", "ETH"). |
| toChainId | number | yes | Destination chain ID. |
| toToken | string | yes | Destination token symbol (e.g. "USDC", "ETH"). |
bridgeTokens
Bridge tokens from one chain to another. Returns an unsigned transaction for wallet signing. ALWAYS use checkBridgeRoute first to verify the route exists, then confirm with the user before executing. REAL TRANSACTION.
| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| amount | string | yes | Amount to bridge in human-readable units. |
| chainId | number | yes | Source chain ID. |
| fromToken | string | yes | Source token symbol. |
| slippage | number | no | Slippage tolerance in percent. Default: 0.5. |
| toChainId | number | yes | Destination chain ID. |
| toToken | string | yes | Destination token symbol. |
| walletAddress | string | yes | User wallet address (0x...). |
getBridgeStatus
Check the status of a cross-chain bridge transaction. Shows source/destination tx hashes, amounts, and whether the bridge is still pending, complete, or failed. Use this to track bridge progress.
| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chainId | number | yes | Source chain ID where the bridge transaction was initiated. |
| toChainId | number | yes | Destination chain ID. |
| txHash | string | yes | Transaction hash of the bridge transaction (0x...). |
Types
Shared types come from @sperax/agent-tools-core:
BuiltinToolManifest, BuiltinToolResult, BuiltinToolContext, and the BaseExecutor
class every tool executor extends.
Related
@sperax/agent-tools-core— the tool contract- All SperaxOS agent tools — tool-swap is one of many
- SperaxOS — the agent workspace these tools were built for
License
Apache-2.0
