# JavaScript SDK: V2 wallet transactions

`@storm-trade/trading-sdk` builds Storm **v2** transactions: market, limit and stop orders, Stop-Loss and Take-Profit, margin changes, liquidity operations. Every method returns transaction parameters (`to`, `value`, `body`), and you send them with the wallet of your choice: TON Connect in the browser or a `@ton/ton` wallet contract in Node.js.

For Smart Accounts and signed intents, use the [JavaScript V3 guide](sdk_js.md). This page covers the existing V2 exports.

- npm: [@storm-trade/trading-sdk](https://www.npmjs.com/package/@storm-trade/trading-sdk)
- Source and runnable examples: [storm-trade/sdk-js](https://github.com/storm-trade/sdk-js), folder `src/examples`

---

## 📦 Install

```bash
npm install @storm-trade/trading-sdk @ton/ton
```

---

## 🚀 Initialize

This example uses Mainnet. For testing, obtain testnet endpoints during [builder onboarding](https://app.storm.tg/builders) and configure the API, oracle and TON RPC for that network together.

```typescript
import { TonClient } from '@ton/ton';
import { StormTradingSdk } from '@storm-trade/trading-sdk/sdk';
import { StormClient, OracleClient } from '@storm-trade/trading-sdk/api-clients';

const ORACLE_URL = 'https://oracle.storm.tg';
const STORM_API_URL = 'https://api.storm.tg/api';
const TON_CENTER = 'https://toncenter.com/api/v2/jsonRPC';

const tonClient = new TonClient({ endpoint: TON_CENTER, apiKey: TONCENTER_API_KEY });

const sdk = new StormTradingSdk(
  new StormClient(STORM_API_URL, new OracleClient(ORACLE_URL)),
  tonClient,
  TRADER_ADDRESS, // the wallet that will sign, string or Address
);
await sdk.init(); // loads markets, vaults and contract addresses
```

---

## 📈 Orders

Amounts are collateral in the asset's own decimals. Leverage and prices are scaled by 10^9.

```typescript
import { Direction, OrderType } from '@storm-trade/trading-sdk/base-packers';

// Market long, 1 TON collateral, 2x, with SL/TP created on execution
const open = await sdk.createMarketOpenOrder({
  baseAssetName: 'XRP',
  collateralAssetName: 'TON',
  direction: Direction.long,
  amount: 1_000_000_000n,
  leverage: 2_000_000_000n,
  minBaseAssetAmount: 900_000_000n,   // slippage guard, optional
  stopTriggerPrice: 80_000_000_000n,  // optional
  takeTriggerPrice: 120_000_000_000n, // optional
});

// Limit order
const limit = await sdk.createLimitOrder({
  baseAssetName: 'XRP',
  collateralAssetName: 'TON',
  direction: Direction.long,
  amount: 1_000_000_000n,
  leverage: 2_000_000_000n,
  limitPrice: 100_000_000_000n,
});

// Stop-market and stop-limit
await sdk.createStopMarketOrder({ /* ...same fields... */ stopPrice: 105_000_000_000n });
await sdk.createStopLimitOrder({ /* ...same fields... */ stopPrice: 105_000_000_000n, limitPrice: 106_000_000_000n });

// Cancel a resting order by type and index from the position manager
const cancel = await sdk.cancelOrder({
  baseAssetName: 'XRP',
  collateralAssetName: 'TON',
  direction: Direction.long,
  orderType: OrderType.limit,
  orderIndex: 0,
});
```

---

## 🧾 Positions

```typescript
// Stop-Loss / Take-Profit on an open position
await sdk.createStopLossOrder({ baseAssetName: 'XRP', collateralAssetName: 'TON', direction: Direction.long, amount: 1_000_000_000n, triggerPrice: 90_000_000_000n });
await sdk.createTakeProfitOrder({ baseAssetName: 'XRP', collateralAssetName: 'TON', direction: Direction.long, amount: 1_000_000_000n, triggerPrice: 110_000_000_000n });

// Close, size is base asset with 9 decimals
await sdk.createClosePositionOrder({ baseAssetName: 'XRP', collateralAssetName: 'TON', direction: Direction.long, size: 1_000_000_000n });

// Margin. The SDK fetches a signed oracle price for these two calls.
await sdk.addMargin({ baseAssetName: 'XRP', collateralAssetName: 'TON', direction: Direction.long, amount: 500_000_000n });
await sdk.removeMargin({ baseAssetName: 'XRP', collateralAssetName: 'TON', direction: Direction.long, amount: 200_000_000n });
```

---

## 💧 Liquidity

```typescript
await sdk.provideLiquidity({ assetName: 'USDT', amount: 1_000_000n }); // 1 USDT, 6 decimals
await sdk.withdrawLiquidity({ assetName: 'TON', amountOfSLP: 500_000_000n }); // 0.5 SLP
```

---

## 📤 Sending the Transaction

Every call above returns `TXParams`. Nothing is sent until you hand it to a wallet.

**Browser, TON Connect:**

```typescript
import { TonConnectUI } from '@tonconnect/ui';

const tonConnectUI = new TonConnectUI({ manifestUrl: 'https://your-app.com/tonconnect-manifest.json' });

const tx = await sdk.createMarketOpenOrder({ /* ... */ });
await tonConnectUI.sendTransaction({
  validUntil: Math.floor(Date.now() / 1000) + 300,
  messages: [{
    address: tx.to.toString(),
    amount: tx.value.toString(),
    payload: tx.body.toBoc().toString('base64'),
  }],
});
```

**Node.js, hot wallet from a mnemonic:**

```typescript
import { internal, WalletContractV4 } from '@ton/ton';
import { mnemonicToPrivateKey } from '@ton/crypto';

const keyPair = await mnemonicToPrivateKey(MNEMONIC.split(' '));
const wallet = tonClient.open(WalletContractV4.create({ workchain: 0, publicKey: keyPair.publicKey }));

const tx = await sdk.createMarketOpenOrder({ /* ... */ });
await wallet.sendTransfer({
  seqno: await wallet.getSeqno(),
  secretKey: keyPair.secretKey,
  messages: [internal(tx)],
});
```

Pass the wallet's address as `TRADER_ADDRESS` when constructing the SDK, otherwise the position manager lookups point at the wrong account.

---

## 🧑‍💻 Examples in the Repository

`src/examples` in [sdk-js](https://github.com/storm-trade/sdk-js) contains runnable scripts grouped by `orders`, `liquidity` and `ton-connect`, plus a `utils/sdk-manager.ts` helper that wraps the Node.js sending pattern above. Copy the closest script and replace the environment block.
