@temple-digital-group/temple-canton-js 2.0.0-beta.5 → 2.0.0-beta.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -51,7 +51,7 @@ setWalletAdapter(loop);
51
51
  | USDCx | Utility | testnet, mainnet |
52
52
  | CBTC | Utility | testnet, mainnet |
53
53
 
54
- > **Symbol normalization:** `CC` is automatically normalized to `Amulet` in all API methods that accept a symbol (e.g. `CC/USDCx` becomes `Amulet/USDCx`).
54
+ > **Symbol normalization:** Use `CC` for Canton Coin in all SDK methods. The SDK handles the internal conversion to `Amulet` where required by the ledger. The `Amulet` symbol is deprecated all API responses now return `CC`.
55
55
 
56
56
  ## Supported Trading Pairs
57
57
 
@@ -66,7 +66,7 @@ The v2 flow covers the full trading lifecycle: onboarding, deposits, trading, an
66
66
  1. Check onboarding → isUserOnboarded(party)
67
67
  If NOT onboarded → onboardUser(party)
68
68
 
69
- 2. Deposit funds → depositFunds({ sender, assetId, amount, holdingCids, ... })
69
+ 2. Deposit funds → deposit(amount, symbol)
70
70
 
71
71
  3. Check balance → getTradingBalance()
72
72
 
@@ -98,35 +98,30 @@ if (!delegation) {
98
98
 
99
99
  ### 2. Deposit Funds
100
100
 
101
- Deposit funds into the user's trading balance. Use `prepareDepositHoldings` to resolve the holdings for the deposit amount.
101
+ The simplest way to deposit is the `deposit()` helper pass the amount and symbol, and it handles everything:
102
102
 
103
103
  ```javascript
104
- import { prepareDepositHoldings, depositFunds } from "@temple-digital-group/temple-canton-js";
105
-
106
- // Prepare holdings for the deposit
107
- const depositOpts = await prepareDepositHoldings(100, "USDCx");
104
+ import { deposit } from "@temple-digital-group/temple-canton-js";
108
105
 
109
- // Submit the deposit
110
- const result = await depositFunds(depositOpts);
106
+ const result = await deposit(100, "USDCx");
107
+ // or
108
+ const result = await deposit(10, "CC");
111
109
  ```
112
110
 
113
- `depositFunds` accepts:
111
+ `deposit()` requires the wallet adapter to be connected. It:
112
+ 1. Checks your CC balance to ensure at least 10 CC is reserved for transaction fees
113
+ 2. For utility deposits (USDCx, CBTC), verifies you have enough of the token **and** 10 CC for fees
114
+ 3. Selects the right UTXOs from your wallet
115
+ 4. Submits the deposit allocation
116
+
117
+ If you need more control, use `prepareDepositHoldings` + `depositFunds` directly:
114
118
 
115
- | Option | Required | Description |
116
- | ---------------- | -------- | ---------------------------------------------------------- |
117
- | `sender` | Yes | Party allocating the assets |
118
- | `assetId` | Yes | Instrument symbol (`USDCx`, `Amulet`, `CBTC`) |
119
- | `amount` | Yes | Amount to allocate |
120
- | `holdingCids` | Yes | Holding contract IDs that fund the allocation |
121
- | `receiver` | No | Counterparty (defaults to sender) |
122
- | `settlementId` | No | Reference ID for the settlement |
123
- | `transferLegId` | No | Unique ID for this transfer leg |
124
- | `allocateBefore` | No | ISO timestamp; allocation deadline (default: +1h) |
125
- | `settleBefore` | No | ISO timestamp; settlement deadline (default: +2h) |
126
- | `disclosures` | No | Pre-fetched Amulet disclosures (for FE without API access) |
127
- | `userId` | No | User ID (falls back to wallet adapter / config) |
119
+ ```javascript
120
+ import { prepareDepositHoldings, depositFunds } from "@temple-digital-group/temple-canton-js";
128
121
 
129
- For Amulet deposits, the SDK fetches disclosures automatically. You can also pass them manually via `opts.disclosures`.
122
+ const depositOpts = await prepareDepositHoldings(100, "USDCx");
123
+ const result = await depositFunds(depositOpts);
124
+ ```
130
125
 
131
126
  ### 3. Trading Balance
132
127
 
@@ -144,14 +139,21 @@ Use this to check available funds before placing orders or withdrawals.
144
139
  ```javascript
145
140
  import { createOrderRequest } from "@temple-digital-group/temple-canton-js";
146
141
 
142
+ // Single order
147
143
  const result = await createOrderRequest({
148
- symbol: "Amulet/USDCx",
144
+ symbol: "CC/USDCx",
149
145
  side: "buy",
150
146
  quantity: 10.5,
151
147
  price: 1.25,
152
148
  order_type: "limit",
153
- expires_at: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
154
149
  });
150
+
151
+ // Batch orders (max 20)
152
+ const batchResult = await createOrderRequest([
153
+ { symbol: "CC/USDCx", side: "buy", quantity: 100, price: 1.25, order_type: "limit" },
154
+ { symbol: "CC/USDCx", side: "sell", quantity: 50, price: 1.50, order_type: "limit" },
155
+ ]);
156
+ // Returns { success, request_ids, count, message }
155
157
  ```
156
158
 
157
159
  ### 5. Cancel Orders
@@ -159,11 +161,15 @@ const result = await createOrderRequest({
159
161
  ```javascript
160
162
  import { cancelOrder, cancelAllOrders } from "@temple-digital-group/temple-canton-js";
161
163
 
162
- // Cancel a specific order
163
- await cancelOrder("order-id-123");
164
+ // Cancel a single order
165
+ await cancelOrder("ord_abc123");
166
+
167
+ // Cancel multiple orders (max 20)
168
+ await cancelOrder(["ord_abc123", "ord_def456", "ord_ghi789"]);
169
+ // Returns { success, canceled, already_queued, not_found, message }
164
170
 
165
171
  // Cancel all orders for a symbol
166
- await cancelAllOrders({ symbol: "Amulet/USDCx" });
172
+ await cancelAllOrders({ symbol: "CC/USDCx" });
167
173
 
168
174
  // Cancel ALL orders
169
175
  await cancelAllOrders();
@@ -368,8 +374,9 @@ const unsubOrder = ws.onUserEvent("user_order", (data) => { ... });
368
374
 
369
375
  | Function | Provider | Description |
370
376
  | ----------------------------------------- | -------- | ----------------------------------------------------- |
371
- | `prepareDepositHoldings(amount, assetId)` | **W** | Resolve holdings for a deposit amount |
372
- | `depositFunds(opts)` | **W** | Deposit funds into the user's trading balance |
377
+ | `deposit(amount, symbol)` | **W** | Deposit funds (validates balance, reserves 10 CC for fees) |
378
+ | `prepareDepositHoldings(amount, assetId)` | **W** | Resolve holdings for a deposit amount (low-level) |
379
+ | `depositFunds(opts)` | **W** | Submit deposit allocation (low-level) |
373
380
  | `withdrawFunds({ asset_id, amount })` | **W** | Withdraw available trading balance back to wallet |
374
381
  | `emergencyWithdrawFunds(opts)` | **W** | Cancel all orders and withdraw everything immediately |
375
382
 
@@ -413,13 +420,15 @@ const unsubOrder = ws.onUserEvent("user_order", (data) => { ... });
413
420
 
414
421
  #### Trading
415
422
 
416
- | Function | Description |
417
- | --------------------------- | ------------------------------------------------------ |
418
- | `createOrderRequest(opts)` | Place a buy/sell order via the trading backend |
419
- | `cancelOrder(orderId)` | Cancel a specific order |
420
- | `cancelAllOrders(options?)` | Cancel all orders (options: `symbol` filter) |
421
- | `getTradingBalance()` | Get user's trading balance (unlocked/locked/in-flight) |
422
- | `getActiveOrders(options?)` | Get active orders (options: `symbol`, `limit`) |
423
+ | Function | Description |
424
+ | ----------------------------------- | ------------------------------------------------------ |
425
+ | `createOrderRequest(opts)` | Place a single order |
426
+ | `createOrderRequest(opts[])` | Place up to 20 orders in one request |
427
+ | `cancelOrder(orderId)` | Cancel a single order |
428
+ | `cancelOrder(orderIds[])` | Cancel up to 20 orders in one request |
429
+ | `cancelAllOrders(options?)` | Cancel all orders (options: `symbol` filter) |
430
+ | `getTradingBalance()` | Get user's trading balance (unlocked/locked/in-flight) |
431
+ | `getActiveOrders(options?)` | Get active orders (options: `symbol`, `limit`) |
423
432
 
424
433
  #### Withdrawals
425
434
 
@@ -1,5 +1,5 @@
1
- import type { ApiError, Ticker, OrderBook, OrderBookOptions, SymbolConfig, OpenInterest, Trade, RecentTradesOptions, ActiveOrder, ActiveOrdersOptions, CancelOrderResponse, CancelAllOrdersOptions, CancelAllOrdersResponse, CreateOrderRequestOpts, CreateOrderRequestResponse, DelegationResponse, WithdrawalResponse, WithdrawalStatusResponse, TradingBalanceResponse, AmuletDisclosure, DisclosuresResponse } from "./types.js";
2
- export type { ApiError, Ticker, OrderBook, OrderBookOptions, SymbolConfig, OpenInterest, Trade, RecentTradesOptions, ActiveOrder, ActiveOrdersOptions, CancelOrderResponse, CancelAllOrdersOptions, CancelAllOrdersResponse, CreateOrderRequestResponse, DelegationResponse, WithdrawalResponse, WithdrawalStatusResponse, TradingBalanceResponse, AmuletDisclosure, DisclosuresResponse, };
1
+ import type { ApiError, Ticker, OrderBook, OrderBookOptions, SymbolConfig, OpenInterest, Trade, RecentTradesOptions, ActiveOrder, ActiveOrdersOptions, CancelOrderResponse, BatchCancelOrdersResponse, CancelAllOrdersOptions, CancelAllOrdersResponse, CreateOrderRequestOpts, CreateOrderRequestResponse, BatchCreateOrderRequestResponse, DelegationResponse, WithdrawalResponse, WithdrawalStatusResponse, TradingBalanceResponse, AmuletDisclosure, DisclosuresResponse } from "./types.js";
2
+ export type { ApiError, Ticker, OrderBook, OrderBookOptions, SymbolConfig, OpenInterest, Trade, RecentTradesOptions, ActiveOrder, ActiveOrdersOptions, CancelOrderResponse, BatchCancelOrdersResponse, CancelAllOrdersOptions, CancelAllOrdersResponse, CreateOrderRequestResponse, BatchCreateOrderRequestResponse, DelegationResponse, WithdrawalResponse, WithdrawalStatusResponse, TradingBalanceResponse, AmuletDisclosure, DisclosuresResponse, };
3
3
  export { getUserId } from "./tokenStore.js";
4
4
  export { setWalletAdapter } from "../../src/config/index.js";
5
5
  /**
@@ -40,10 +40,15 @@ export declare function getRecentTrades(symbol: string, options?: RecentTradesOp
40
40
  */
41
41
  export declare function getActiveOrders(options?: ActiveOrdersOptions): Promise<ActiveOrder[] | ApiError>;
42
42
  /**
43
- * Cancel a specific order by ID.
43
+ * Cancel a single order by ID.
44
44
  * @param orderId - The order ID to cancel
45
45
  */
46
46
  export declare function cancelOrder(orderId: string): Promise<CancelOrderResponse | ApiError>;
47
+ /**
48
+ * Cancel multiple orders by ID (max 20).
49
+ * @param orderIds - Array of order IDs to cancel
50
+ */
51
+ export declare function cancelOrder(orderIds: string[]): Promise<BatchCancelOrdersResponse | ApiError>;
47
52
  /**
48
53
  * Cancel all active orders, optionally filtered by symbol.
49
54
  * @param options - Optional symbol filter
@@ -61,9 +66,10 @@ export declare function getDisclosures(partyId: string): Promise<DisclosuresResp
61
66
  export declare function getDelegation(): Promise<DelegationResponse | ApiError>;
62
67
  /**
63
68
  * Create an order request (limit buy/sell) on the Temple trading backend.
64
- * @param opts - Order parameters: symbol, side, quantity, price, order_type, expires_at
69
+ * @param opts - Single order or array of orders (max 20)
65
70
  */
66
71
  export declare function createOrderRequest(opts: CreateOrderRequestOpts): Promise<CreateOrderRequestResponse | ApiError>;
72
+ export declare function createOrderRequest(opts: CreateOrderRequestOpts[]): Promise<BatchCreateOrderRequestResponse | ApiError>;
67
73
  /**
68
74
  * Create a withdrawal request.
69
75
  * @param assetId - Instrument symbol (e.g. "USDCx", "Amulet")
package/dist/api/index.js CHANGED
@@ -154,15 +154,20 @@ export async function getActiveOrders(options = {}) {
154
154
  limit: options.limit,
155
155
  });
156
156
  }
157
- /**
158
- * Cancel a specific order by ID.
159
- * @param orderId - The order ID to cancel
160
- */
161
- export async function cancelOrder(orderId) {
162
- if (!orderId) {
157
+ export async function cancelOrder(orderIdOrIds) {
158
+ if (Array.isArray(orderIdOrIds)) {
159
+ if (orderIdOrIds.length === 0) {
160
+ return { error: true, status: null, code: "INVALID_PARAMS", message: "At least one order ID is required." };
161
+ }
162
+ if (orderIdOrIds.length > 20) {
163
+ return { error: true, status: null, code: "INVALID_PARAMS", message: "Maximum 20 order IDs per batch." };
164
+ }
165
+ return authenticatedPost("/api/trading/orders/cancel", { order_ids: orderIdOrIds });
166
+ }
167
+ if (!orderIdOrIds) {
163
168
  return { error: true, status: null, code: "INVALID_PARAMS", message: "Order ID is required." };
164
169
  }
165
- return authenticatedPost(`/api/trading/orders/${encodeURIComponent(orderId)}/cancel`);
170
+ return authenticatedPost("/api/trading/orders/cancel", { order_id: orderIdOrIds });
166
171
  }
167
172
  /**
168
173
  * Cancel all active orders, optionally filtered by symbol.
@@ -190,12 +195,23 @@ export async function getDisclosures(partyId) {
190
195
  export async function getDelegation() {
191
196
  return authenticatedGet("/api/trading/delegation");
192
197
  }
193
- // ── Order Requests ──
194
- /**
195
- * Create an order request (limit buy/sell) on the Temple trading backend.
196
- * @param opts - Order parameters: symbol, side, quantity, price, order_type, expires_at
197
- */
198
198
  export async function createOrderRequest(opts) {
199
+ if (Array.isArray(opts)) {
200
+ if (opts.length === 0) {
201
+ return { error: true, status: null, code: "INVALID_PARAMS", message: "At least one order is required." };
202
+ }
203
+ if (opts.length > 20) {
204
+ return { error: true, status: null, code: "INVALID_PARAMS", message: "Maximum 20 orders per batch." };
205
+ }
206
+ const body = opts.map((o) => {
207
+ const { symbol: rawSymbol, side, quantity, price, order_type = "limit", expires_at } = o;
208
+ const order = { symbol: normalizeSymbol(rawSymbol), side, quantity: Number(quantity), price: Number(price), order_type };
209
+ if (expires_at)
210
+ order.expires_at = expires_at;
211
+ return order;
212
+ });
213
+ return authenticatedPost("/api/trading/orders", body);
214
+ }
199
215
  const { symbol: rawSymbol, side, quantity, price, order_type = "limit", expires_at } = opts || {};
200
216
  if (!rawSymbol || !side || quantity == null || price == null) {
201
217
  return { error: true, status: null, code: "INVALID_PARAMS", message: "symbol, side, quantity, and price are required." };
@@ -72,6 +72,13 @@ export interface CancelOrderResponse {
72
72
  already_queued: boolean;
73
73
  message: string;
74
74
  }
75
+ export interface BatchCancelOrdersResponse {
76
+ success: boolean;
77
+ canceled: string[];
78
+ already_queued: string[];
79
+ not_found: string[];
80
+ message: string;
81
+ }
75
82
  export interface CancelAllOrdersOptions {
76
83
  symbol?: string;
77
84
  }
@@ -98,6 +105,12 @@ export interface CreateOrderRequestOpts {
98
105
  order_type?: string;
99
106
  expires_at?: string;
100
107
  }
108
+ export interface BatchCreateOrderRequestResponse {
109
+ success: boolean;
110
+ request_ids: number[];
111
+ count: number;
112
+ message: string;
113
+ }
101
114
  export interface CreateOrderRequestResponse {
102
115
  [key: string]: unknown;
103
116
  }
@@ -0,0 +1,52 @@
1
+ export interface DepositFundsOpts {
2
+ sender: string;
3
+ receiver?: string;
4
+ assetId: string;
5
+ amount: string | number;
6
+ holdingCids?: string[];
7
+ settlementId?: string;
8
+ transferLegId?: string;
9
+ allocateBefore?: string;
10
+ settleBefore?: string;
11
+ disclosures?: Record<string, unknown>;
12
+ userId?: string;
13
+ }
14
+ export interface PreparedDeposit {
15
+ sender: string;
16
+ receiver: string;
17
+ assetId: string;
18
+ amount: string;
19
+ holdingCids: string[];
20
+ }
21
+ /**
22
+ * Prepare holdings for a deposit by selecting UTXOs from the wallet provider.
23
+ *
24
+ * Queries the provider for holdings, filters and sorts them, then greedily
25
+ * selects until the requested amount is covered.
26
+ */
27
+ export declare function prepareDepositHoldings(amount: number | string, symbol: string): Promise<PreparedDeposit | {
28
+ error: string;
29
+ data?: Record<string, unknown>;
30
+ }>;
31
+ /**
32
+ * High-level deposit helper.
33
+ *
34
+ * Wraps `prepareDepositHoldings` and `depositFunds` into a single call.
35
+ * Validates the user has sufficient balance and reserves 10 CC for transaction fees.
36
+ *
37
+ * Requires:
38
+ * - Wallet adapter (for reading balances and submitting)
39
+ * - API connection (for disclosures on Amulet deposits)
40
+ */
41
+ export declare function deposit(amount: number | string, symbol: string): Promise<Record<string, unknown>>;
42
+ /**
43
+ * Create a CIP-56 Allocation.
44
+ * Fetches the AllocationFactory, then exercises AllocationFactory_Allocate
45
+ * to lock holdings for a settlement leg.
46
+ *
47
+ * Three resolution paths:
48
+ * 1. Localhost: resolve factory and context from ledger directly
49
+ * 2. Amulet via disclosures (FE/proxy path — no Scan API access)
50
+ * 3. Remote: Scan API / Registry API
51
+ */
52
+ export declare function depositFunds(opts: DepositFundsOpts, returnCommand?: boolean): Promise<Record<string, unknown>>;