> For the complete documentation index, see [llms.txt](https://docs.ston.fi/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.ston.fi/developer-section/dex/sdk/swap.md).

# Swap

Build and submit a direct DEX v2 swap, then inspect its result.

Swap TON or jettons directly through a STON.fi pool. This guide uses DEX v2 contracts and SDK 2.x. See [Setup and environments](/developer-section/dex/sdk/v2.md) for client setup and router selection.

{% hint style="info" %}
**Learn More**

* **Blog**: [Easy DeFi for TON Projects: STON.fi Integration](https://blog.ston.fi/easy-defi-for-ton-projects-stonfi-integration/)
  {% endhint %}

## Mainnet-first workflow

STON.fi’s REST API (`api.ston.fi`) serves mainnet data. For a mainnet swap:

1. Simulate the swap to obtain routing metadata (expected amounts, vault info, and the full router object).
2. Feed `simulationResult.router` directly into `dexFactory()` to build contracts dynamically.
3. Generate the swap transaction parameters with the router helpers.

```typescript
import { dexFactory, Client } from "@ston-fi/sdk";
import { StonApiClient } from "@ston-fi/api";

const tonClient = new Client({
  endpoint: "https://toncenter.com/api/v2/jsonRPC",
});

const apiClient = new StonApiClient();

// 1. Simulate the swap to discover routing details
const simulationResult = await apiClient.simulateSwap({
  offerAddress: "<from asset address or 'ton'>",
  askAddress: "<to asset address>",
  offerUnits: "<amount in blockchain units>",
  slippageTolerance: "0.01",
});

// 2. Router metadata ships with the simulation result
const { router: routerInfo } = simulationResult;
const dexContracts = dexFactory(routerInfo);

// 3. Open the router contract
const router = tonClient.open(
  dexContracts.Router.create(routerInfo.address)
);

// Optional helper when TON is part of the route
const proxyTon = dexContracts.pTON.create(routerInfo.ptonMasterAddress);
```

The `simulationResult` object contains `offerUnits`, `minAskUnits`, `offerAddress`, `askAddress`, and `router`. Reuse those values when building the actual swap transaction to ensure the signed transaction matches the simulated path.

> **Integrator fees:** See [DEX fees](/developer-section/dex/fees.md#integrator-fees) for the direct DEX fee model.

## Swap TON to jetton

```typescript
const txParams = await router.getSwapTonToJettonTxParams({
  userWalletAddress: "<your wallet address>",
  offerAmount: simulationResult.offerUnits,
  minAskAmount: simulationResult.minAskUnits,
  askJettonAddress: simulationResult.askAddress,
  proxyTon,
  // Optional referral parameters:
  referralAddress: "<your referral TON address>",
  referralValue: 10, // e.g. 10 => 0.1% fee
  queryId: 12345,
});
```

Send the resulting parameters using your preferred wallet integration. See our [transaction sending guide](/developer-section/common/transaction-sending.md) for wallet-specific examples.

## Swap jetton to jetton

```typescript
const txParams = await router.getSwapJettonToJettonTxParams({
  userWalletAddress: "<your wallet address>",
  offerJettonAddress: simulationResult.offerAddress,
  askJettonAddress: simulationResult.askAddress,
  offerAmount: simulationResult.offerUnits,
  minAskAmount: simulationResult.minAskUnits,
  // Optional referral parameters:
  referralAddress: "<your referral TON address>",
  referralValue: 25, // e.g. 25 => 0.25% fee
  queryId: 12345,
});
```

## Swap jetton to TON

```typescript
const txParams = await router.getSwapJettonToTonTxParams({
  userWalletAddress: "<your wallet address>",
  offerJettonAddress: simulationResult.offerAddress,
  offerAmount: simulationResult.offerUnits,
  minAskAmount: simulationResult.minAskUnits,
  proxyTon, // reuse from the common setup
  // Optional referral parameters:
  referralAddress: "<your referral TON address>",
  referralValue: 50, // e.g. 50 => 0.5% fee
  queryId: 12345,
});
```

Convert the built parameters to your wallet's message format using the [transaction sending guide](/developer-section/common/transaction-sending.md).

## Testnet swaps (manual setup)

To run v2 swaps on TON testnet, configure testnet contracts and provide liquidity to the pools. The `api.ston.fi` endpoint serves mainnet data.

To mirror the three swap types from the mainnet example, testers often run the following sequence on testnet:

1. swap 1 TON to TesREED (ton -> jetton)
2. swap TesREED to TestBlue (jetton -> jetton)
3. swap TestBlue back to TON (jetton -> ton)

```typescript
import { TonClient, toNano } from "@ton/ton";
import { DEX, pTON } from "@ston-fi/sdk";

const client = new TonClient({
  endpoint: "https://testnet.toncenter.com/api/v2/jsonRPC",
});

const router = client.open(
  DEX.v2_1.Router.CPI.create("kQALh-JBBIKK7gr0o4AVf9JZnEsFndqO0qTCyT-D-yBsWk0v") // CPI Router v2.1.0 (testnet)
);

const proxyTon = pTON.v2_1.create("kQACS30DNoUQ7NfApPvzh7eBmSZ9L4ygJ-lkNWtba8TQT-Px"); // pTON v2.1.0 (testnet)

const txParams = await router.getSwapTonToJettonTxParams({
  userWalletAddress: "<your testnet wallet>",
  proxyTon,
  offerAmount: toNano("1"),
  askJettonAddress: "kQDLvsZol3juZyOAVG8tWsJntOxeEZWEaWCbbSjYakQpuYN5", // TesREED jetton (testnet)
  minAskAmount: "1",
});
```

This manual approach is strictly **for testing**. Switch back to the API-driven workflow for anything mainnet facing.

## Check the result

An implementation reference is available in the [swap demo](https://sdk-demo-app.ston.fi/swap) and [SDK example application](https://github.com/ston-fi/sdk/tree/main/examples/next-js-app).

Resolve the submitted wallet transaction with the [transaction query](/developer-section/dex/api/reference.md#transaction-query), then inspect swap status/action-tree data for that operation. An API lookup with no result yet is not proof of failure. Refresh expired simulations before a new submission; do not submit again solely because the UI timed out.

Use the [REST transaction action tree](/developer-section/dex/api/reference.md#transaction-action-tree) to inspect the submitted operation.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.ston.fi/developer-section/dex/sdk/swap.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
