> 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/omniston/sdk/nodejs.md).

# TypeScript and JavaScript

Receive quotes, submit swaps or orders, and track settlement with the base Omniston SDK and API v1beta8.

The base `@ston-fi/omniston-sdk` works in frontend and backend JavaScript/TypeScript integrations. This guide prepares an RFQ, builds the selected settlement, and tracks its result. The examples use API v1beta8 and SDK 0.8.x; choose the [environment](/developer-section/omniston/environments.md) before creating a client.

Prepare the [input and output assets](/developer-section/omniston/chains.md), source wallet, and destination address. See [API amounts](/developer-section/omniston/swap/v1beta8.md#amounts-and-fee-fields) for amount fields and [wallet integration](/developer-section/omniston/sdk.md#wallet-integration) for signing.

The code sections show separate settlement branches. Each starts from a valid `quote` selected from `quoteUpdated`. Follow the matching branch and supply wallet addresses and signing inputs from your application. In `v1beta8`, the main integration flow is:

1. prepare `settlementParams` for the settlement methods you want to allow
2. subscribe to RFQ updates and select a quote from the stream
3. branch on `quote.settlementData?.$case`
4. build and sign either a swap flow or an order flow
5. track the resulting settlement

An end-to-end open source reference implementation is also available in our example app: [examples/react-app](https://github.com/ston-fi/omniston-sdk/tree/main/examples/react-app)

## Installation

* [Source code](https://github.com/ston-fi/omniston-sdk/tree/main/packages/omniston-sdk)
* [@ston-fi/omniston-sdk](https://www.npmjs.com/package/@ston-fi/omniston-sdk) NPM Package

Install the SDK in your project:

```sh
npm install @ston-fi/omniston-sdk
```

## Creating an instance

Create an `Omniston` instance pointing to the desired API endpoint.

```ts
import { Omniston } from "@ston-fi/omniston-sdk";

const omniston = new Omniston({
  apiUrl: "wss://omni-ws.ston.fi",
});
```

For the **sandbox** environment, use:

```ts
const omniston = new Omniston({
  apiUrl: "wss://omni-ws-sandbox.ston.fi",
});
```

## Preparing settlement params

`settlementParams` enables the settlement branches your application supports:

* Swap: immediate execution through swap routes.
* Order: escrow-backed or signed orders, including HTLC cross-chain settlement.
* Both: accept quotes for either branch.

After selecting a quote, follow its returned settlement branch.

```ts
import {
  type SettlementParams,
  type SwapSettlementParams,
  type OrderSettlementParams,
} from "@ston-fi/omniston-sdk";

const swapOnlySettlementParams: SettlementParams[] = [
  {
    params: {
      $case: "swap",
      value: {
        maxPriceSlippagePips: 10_000, // 1%
        flexibleIntegratorFee: true,
      } satisfies SwapSettlementParams,
    },
  },
];

const orderOnlySettlementParams: SettlementParams[] = [
  {
    params: {
      $case: "order",
      value: {} satisfies OrderSettlementParams,
    },
  },
];

const swapAndOrderSettlementParams: SettlementParams[] = [
  ...swapOnlySettlementParams,
  ...orderOnlySettlementParams,
];
```

## Quote receiving based on parameters

Call `requestForQuote()` with the prepared parameters and subscribe to its stream. Process `quoteUpdated` events as pricing updates and select a quote for settlement.

```ts
import type { AssetId, QuoteRequest } from "@ston-fi/omniston-sdk";

const inputAsset: AssetId = {
  chain: {
    $case: "ton",
    value: {
      kind: {
        $case: "jetton",
        value: "EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs", // example: USDT
      },
    },
  },
};

const outputAsset: AssetId = {
  chain: {
    $case: "ton",
    value: {
      kind: {
        $case: "jetton",
        value: "EQA2kCVNwVsil2EM2mB0SkXytxCqQjS4mttjDpnXmwG9T6bO", // example: STON
      },
    },
  },
};

const quoteRequest: QuoteRequest = {
  inputAsset,
  outputAsset,
  amount: {
    $case: "inputUnits",
    value: "1000000",
  },
  settlementParams: swapAndOrderSettlementParams,
};

const rfqSubscription = omniston.requestForQuote(quoteRequest).subscribe({
  next(event) {
    switch (event?.$case) {
      case "ack":
        console.log("RFQ id:", event.value.rfqId);
        break;
      case "quoteUpdated":
        console.log("Received quote:", event.value.quoteId);
        break;
      case "noQuote":
        console.log(`No quote available for RFQ ${event.rfqId}`);
        break;
      case "unsubscribed":
        console.log("Quote stream was closed by server");
        break;
    }
  },
  error(error) {
    console.error("RFQ stream failed", error);
  },
});
```

## Settlement flows

Once you have selected a `quote` from the RFQ stream, branch on `quote.settlementData?.$case` and follow the corresponding settlement flow.

### Swap quotes

#### Build and sign the transaction

Once you have selected a `quote` from the stream and it uses swap settlement, build a TON transaction with `tonBuildSwap()`, then pass the resulting messages to the wallet or signing library you use in your application.

```ts
import { isSwapQuote, type ChainAddress } from "@ston-fi/omniston-sdk";

if (!isSwapQuote(quote)) {
  throw new Error("Expected a swap quote");
}

const traderAddress: ChainAddress = {
  chain: {
    $case: "ton",
    value: "EQ...",
  },
};

// This branch builds a TON-source swap. `quote` is the selected swap quote.
const swapTx = await omniston.tonBuildSwap({
  quoteId: quote.quoteId,
  transferSrcAddress: traderAddress,
  refundSrcAddress: traderAddress,
  gasExcessAddress: traderAddress,
  traderDstAddress: traderAddress,
});

// Pass all `swapTx.messages` to your wallet; preserve order and optional state init.
```

Use the [TON wallet guide](/developer-section/omniston/sdk/ton.md) to send these messages and derive `outgoingTxQuery` from the wallet result.

#### Tracking

After the swap transaction is sent, track the swap with `swapTrack()`. You need the `quoteId`, the trader wallet address, and an identifier that lets Omniston find the outgoing transaction.

```ts
const swapTrackStream = omniston.swapTrack({
  quoteId: quote.quoteId,
  traderAddress,
  outgoingTxQuery, // tx hash, message hash, or outgoing message body
});

swapTrackStream.subscribe({
  next(event) {
    switch (event?.$case) {
      case "awaitingTransfer":
        console.log("Waiting for transfer");
        break;
      case "progress":
        console.log("Swap status:", event.value.status);
        break;
      case "unsubscribed":
        console.log("Swap tracking stream closed");
        break;
    }
  },
});
```

### Order quotes

#### Build and sign the transaction

Once you have selected a `quote` from the stream and it uses order settlement, the build-and-sign flow depends on the source chain.

For TON-source order settlement, build an escrow transfer and send all its messages. The following example uses a TON destination too; for cross-chain orders set `traderDstAddress` to the actual destination-chain address. For trader-managed HTLC secrets, supply hashes matching the quote’s hashing function and execution indexing; see [TON wallet integration](/developer-section/omniston/sdk/ton.md).

```ts
import {
  isHtlcOrderQuote,
  isOrderQuote,
  type HtlcSecrets,
} from "@ston-fi/omniston-sdk";

if (!isOrderQuote(quote)) {
  throw new Error("Expected an order quote");
}

const tonOrderTx = await omniston.tonBuildEscrowTransfer({
  quoteId: quote.quoteId,
  ownerSrcAddress: traderAddress,
  transferSrcAddress: traderAddress,
  refundSrcAddress: traderAddress,
  gasExcessAddress: traderAddress,
  traderDstAddress: traderAddress,
});

// `tonOrderTx.messages` should be signed and sent with the TON wallet package used by your project.
```

For EVM order settlement, build the order payload, sign it with your EVM wallet, and register the signed order with Omniston:

```ts
if (!isOrderQuote(quote)) {
  throw new Error("Expected an order quote");
}

const evmTraderAddress: ChainAddress = {
  chain: {
    $case: "base",
    value: "0x...",
  },
};

const htlcSecrets: HtlcSecrets | undefined = isHtlcOrderQuote(quote)
  ? {
      secretMode: {
        $case: "provided",
        value: {
          hashes: myGeneratedHashlocks,
        },
      },
    }
  : undefined;

const orderPayload = await omniston.evmBuildOrderPayload({
  quoteId: quote.quoteId,
  ownerSrcAddress: evmTraderAddress,
  traderDstAddress: traderAddress,
  htlcSecrets,
  traderDstDiscloseAddress: traderAddress,
});

// Application wallet adapter: return the SignedOrder type required by this payload.
// See the EVM wallet/signature guide linked below.
const signedOrder = await buildSignedOrderSomehow(orderPayload);

await omniston.orderRegisterSignedOrder({
  quoteId: quote.quoteId,
  ownerSrcAddress: evmTraderAddress,
  signedOrder,
  serializedOrderDetails: orderPayload.serializedOrderDetails,
});
```

Use the [EVM wallet guide](/developer-section/omniston/sdk/evm.md) for wallet kind, allowance, and signing; use the [TRON guide](/developer-section/omniston/sdk/tron.md) for a TRON source. `myGeneratedHashlocks` and `mySecretBytes` are hashes and preimages generated by your application.

#### Tracking

Once the order is submitted, use `orderTrack()` to monitor its lifecycle. Here `sourceOwnerAddress` is the source-side owner used in the selected build branch: `traderAddress` for the TON example or `evmTraderAddress` for the EVM example. For HTLC-based partial fills, the application must generate secrets on its own, pass their hashes when building the order payload, and later disclose the original secrets with `orderDiscloseHtlcSecret()` when executions reach the appropriate phase.

```ts
const orderTrackStream = omniston.orderTrack({
  quoteId: quote.quoteId,
  traderAddress: sourceOwnerAddress,
});

orderTrackStream.subscribe({
  next(event) {
    switch (event?.$case) {
      case "order":
        console.log("Order status:", event.value.status);
        console.log("Executions:", event.value.executions.length);
        break;
      case "unsubscribed":
        console.log("Order tracking stream closed");
        break;
    }
  },
});
```

For trader-managed HTLC secrets, call `orderDiscloseHtlcSecret()` after the destination position reaches the required completion phase. See [Secrets and disclosure](/developer-section/omniston/how-omniston-works.md#when-to-call-orderdisclosehtlcsecret):

```ts
await omniston.orderDiscloseHtlcSecret({
  quoteId: quote.quoteId,
  executionIndex: 0,
  secret: mySecretBytes,
});
```

## Active orders list

Call `orderGetActive()` to restore active orders for a trader. It returns a snapshot. Call it on demand or poll it for periodic refreshes.

```ts
import type { ChainAddress } from "@ston-fi/omniston-sdk";

const traderAddress: ChainAddress = {
  chain: {
    $case: "ton",
    value: "EQ...",
  },
};

const activeOrders = await omniston.orderGetActive({
  traderAddress,
});

for (const activeOrder of activeOrders.activeOrders) {
  console.log("Order quote id:", activeOrder.quote.quoteId);
  console.log("Order status:", activeOrder.order.status);
}
```

## Results, recovery, and cleanup

Use `swapTrack()` for swap settlement and `orderTrack()` for order settlement. Read settlement status from these streams after submission. Keep the last order snapshot when a stream closes; see [Settlement lifecycle](/developer-section/omniston/how-omniston-works.md#reading-completion-in-order-settlement) for statuses and execution phases.

Use `orderGetActive()` to recover active orders after reconnecting.

Unsubscribe when pricing or tracking is no longer needed. Close a dedicated client with `omniston.transport.close()` after disposing its subscriptions. Keep a shared client open until all its consumers have finished. A `noQuote` event means no executable quote is currently available for the RFQ.


---

# 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/omniston/sdk/nodejs.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.
