aftermath-ts-sdk 1.3.23-perps.25 → 1.3.23-perps.27

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.
@@ -26,10 +26,58 @@ const utils_1 = require("../../general/utils");
26
26
  const perpetuals_1 = require("./perpetuals");
27
27
  const transactions_1 = require("@mysten/sui/transactions");
28
28
  // TODO: create refresh account positions function ?
29
+ /**
30
+ * High-level wrapper around a single Perpetuals account or vault account.
31
+ *
32
+ * This class encapsulates:
33
+ *
34
+ * - Transaction builders for:
35
+ * - Collateral actions (deposit, withdraw, allocate, deallocate, transfer)
36
+ * - Orders (market/limit, cancel, stop orders, SL/TP, set leverage)
37
+ * - Read-only account helpers:
38
+ * - Stop-order message signing
39
+ * - Order & stop-order metadata
40
+ * - Collateral & trade history
41
+ * - Convenience helpers to:
42
+ * - Fetch and categorize SL/TP stop orders
43
+ * - Resolve account/vault identifiers and owner addresses
44
+ *
45
+ * You typically do not construct `PerpetualsAccount` directly. Instead, use
46
+ * {@link Perpetuals.getAccount} or {@link Perpetuals.getAccounts}, which
47
+ * fetch all required on-chain data and wrap it for you:
48
+ *
49
+ * ```ts
50
+ * const afSdk = new Aftermath("MAINNET");
51
+ * await afSdk.init();
52
+ *
53
+ * const perps = afSdk.Perpetuals();
54
+ * const [accountCap] = await perps.getOwnedAccountCaps({
55
+ * walletAddress: "0x...",
56
+ * });
57
+ *
58
+ * const account = await perps.getAccount({ accountCap });
59
+ *
60
+ * // Build a deposit transaction
61
+ * const depositTx = await account.getDepositCollateralTx({
62
+ * depositAmount: BigInt("1000000000"),
63
+ * });
64
+ * ```
65
+ */
29
66
  class PerpetualsAccount extends caller_1.Caller {
30
67
  // =========================================================================
31
68
  // Constructor
32
69
  // =========================================================================
70
+ /**
71
+ * Create a new {@link PerpetualsAccount} wrapper.
72
+ *
73
+ * @param account - Raw account object with positions and equity data.
74
+ * @param accountCap - Account cap or vault-cap-extended object containing
75
+ * ownership and collateral metadata.
76
+ * @param config - Optional {@link CallerConfig} (network, auth, etc.).
77
+ * @param Provider - Optional shared {@link AftermathApi} provider instance
78
+ * used to derive serialized transaction kinds (`txKind`) from
79
+ * {@link Transaction} objects.
80
+ */
33
81
  constructor(account, accountCap, config, Provider) {
34
82
  const vaultId = "vaultId" in accountCap ? accountCap.vaultId : undefined;
35
83
  super(config, "perpetuals");
@@ -44,6 +92,33 @@ class PerpetualsAccount extends caller_1.Caller {
44
92
  // =========================================================================
45
93
  // Collateral Txs
46
94
  // =========================================================================
95
+ /**
96
+ * Build a `deposit-collateral` transaction for this account.
97
+ *
98
+ * For non-vault accounts, this endpoint constructs a transaction that:
99
+ * - Optionally extends an existing {@link Transaction}, and
100
+ * - Deposits collateral into the Perpetuals account.
101
+ *
102
+ * **Note:** Vault accounts are currently not supported and will throw.
103
+ *
104
+ * @param inputs.tx - Optional existing transaction to extend. If omitted,
105
+ * a new {@link Transaction} is created under the hood.
106
+ * @param inputs.isSponsoredTx - Optional flag indicating whether the
107
+ * transaction is gas-sponsored.
108
+ * @param inputs.depositAmount - Amount of collateral to deposit, if paying
109
+ * directly from the wallet.
110
+ * @param inputs.depositCoinArg - Transaction object argument referencing a
111
+ * coin to deposit (mutually exclusive with `depositAmount`).
112
+ *
113
+ * @returns Transaction response containing a serialized `txKind`.
114
+ *
115
+ * @example
116
+ * ```ts
117
+ * const { txKind } = await account.getDepositCollateralTx({
118
+ * depositAmount: BigInt("1000000000"),
119
+ * });
120
+ * ```
121
+ */
47
122
  getDepositCollateralTx(inputs) {
48
123
  return __awaiter(this, void 0, void 0, function* () {
49
124
  var _a;
@@ -65,6 +140,31 @@ class PerpetualsAccount extends caller_1.Caller {
65
140
  });
66
141
  });
67
142
  }
143
+ /**
144
+ * Build a `withdraw-collateral` transaction for this account.
145
+ *
146
+ * For non-vault accounts, this endpoint constructs a transaction to:
147
+ * - Withdraw collateral from the Perpetuals account, and
148
+ * - Optionally transfer it to a `recipientAddress` (otherwise coin is left
149
+ * as a transaction argument).
150
+ *
151
+ * **Note:** Vault accounts are currently not supported and will throw.
152
+ *
153
+ * @param inputs.withdrawAmount - Amount of collateral to withdraw.
154
+ * @param inputs.recipientAddress - Optional address to receive the withdrawn
155
+ * coins directly.
156
+ * @param inputs.tx - Optional transaction to extend (defaults to new `Transaction()`).
157
+ *
158
+ * @returns A response containing `txKind` and the `coinOutArg` where the
159
+ * withdrawn coins end up if `recipientAddress` is not used.
160
+ *
161
+ * @example
162
+ * ```ts
163
+ * const { txKind, coinOutArg } = await account.getWithdrawCollateralTx({
164
+ * withdrawAmount: BigInt("1000000000"),
165
+ * });
166
+ * ```
167
+ */
68
168
  getWithdrawCollateralTx(inputs) {
69
169
  return __awaiter(this, void 0, void 0, function* () {
70
170
  var _a;
@@ -87,6 +187,18 @@ class PerpetualsAccount extends caller_1.Caller {
87
187
  });
88
188
  });
89
189
  }
190
+ /**
191
+ * Build an `allocate-collateral` transaction, moving collateral from this
192
+ * account into a specific market (clearing house).
193
+ *
194
+ * Works for both account-backed and vault-backed accounts.
195
+ *
196
+ * @param inputs.marketId - Market to allocate collateral to.
197
+ * @param inputs.allocateAmount - Amount of collateral to allocate.
198
+ * @param inputs.tx - Optional transaction to extend.
199
+ *
200
+ * @returns Transaction response containing a serialized `txKind`.
201
+ */
90
202
  getAllocateCollateralTx(inputs) {
91
203
  return __awaiter(this, void 0, void 0, function* () {
92
204
  var _a;
@@ -104,6 +216,18 @@ class PerpetualsAccount extends caller_1.Caller {
104
216
  });
105
217
  });
106
218
  }
219
+ /**
220
+ * Build a `deallocate-collateral` transaction, moving collateral from a
221
+ * specific market back to this account.
222
+ *
223
+ * Works for both account-backed and vault-backed accounts.
224
+ *
225
+ * @param inputs.marketId - Market to deallocate collateral from.
226
+ * @param inputs.deallocateAmount - Amount of collateral to deallocate.
227
+ * @param inputs.tx - Optional transaction to extend.
228
+ *
229
+ * @returns Transaction response containing a serialized `txKind`.
230
+ */
107
231
  getDeallocateCollateralTx(inputs) {
108
232
  return __awaiter(this, void 0, void 0, function* () {
109
233
  var _a;
@@ -121,6 +245,17 @@ class PerpetualsAccount extends caller_1.Caller {
121
245
  });
122
246
  });
123
247
  }
248
+ /**
249
+ * Build a `transfer-collateral` transaction between two Perpetuals accounts.
250
+ *
251
+ * Only supported for direct accounts, **not** vault-backed accounts.
252
+ *
253
+ * @param inputs.transferAmount - Amount of collateral to transfer.
254
+ * @param inputs.toAccountId - Destination account ID.
255
+ * @param inputs.tx - Optional transaction to extend.
256
+ *
257
+ * @returns Transaction response containing a serialized `txKind`.
258
+ */
124
259
  getTransferCollateralTx(inputs) {
125
260
  return __awaiter(this, void 0, void 0, function* () {
126
261
  var _a;
@@ -143,6 +278,35 @@ class PerpetualsAccount extends caller_1.Caller {
143
278
  // =========================================================================
144
279
  // Order Txs
145
280
  // =========================================================================
281
+ /**
282
+ * Build a `place-market-order` transaction for this account.
283
+ *
284
+ * This is the primary entrypoint for opening/closing positions via market orders.
285
+ * It automatically:
286
+ * - Injects the account/vault identity into the payload.
287
+ * - Derives `hasPosition` based on the current account state for the given market.
288
+ * - Optionally attaches SL/TP stop orders via the `slTp` input.
289
+ *
290
+ * @param inputs - See {@link SdkPerpetualsPlaceMarketOrderInputs} for details.
291
+ * Notably:
292
+ * - `marketId`, `side`, `size`, `collateralChange`, `reduceOnly`
293
+ * - Optional `leverage`
294
+ * - Optional `slTp` params
295
+ * - Optional `tx` to extend
296
+ *
297
+ * @returns Transaction response containing `txKind`.
298
+ *
299
+ * @example
300
+ * ```ts
301
+ * const { txKind } = await account.getPlaceMarketOrderTx({
302
+ * marketId: "0x...",
303
+ * side: PerpetualsOrderSide.Bid,
304
+ * size: BigInt("1000000000"),
305
+ * collateralChange: 10,
306
+ * reduceOnly: false,
307
+ * });
308
+ * ```
309
+ */
146
310
  getPlaceMarketOrderTx(inputs) {
147
311
  return __awaiter(this, void 0, void 0, function* () {
148
312
  var _a;
@@ -162,6 +326,17 @@ class PerpetualsAccount extends caller_1.Caller {
162
326
  });
163
327
  });
164
328
  }
329
+ /**
330
+ * Build a `place-limit-order` transaction for this account.
331
+ *
332
+ * Similar to {@link getPlaceMarketOrderTx}, but uses limit order semantics:
333
+ * - Requires `price` and `orderType`.
334
+ * - Supports reduce-only flags, expiry, optional leverage, and SL/TP stop orders.
335
+ *
336
+ * @param inputs - See {@link SdkPerpetualsPlaceLimitOrderInputs}.
337
+ *
338
+ * @returns Transaction response containing `txKind`.
339
+ */
165
340
  getPlaceLimitOrderTx(inputs) {
166
341
  return __awaiter(this, void 0, void 0, function* () {
167
342
  var _a;
@@ -181,6 +356,17 @@ class PerpetualsAccount extends caller_1.Caller {
181
356
  });
182
357
  });
183
358
  }
359
+ /**
360
+ * Build a `cancel-orders` transaction for this account.
361
+ *
362
+ * @param inputs.tx - Optional transaction to extend.
363
+ * @param inputs.marketIdsToData - Mapping from market IDs to:
364
+ * - `orderIds`: order IDs to cancel
365
+ * - `collateralChange`: net collateral impact (if any)
366
+ * - `leverage`: current leverage used for estimating effects
367
+ *
368
+ * @returns Transaction response containing `txKind`.
369
+ */
184
370
  getCancelOrdersTx(inputs) {
185
371
  return __awaiter(this, void 0, void 0, function* () {
186
372
  var _a;
@@ -197,6 +383,14 @@ class PerpetualsAccount extends caller_1.Caller {
197
383
  });
198
384
  });
199
385
  }
386
+ /**
387
+ * Build a `cancel-stop-orders` transaction for this account.
388
+ *
389
+ * @param inputs.tx - Optional transaction to extend.
390
+ * @param inputs.stopOrderIds - Array of stop-order ticket IDs to cancel.
391
+ *
392
+ * @returns Transaction response containing `txKind`.
393
+ */
200
394
  getCancelStopOrdersTx(inputs) {
201
395
  return __awaiter(this, void 0, void 0, function* () {
202
396
  var _a;
@@ -213,6 +407,16 @@ class PerpetualsAccount extends caller_1.Caller {
213
407
  });
214
408
  });
215
409
  }
410
+ /**
411
+ * Build a `place-stop-orders` transaction for this account.
412
+ *
413
+ * This allows placing one or more stop orders in a single transaction,
414
+ * optionally with a dedicated gas coin and a sponsored gas flag.
415
+ *
416
+ * @param inputs - See {@link SdkPerpetualsPlaceStopOrdersInputs}.
417
+ *
418
+ * @returns Transaction response containing `txKind`.
419
+ */
216
420
  getPlaceStopOrdersTx(inputs) {
217
421
  return __awaiter(this, void 0, void 0, function* () {
218
422
  var _a;
@@ -233,6 +437,17 @@ class PerpetualsAccount extends caller_1.Caller {
233
437
  });
234
438
  });
235
439
  }
440
+ /**
441
+ * Build a `place-sl-tp-orders` transaction for this account.
442
+ *
443
+ * This helper constructs SL/TP stop orders for an **existing** position
444
+ * in a given market. If the account has no position for `marketId`, this
445
+ * throws an error.
446
+ *
447
+ * @param inputs - See {@link SdkPerpetualsPlaceSlTpOrdersInputs}.
448
+ *
449
+ * @returns Transaction response containing `txKind`.
450
+ */
236
451
  getPlaceSlTpOrdersTx(inputs) {
237
452
  return __awaiter(this, void 0, void 0, function* () {
238
453
  var _a;
@@ -256,6 +471,16 @@ class PerpetualsAccount extends caller_1.Caller {
256
471
  });
257
472
  });
258
473
  }
474
+ /**
475
+ * Build an `edit-stop-orders` transaction for this account.
476
+ *
477
+ * This endpoint lets you update existing stop orders in batch.
478
+ *
479
+ * @param inputs.stopOrders - Full updated stop-order payloads to apply.
480
+ * @param inputs.tx - Optional transaction to extend.
481
+ *
482
+ * @returns Transaction response containing `txKind`.
483
+ */
259
484
  getEditStopOrdersTx(inputs) {
260
485
  return __awaiter(this, void 0, void 0, function* () {
261
486
  var _a;
@@ -309,6 +534,20 @@ class PerpetualsAccount extends caller_1.Caller {
309
534
  // }
310
535
  // );
311
536
  // }
537
+ /**
538
+ * Build a `set-leverage` transaction for a given market.
539
+ *
540
+ * This updates the effective leverage for the position (or potential position)
541
+ * in `marketId`, and optionally adjusts collateral in tandem.
542
+ *
543
+ * @param inputs.tx - Optional transaction to extend.
544
+ * @param inputs.leverage - Target leverage value.
545
+ * @param inputs.collateralChange - Net collateral change to apply alongside
546
+ * the leverage update.
547
+ * @param inputs.marketId - Market whose leverage to adjust.
548
+ *
549
+ * @returns Transaction response containing `txKind`.
550
+ */
312
551
  getSetLeverageTx(inputs) {
313
552
  return __awaiter(this, void 0, void 0, function* () {
314
553
  var _a;
@@ -345,6 +584,26 @@ class PerpetualsAccount extends caller_1.Caller {
345
584
  // =========================================================================
346
585
  // Interactions
347
586
  // =========================================================================
587
+ /**
588
+ * Build a deterministic message payload to sign when querying stop orders
589
+ * from the backend.
590
+ *
591
+ * This payload is intended to be signed off-chain and then submitted to
592
+ * `getStopOrderDatas` as a proof of account ownership.
593
+ *
594
+ * @param inputs.marketIds - Optional list of market IDs to scope the query.
595
+ *
596
+ * @returns An object describing the action and account/market IDs, suitable
597
+ * for message signing.
598
+ *
599
+ * @example
600
+ * ```ts
601
+ * const message = account.getStopOrdersMessageToSign({ marketIds: ["0x..."] });
602
+ * const { signature } = await wallet.signMessage({
603
+ * message: new TextEncoder().encode(JSON.stringify(message)),
604
+ * });
605
+ * ```
606
+ */
348
607
  getStopOrdersMessageToSign(inputs) {
349
608
  var _a;
350
609
  return {
@@ -363,7 +622,7 @@ class PerpetualsAccount extends caller_1.Caller {
363
622
  // error: string;
364
623
  // }
365
624
  // | {
366
- // positionAfterOrder: PerpetualsPosition;
625
+ // updatedPosition: PerpetualsPosition;
367
626
  // priceSlippage: number;
368
627
  // percentSlippage: Percentage;
369
628
  // filledSize: number;
@@ -387,6 +646,20 @@ class PerpetualsAccount extends caller_1.Caller {
387
646
  // abortSignal
388
647
  // );
389
648
  // }
649
+ /**
650
+ * Preview the effects of placing a market order (without building a tx).
651
+ *
652
+ * @param inputs - See {@link SdkPerpetualsPlaceMarketOrderPreviewInputs}.
653
+ * @param abortSignal - Optional `AbortSignal` to cancel the request.
654
+ *
655
+ * @returns Either an error message or a preview including:
656
+ * - `updatedPosition`
657
+ * - `priceSlippage`, `percentSlippage`
658
+ * - `filledSize`, `filledSizeUsd`
659
+ * - `postedSize`, `postedSizeUsd`
660
+ * - `collateralChange`
661
+ * - `executionPrice`
662
+ */
390
663
  getPlaceMarketOrderPreview(inputs, abortSignal) {
391
664
  return __awaiter(this, void 0, void 0, function* () {
392
665
  return this.fetchApi(`${this.vaultId ? "vault" : "account"}/` +
@@ -399,6 +672,15 @@ class PerpetualsAccount extends caller_1.Caller {
399
672
  })), abortSignal);
400
673
  });
401
674
  }
675
+ /**
676
+ * Preview the effects of placing a limit order (without building a tx).
677
+ *
678
+ * @param inputs - See {@link SdkPerpetualsPlaceLimitOrderPreviewInputs}.
679
+ * @param abortSignal - Optional `AbortSignal` to cancel the request.
680
+ *
681
+ * @returns Either an error message or a preview object similar to
682
+ * {@link getPlaceMarketOrderPreview}.
683
+ */
402
684
  getPlaceLimitOrderPreview(inputs, abortSignal) {
403
685
  return __awaiter(this, void 0, void 0, function* () {
404
686
  return this.fetchApi(`${this.vaultId ? "vault" : "account"}/` +
@@ -411,13 +693,27 @@ class PerpetualsAccount extends caller_1.Caller {
411
693
  })), abortSignal);
412
694
  });
413
695
  }
696
+ /**
697
+ * Preview the effects of canceling orders across one or more markets.
698
+ *
699
+ * If `marketIdsToData` is empty, this returns a trivial preview with:
700
+ * - `collateralChange: 0`
701
+ * - `updatedPositions: []`
702
+ *
703
+ * @param inputs - See {@link SdkPerpetualsCancelOrdersPreviewInputs}.
704
+ * @param abortSignal - Optional `AbortSignal` to cancel the request.
705
+ *
706
+ * @returns Either:
707
+ * - `{ updatedPositions, collateralChange }`, or
708
+ * - `{ error }`.
709
+ */
414
710
  getCancelOrdersPreview(inputs, abortSignal) {
415
711
  return __awaiter(this, void 0, void 0, function* () {
416
712
  // NOTE: should this case return an error instead ?
417
713
  if (Object.keys(inputs.marketIdsToData).length <= 0)
418
714
  return {
419
715
  collateralChange: 0,
420
- marketIdsToPositionAfterCancelOrders: {},
716
+ updatedPositions: [],
421
717
  };
422
718
  return this.fetchApi(`${this.vaultId ? "vault" : "account"}/` + "previews/cancel-orders", Object.assign(Object.assign({}, inputs), ("vaultId" in this.accountCap
423
719
  ? {
@@ -463,6 +759,17 @@ class PerpetualsAccount extends caller_1.Caller {
463
759
  // abortSignal
464
760
  // );
465
761
  // }
762
+ /**
763
+ * Preview the effects of setting leverage for a given market.
764
+ *
765
+ * @param inputs.marketId - Market whose leverage you want to adjust.
766
+ * @param inputs.leverage - Target leverage value.
767
+ * @param abortSignal - Optional `AbortSignal` to cancel the request.
768
+ *
769
+ * @returns Either:
770
+ * - `{ updatedPosition, collateralChange }`, or
771
+ * - `{ error }`.
772
+ */
466
773
  getSetLeveragePreview(inputs, abortSignal) {
467
774
  return __awaiter(this, void 0, void 0, function* () {
468
775
  const { marketId, leverage } = inputs;
@@ -476,6 +783,34 @@ class PerpetualsAccount extends caller_1.Caller {
476
783
  })), abortSignal);
477
784
  });
478
785
  }
786
+ /**
787
+ * Preview the effects of allocating/deallocating collateral for the position in
788
+ * a given market.
789
+ *
790
+ * @param inputs.marketId - Market of whose position you want to allocate/deallocate
791
+ * collateral to/from.
792
+ * @param inputs.collateralChange - The target collateral change (a positive number
793
+ * for allocating collateral, negative for deallocating collateral).
794
+ * @param abortSignal - Optional `AbortSignal` to cancel the request.
795
+ *
796
+ * @returns Either:
797
+ * - `{ updatedPosition, collateralChange }`, or
798
+ * - `{ error }`.
799
+ */
800
+ getEditCollateralPreview(inputs, abortSignal) {
801
+ return __awaiter(this, void 0, void 0, function* () {
802
+ const { marketId, collateralChange } = inputs;
803
+ return this.fetchApi(`${this.vaultId ? "vault" : "account"}/` +
804
+ "previews/edit-collateral", Object.assign({ marketId,
805
+ collateralChange }, ("vaultId" in this.accountCap
806
+ ? {
807
+ vaultId: this.accountCap.vaultId,
808
+ }
809
+ : {
810
+ accountId: this.accountCap.accountId,
811
+ })), abortSignal);
812
+ });
813
+ }
479
814
  // public getPlaceClosePositionOrderPreview = async (
480
815
  // inputs: {
481
816
  // size: bigint;
@@ -512,6 +847,15 @@ class PerpetualsAccount extends caller_1.Caller {
512
847
  // abortSignal
513
848
  // );
514
849
  // };
850
+ /**
851
+ * Fetch the latest order metadata (sizes, IDs) for this account.
852
+ *
853
+ * This is especially useful after a long-running session where on-chain
854
+ * pending orders may have changed relative to the local `account` state.
855
+ *
856
+ * @returns Array of {@link PerpetualsOrderData} describing each pending order.
857
+ * Returns `[]` if there are no pending orders.
858
+ */
515
859
  getOrderDatas() {
516
860
  return __awaiter(this, void 0, void 0, function* () {
517
861
  const orderDatas = this.account.positions.reduce((acc, position) => [
@@ -529,37 +873,70 @@ class PerpetualsAccount extends caller_1.Caller {
529
873
  });
530
874
  });
531
875
  }
876
+ /**
877
+ * Fetch stop-order ticket data for this account, using an off-chain signed
878
+ * payload.
879
+ *
880
+ * @param inputs.bytes - Serialized message that was signed (e.g. from
881
+ * {@link getStopOrdersMessageToSign}).
882
+ * @param inputs.signature - Signature over `bytes`.
883
+ * @param inputs.marketIds - Optional subset of markets to filter results by.
884
+ *
885
+ * @returns Array of {@link PerpetualsStopOrderData}.
886
+ */
532
887
  getStopOrderDatas(inputs) {
533
888
  return __awaiter(this, void 0, void 0, function* () {
534
889
  const { bytes, signature, marketIds } = inputs;
535
- return this.fetchApi("account/stop-order-datas", {
536
- bytes,
537
- signature,
538
- accountId: this.accountCap.accountId,
539
- walletAddress: this.ownerAddress(),
540
- marketIds: marketIds !== null && marketIds !== void 0 ? marketIds : [],
541
- });
890
+ return this.fetchApi(`${this.vaultId ? "vault" : "account"}/` + "stop-order-datas", Object.assign({ bytes,
891
+ signature, walletAddress: this.ownerAddress(), marketIds: marketIds !== null && marketIds !== void 0 ? marketIds : [] }, ("vaultId" in this.accountCap
892
+ ? {
893
+ vaultId: this.accountCap.vaultId,
894
+ }
895
+ : {
896
+ accountId: this.accountCap.accountId,
897
+ })));
542
898
  });
543
899
  }
900
+ /**
901
+ * Fetch paginated collateral-change history for this account, including
902
+ * deposits, withdrawals, funding settlements, liquidations, etc.
903
+ *
904
+ * @param inputs.cursor - Optional cursor for pagination.
905
+ * @param inputs.limit - Optional limit per page.
906
+ *
907
+ * @returns {@link PerpetualsAccountCollateralChangesWithCursor} containing
908
+ * an array of changes and a `nextCursor`.
909
+ */
544
910
  getCollateralHistory(inputs) {
545
911
  return __awaiter(this, void 0, void 0, function* () {
546
912
  return this.fetchApi("account/collateral-history", Object.assign(Object.assign({}, inputs), { accountId: this.accountCap.accountId, collateralCoinType: this.accountCap.collateralCoinType }));
547
913
  });
548
914
  }
915
+ /**
916
+ * Fetch paginated trade (order fill) history for this account.
917
+ *
918
+ * @param inputs.cursor - Optional cursor for pagination.
919
+ * @param inputs.limit - Optional limit per page.
920
+ *
921
+ * @returns {@link PerpetualsAccountTradesWithCursor} containing a list of
922
+ * trades and a `nextCursor`.
923
+ */
549
924
  getOrderHistory(inputs) {
550
925
  return __awaiter(this, void 0, void 0, function* () {
551
926
  return this.fetchApi("account/trade-history", Object.assign(Object.assign({}, inputs), { accountId: this.accountCap.accountId }));
552
927
  });
553
928
  }
554
- // public async getMarginHistory() {
555
- // return this.fetchApi<
556
- // PerpetualsAccountMarginData[],
557
- // ApiPerpetualsAccountMarginHistoryBody
558
- // >("account/margin-history", {
559
- // accountId: this.accountCap.accountId,
560
- // collateralCoinType: this.accountCap.collateralCoinType,
561
- // });
562
- // }
929
+ // TODO: docs
930
+ // public async getMarginHistory(inputs: ApiDataWithCursorBody<Timestamp>) {
931
+ getMarginHistory() {
932
+ return __awaiter(this, void 0, void 0, function* () {
933
+ return this.fetchApi("account/margin-history", {
934
+ // ...inputs,
935
+ accountId: this.accountCap.accountId,
936
+ collateralCoinType: this.accountCap.collateralCoinType,
937
+ });
938
+ });
939
+ }
563
940
  // public async getOwnedWithdrawRequests() {
564
941
  // return new Perpetuals(
565
942
  // this.config,
@@ -571,6 +948,12 @@ class PerpetualsAccount extends caller_1.Caller {
571
948
  // =========================================================================
572
949
  // Helpers
573
950
  // =========================================================================
951
+ /**
952
+ * Find the current position for a given market ID, if any.
953
+ *
954
+ * @param inputs.marketId - Market ID to search for.
955
+ * @returns {@link PerpetualsPosition} if found, otherwise `undefined`.
956
+ */
574
957
  positionForMarketId(inputs) {
575
958
  try {
576
959
  return this.account.positions.find((pos) => pos.marketId === inputs.marketId);
@@ -579,6 +962,15 @@ class PerpetualsAccount extends caller_1.Caller {
579
962
  return undefined;
580
963
  }
581
964
  }
965
+ /**
966
+ * Filter a list of stop orders to only include non-SL/TP orders.
967
+ *
968
+ * A stop order is considered SL/TP if it appears in the combined set of
969
+ * SL/TP orders across **all** markets (see {@link slTpStopOrderDatas}).
970
+ *
971
+ * @param inputs.stopOrderDatas - Full array of stop-order ticket data.
972
+ * @returns An array of non-SL/TP stop orders, or `undefined` if none exist.
973
+ */
582
974
  nonSlTpStopOrderDatas(inputs) {
583
975
  const { stopOrderDatas } = inputs;
584
976
  const slTpOrders = this.slTpStopOrderDatas(inputs);
@@ -587,6 +979,21 @@ class PerpetualsAccount extends caller_1.Caller {
587
979
  .includes(JSON.stringify(stopOrder)));
588
980
  return stopOrders.length <= 0 ? undefined : stopOrders;
589
981
  }
982
+ /**
983
+ * Extract all SL/TP-style stop orders across **all** markets for this
984
+ * account.
985
+ *
986
+ * SL/TP orders are stop orders which:
987
+ * - Have an `slTp` payload, and
988
+ * - Target the opposite side of the current position.
989
+ *
990
+ * This combines:
991
+ * - "Full" SL/TP orders (size >= `i64MaxBigInt`)
992
+ * - "Partial" SL/TP orders (size < `i64MaxBigInt`)
993
+ *
994
+ * @param inputs.stopOrderDatas - Full list of stop-order tickets.
995
+ * @returns Array of SL/TP stop orders, or `undefined` if none exist.
996
+ */
590
997
  slTpStopOrderDatas(inputs) {
591
998
  const { stopOrderDatas } = inputs;
592
999
  let slTpOrders = [];
@@ -603,6 +1010,15 @@ class PerpetualsAccount extends caller_1.Caller {
603
1010
  }
604
1011
  return slTpOrders.length <= 0 ? undefined : slTpOrders;
605
1012
  }
1013
+ /**
1014
+ * Filter stop orders for a single market to only include non-SL/TP orders.
1015
+ *
1016
+ * Uses {@link slTpStopOrderDatasForMarketId} under the hood.
1017
+ *
1018
+ * @param inputs.marketId - Market ID to filter for.
1019
+ * @param inputs.stopOrderDatas - Full list of stop orders.
1020
+ * @returns Non-SL/TP stop orders for the given market, or `undefined` if none exist.
1021
+ */
606
1022
  nonSlTpStopOrderDatasForMarketId(inputs) {
607
1023
  const { marketId, stopOrderDatas } = inputs;
608
1024
  const position = this.positionForMarketId({ marketId });
@@ -617,6 +1033,24 @@ class PerpetualsAccount extends caller_1.Caller {
617
1033
  .includes(JSON.stringify(stopOrder)));
618
1034
  return stopOrders.length <= 0 ? undefined : stopOrders;
619
1035
  }
1036
+ /**
1037
+ * Categorize stop orders for a specific market into:
1038
+ * - A "full" SL/TP order (size >= `i64MaxBigInt`) if any.
1039
+ * - A set of "partial" SL/TP orders (size < `i64MaxBigInt`).
1040
+ *
1041
+ * SL/TP stop orders are defined as:
1042
+ * - Market ID matches the input market.
1043
+ * - `slTp` field is present.
1044
+ * - Order side is opposite of the position side.
1045
+ * - At least a `stopLossIndexPrice` or `takeProfitIndexPrice` is set.
1046
+ *
1047
+ * @param inputs.marketId - Market to categorize stop orders for.
1048
+ * @param inputs.stopOrderDatas - Full list of stop orders.
1049
+ *
1050
+ * @returns Object containing:
1051
+ * - `fullSlTpOrder` (if any)
1052
+ * - `partialSlTpOrders` (if any, otherwise `undefined`)
1053
+ */
620
1054
  slTpStopOrderDatasForMarketId(inputs) {
621
1055
  const { marketId, stopOrderDatas } = inputs;
622
1056
  const position = this.positionForMarketId({ marketId });
@@ -645,6 +1079,11 @@ class PerpetualsAccount extends caller_1.Caller {
645
1079
  partialSlTpOrders: partialSlTpOrders.length <= 0 ? undefined : partialSlTpOrders,
646
1080
  };
647
1081
  }
1082
+ /**
1083
+ * Convenience accessor for the account's available collateral (in coin units).
1084
+ *
1085
+ * @returns Available collateral as a `number`.
1086
+ */
648
1087
  collateral() {
649
1088
  return this.account.availableCollateral;
650
1089
  }
@@ -657,21 +1096,52 @@ class PerpetualsAccount extends caller_1.Caller {
657
1096
  // this.collateralDecimals()
658
1097
  // );
659
1098
  // }
1099
+ /**
1100
+ * Check whether this {@link PerpetualsAccount} is vault-backed.
1101
+ *
1102
+ * @returns `true` if the underlying `accountCap` is a vault cap; otherwise `false`.
1103
+ */
660
1104
  isVault() {
661
- return this.isVault !== undefined;
1105
+ return "vaultId" in this.accountCap;
662
1106
  }
1107
+ /**
1108
+ * Resolve the owner wallet address of this account or vault.
1109
+ *
1110
+ * - For direct accounts, returns the `walletAddress` field.
1111
+ * - For vault-backed accounts, returns `ownerAddress`.
1112
+ *
1113
+ * @returns Owner wallet {@link SuiAddress}.
1114
+ */
663
1115
  ownerAddress() {
664
1116
  return "walletAddress" in this.accountCap
665
1117
  ? // TODO: change to ownerAddress ?
666
1118
  this.accountCap.walletAddress
667
1119
  : this.accountCap.ownerAddress;
668
1120
  }
1121
+ /**
1122
+ * Get the underlying account object ID.
1123
+ *
1124
+ * @returns {@link ObjectId} of the account object.
1125
+ */
669
1126
  accountObjectId() {
670
1127
  return this.accountCap.accountObjectId;
671
1128
  }
1129
+ /**
1130
+ * Get the numeric perpetuals account ID.
1131
+ *
1132
+ * @returns {@link PerpetualsAccountId} for this account.
1133
+ */
672
1134
  accountId() {
673
1135
  return this.accountCap.accountId;
674
1136
  }
1137
+ /**
1138
+ * Get the account cap object ID, if this is a direct account.
1139
+ *
1140
+ * **Note:** This is **not** available for vault-backed accounts and will
1141
+ * throw an error if called on one.
1142
+ *
1143
+ * @returns {@link ObjectId} of the account cap.
1144
+ */
675
1145
  // TODO: make this work with vaults
676
1146
  accountCapId() {
677
1147
  if ("vaultId" in this.accountCap)
@@ -680,9 +1150,3 @@ class PerpetualsAccount extends caller_1.Caller {
680
1150
  }
681
1151
  }
682
1152
  exports.PerpetualsAccount = PerpetualsAccount;
683
- // =========================================================================
684
- // Private Constants
685
- // =========================================================================
686
- PerpetualsAccount.constants = {
687
- closePositionMarginOfError: 0.1, // 10%
688
- };