> ## Documentation Index
> Fetch the complete documentation index at: https://docs.debridge.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Same-Chain Swaps

> An engineering walkthrough for integrating DLN’s same-chain swaps with executable transactions, affiliate fees, and production-grade tracking.

A product surface wants single-network token conversions that behave like reliable transactions, not optimistic quotes. The integration path is
intentionally compact: first, ask for a quote; then, once the sender and recipient are known, request the fully constructed transaction. Under the
hood, DLN simulates routes across multiple aggregators and returns calldata that targets **`DeBridgeRouter`** on EVM, or a serialized transaction on
Solana. The result is an estimation-then-execution loop that stays responsive and grounded in market reality, with the added benefit of **adaptive
slippage** that takes real-time conditions into account.

### What this guide covers

* Endpoints and request shapes to obtain quotes and ready-to-send transactions.
* EVM and Solana submission flows based on the provided TypeScript examples.
* Where affiliate fee parameters plug into the flow.
* Tracking and observability via the Stats API for histories and per-swap lookups.
* Freshness and slippage guidance for resilient UX at scale.

> Reference: [DLN OpenAPI specification](/api-reference/single-chain-swap/get-v10chaintransaction).
> Reference: [Stats API for order tracking](/api-reference/orders/get-filtered-list-of-orders-ordered-by-block-timestamp-desc-max-page-size:-100).

***

## Architecture in brief

A same-chain swap never leaves its origin network. The DLN API handles route discovery and simulation, returning:

* **EVM**: `tx` with `to`, `data`, and (when required) `value`, crafted to call **`DeBridgeRouter`**.
* **Solana**: `tx.data` containing a hex-encoded `VersionedTransaction` that is deserialized, updated with a recent blockhash, signed, and sent.

This design keeps the UI responsive before a wallet is connected, and returns an executable payload once sender and recipient are known.

***

## Endpoints

### Get a quote (estimation)

Use **`GET /v1.0/chain/estimation`** to retrieve a quote for the desired pair. This step is suitable when the wallet is not connected or recipient is
not yet known.

**Minimal request - SOL for USDC on Solana**

```json theme={null}
{
  "chainId": "7565164",
  "tokenIn": "11111111111111111111111111111111", // SOL on Solana
  "tokenInAmount": "200000",
  "tokenOut": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", // USDC on Solana,
  "slippage": "auto" // Default value
}
```

<Note>
  * The response contains pricing, route details, aggregator comparison, and costs metadata used to inform UI and future submission.
  * The recommended value for slippage parameter is `auto`. The API selects a minimum reasonable slippage band from live market conditions and simulations.
</Note>

<Accordion title="Full response schema">
  ```json theme={null}
  {
    "estimation": {
      "tokenIn": {
        "address": "string", // token address
        "name": "string", // token name
        "symbol": "string", // token symbol
        "decimals": 0, // token decimals
        "amount": "string", // input amount
        "approximateUsdValue": 0 // approximate USD value of input amount
      },
      "tokenOut": {
        "address": "string", // token address
        "name": "string", // token name
        "symbol": "string", // token symbol
        "decimals": 0, // token decimals
        "amount": "string", // output amount
        "minAmount": "string", // minimum output amount
        "approximateUsdValue": 0 // approximate USD value of output amount
      },
      "slippage": 0, // slippage percentage (e.g. 0.5 for 0.5%)
      "recommendedSlippage": 0, // recommended slippage percentage based on route simulation and volatility
      "protocolFee": "string", // protocol fee amount in tokenIn
      "estimatedTransactionFee": { // estimated transaction fee details
        "total": "string",
        "details": {
          "giveOrderState": "string",
          "giveOrderWallet": "string",
          "nonceMaster": "string",
          "txFee": "string",
          "priorityFee": "string",
          "gasLimit": "string",
          "gasPrice": "string",
          "baseFee": "string",
          "maxFeePerGas": "string",
          "maxPriorityFeePerGas": "string"
        },
        "approximateUsdValue": 0 // approximate USD value of the total estimated transaction fee
      },
      "costsDetails": [ // Breakdown of costs and fees
        {
          "chain": "string",
          "tokenIn": "string",
          "tokenOut": "string",
          "amountIn": "string",
          "amountOut": "string",
          "type": "string",
          "payload": {
            "feeAmount": "string",
            "feeBps": "string",
            "amountOutBeforeCorrection": "string",
            "estimatedVolatilityBps": "string",
            "actualFeeAmount": "string",
            "actualFeeBps": "string",
            "subsidyAmount": "string",
            "feeApproximateUsdValue": "string"
          }
        }
      ],
      "comparedAggregators": [ // List of queried aggregators and their rates
        {
          "name": "string",
          "amount": "string",
          "approximateUsdValue": 0,
          "priceDrop": 0,
          "imageUrl": "string"
        }
      ]
    }
  }
  ```
</Accordion>

### Get an executable transaction

Use **`GET /v1.0/chain/transaction`** to obtain the **same quote fields** plus a **tx object** ready to be signed and broadcast.

**Minimal request - USDC for MATIC on Polygon**

```json theme={null}
{
  "chainId": "137",
  "tokenIn": "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359", // USDC on Polygon
  "tokenInAmount": "200000",
  "tokenOut": "0x0000000000000000000000000000000000000000", // Native token (MATIC on Polygon)
  "tokenOutRecipient": "<recipient_address>",
  "senderAddress": "<sender_address>",
  "slippage": "auto" // Default value
}
```

**Response Highlights**

```json theme={null}
{
  /* same content as in /estimation */
  "tx": {
    "to": "<DeBridgeRouter_target_on_evm>",
    "data": "0x...",
    "value": "0x..."
  }
}
```

On **Solana**, the `tx` object contains only:

```json theme={null}
{
  /* same content as in /estimation */
  "tx": { "data": "0x<hex_versioned_transaction>" }
}
```

***

## Compared Aggregators

DLN’s same-chain swaps leverage multiple DeFi aggregators to ensure competitive pricing and route diversity. Response payload for both estimation and
transaction endpoints includes the `comparedAggregators` field, which lists the aggregators queried during route discovery. This transparency allows
integrators to understand the aggregator choice and provides insights into the liquidity sources considered for the swap.

## EVM submission flow

The EVM submission sequence mirrors a typical ERC-20 flow plus a single call to `DeBridgeRouter`:

* Fetch estimation with `/v1.0/chain/estimation` to present the quote.
* Request transaction and quote via `/v1.0/chain/transaction` once the sender and recipient are known.
* Ensure allowance for `tokenIn` toward `tx.to` - the `DeBridgeRouter` contract. [Deployed contracts](/dln-details/overview/deployed-contracts) page
  should be consulted for the correct address.
* Send the main transaction using the returned `tx` object.

**Skeleton (TypeScript) aligning with the provided example**

```typescript theme={null}
// Pseudocode stitched to the structure of the provided EVM example
const swap = await createDeBridgeSameChainSwap({
  chainId: "137", // Polygon chainId
  tokenIn: "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359", // USDC on Polygon
  tokenInAmount: "200000",
  tokenOut: "0x0000000000000000000000000000000000000000", // Native token (MATIC on Polygon)
  tokenOutRecipient: senderAddress,
  senderAddress
});

// 1) Validate response
const tx = swap?.tx;
if (!tx?.to || !tx?.data) throw new Error("Invalid tx");

// 2) Approve if needed - only for ERC-20 tokenIn
const required = BigInt(swap.tokenIn.amount);
const currentAllowance = await erc20.allowance(senderAddress, tx.to);
if (currentAllowance < required) {
  const approveTx = await erc20.approve(tx.to, required);
  await approveTx.wait();
}

// 3) Submit the transaction
const sent = await signer.sendTransaction(tx);
const receipt = await sent.wait();

```

#### Complete EVM example

The full, production-ready script (logging, receipt checks, explorer links) is available
[here](https://github.com/debridge-finance/api-integrator-example/tree/master/src/scripts/same-chain/poly-usdc-to-matic.ts) and can
be reused for inspiration in real integrations.

***

## Solana submission flow

The Solana variant returns a serialized `VersionedTransaction` ready to be deserialized, refreshed, signed, and sent:

* Request transaction and quote via `/v1.0/chain/transaction` with Solana chain id.
* Deserialize the hex `tx.data` into a `VersionedTransaction`.
* Refresh `blockhash` with `getLatestBlockhash()` and set `tx.message.recentBlockhash`.
  * Optionally, adjust CU price/limit using a helper (as in the provided example).
* Sign and send the raw transaction, then confirm.

**Skeleton (TypeScript) aligning with the provided Solana example**

```typescript theme={null}
const swap = await createDeBridgeSameChainSwap({
  chainId: "7565164", // Solana chainId
  tokenIn: "11111111111111111111111111111111", // SOL on Solana
  tokenInAmount: "200000",
  tokenOut: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", // USDC on Solana
  tokenOutRecipient: solWallet.publicKey.toBase58(),
  senderAddress: solWallet.publicKey.toBase58()
});

// Deserialize hex-encoded VersionedTransaction
const tx = VersionedTransaction.deserialize(Buffer.from(swap.tx.data.slice(2), "hex"));

// Refresh blockhash and (optionally) adjust CU price/limit, then sign
const { blockhash } = await connection.getLatestBlockhash();
tx.message.recentBlockhash = blockhash;
// updatePriorityFee(tx, NEW_CU_PRICE, NEW_CU_LIMIT); // as in the github example
tx.sign([solWallet]);

// Send and confirm
const sig = await connection.sendRawTransaction(tx.serialize(), { skipPreflight: false });
```

#### Complete Solana example

The full script (simulation, CU sizing, prioritization fee median, and final submission) is available
[here](https://github.com/debridge-finance/api-integrator-example/tree/master/src/scripts/same-chain/sol-usdc-to-sol.ts) and can be
reused for inspiration in real integrations.

***

## Affiliate fees

Affiliate fees are supported in the same-chain flow. The parameters used are `affiliateFeePercent` and `affiliateFeeRecipient`.

More details are available in the the [Same-Chain Affiliate Fees article](/dln-details/affiliates/affiliate-fees#same-chain-affiliate-fees).

<Note>
  The higher the affiliate fee, the worse rates the users using the app will get.
</Note>

***

## Tracking and observability

Tracking is performed with the [**Stats API**](). The default order history endpoints now include same-chain swaps when requested explicitly.

### Wallet histories (filtered list)

For listing same-chain swaps of a single wallet `POST https://dln-api.debridge.finance/api/Orders/filteredList` should be used with a `filterMode:
"SameChain"` parameter.\`:

Allowed values for `filterMode` are:

* `"CrossChain"` (default)
* `"SameChain"`
* `"Mixed"`

**Example request**

```json theme={null}
{ "skip": 0, "take": 1, "maker": "<wallet_address>", "filterMode": "SameChain" }
```

<Accordion title="Example response">
  ```json theme={null}
  {
    "orders": [
      {
        "orderId": { /* order ID object - with bytes, bytes array and string values */ },
        "creationTimestamp": 1759141461, // Unix timestamp
        "giveOfferWithMetadata": {
          "chainId": { /* chain ID object with different representations */ },
          "tokenAddress": { /* token address object - with different representations */ },
          "amount": { /* amount object - with different representations */ },
          "metadata": { /* input token metadata */
            "decimals": 6,
            "name": "Dephaser JPY",
            "symbol": "JPYT",
            "logoURI": null
          },
          "decimals": 6,
          "name": "Dephaser JPY",
          "symbol": "JPYT",
          "logoURI": null
        },
        "takeOfferWithMetadata": {
          "chainId": { /* chain ID object with different representations */ },
          "tokenAddress": { /* token address object - with different representations */ },
          "amount": { /* amount object - with different representations */ },
          "metadata": { /* output token metadata */
            "decimals": 18,
            "name": "AntHive",
            "symbol": "ANTH",
            "logoURI": null
          },
          "decimals": 18,
          "name": "AntHive",
          "symbol": "ANTH",
          "logoURI": null
        },
        "state": "Fulfilled", // Swap state
        "affiliateFee": {
          "beneficiarySrc": { /* affiliate fee beneficiary address object - with bytes, bytes array and string values */ },
          "amount": { /* amount object - with bytes, bytes array and string values */ }
        },
        "createEventTransactionHash": { /* transaction hash object - with bytes, bytes array and string values */ },
        "tradeType": "SameChain"
      }
    ],
    "totalCount": 24
  }
  ```
</Accordion>

<Note>
  Same-chain swaps do not create an on-chain DLN order entity. The Stats API maps same-chain data into an order-like representation purely for
  consistency in histories and dashboards.
</Note>

### Single order lookup

To get details of a single order from the transaction hash, `GET https://dln-api.debridge.finance/api/SameChainSwap/${chainId}/tx/${transactionHash}`
should be used with `chainId` and `transactionHash` parameters. Response structure is identical to the order object in the filtered list.

***

## Freshness and slippage

Quotes are tied to current market conditions and route simulations. Signing and submission should occur shortly after a transaction payload is
received; stale quotes should be refreshed **every 30 seconds**. The recommended value for `slippage` parameter is `"auto"`. The API selects a minimum
reasonable slippage bound based on volatility and route simulation, a design that reduces execution risk without forcing conservative hard-coding.

***

## Example links

* [EVM same-chain swap script (USDC → native on
  Polygon)](https://github.com/debridge-finance/api-integrator-example/tree/master/src/scripts/same-chain/poly-usdc-to-matic.ts).
* [Solana same-chain swap script (USDC →
  native)](https://github.com/debridge-finance/api-integrator-example/tree/master/src/scripts/same-chain/sol-usdc-to-sol.ts).
* [Estimation-only script demonstrating
  `/v1.0/chain/estimation`](https://github.com/debridge-finance/api-integrator-example/tree/master/src/scripts/same-chain/estimation/estimation-example.ts).
* [Filtered history script using `api/Orders/filteredList` with
  `filterMode`](https://github.com/debridge-finance/api-integrator-example/tree/master/src/scripts/same-chain/queries/get-same-chain-swaps.ts).

***

## Production checklist

* Fetch the `estimation` endpoint for quotes before the wallet is connected; request the `transaction` endpoint for quotes and a transaction object
  once `senderAddress` and `tokenOutRecipient` are known.
* Prefer adaptive `slippage` with `auto`.
* On EVM, ensure `tokenIn` allowance toward the `DeBridgeRouter` target in `tx.to`.
* Refresh quotes every 30 seconds if signing is delayed to avoid staleness.
* Use Stats API `filterList` endpoint with `filterMode: "SameChain"` for observability.
