@decibeltrade/sdk 0.2.7 → 0.2.8

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.
Files changed (66) hide show
  1. package/package.json +7 -1
  2. package/.github/workflows/npm_publish.yml +0 -58
  3. package/eslint.config.mjs +0 -25
  4. package/src/abi/generate-abis.ts +0 -164
  5. package/src/abi/json/netna.json +0 -1325
  6. package/src/abi/json/testnet.json +0 -1328
  7. package/src/abi/types.ts +0 -23
  8. package/src/admin.ts +0 -287
  9. package/src/base.ts +0 -226
  10. package/src/constants.ts +0 -131
  11. package/src/fee-pay.ts +0 -39
  12. package/src/gas/gas-price-manager.ts +0 -115
  13. package/src/index.ts +0 -11
  14. package/src/order-event.types.ts +0 -65
  15. package/src/order-status.ts +0 -89
  16. package/src/read/account-overview/account-overview.reader.ts +0 -47
  17. package/src/read/account-overview/account-overview.types.ts +0 -47
  18. package/src/read/base-reader.ts +0 -41
  19. package/src/read/candlesticks/candlesticks.reader.ts +0 -61
  20. package/src/read/candlesticks/candlesticks.types.ts +0 -46
  21. package/src/read/delegations/delegations.reader.ts +0 -22
  22. package/src/read/delegations/delegations.types.ts +0 -19
  23. package/src/read/index.ts +0 -288
  24. package/src/read/leaderboard/leaderboard.reader.ts +0 -21
  25. package/src/read/leaderboard/leaderboard.types.ts +0 -26
  26. package/src/read/market-contexts/market-contexts.reader.ts +0 -26
  27. package/src/read/market-contexts/market-contexts.types.ts +0 -17
  28. package/src/read/market-depth/market-depth.reader.ts +0 -60
  29. package/src/read/market-depth/market-depth.types.ts +0 -24
  30. package/src/read/market-prices/market-prices.reader.ts +0 -74
  31. package/src/read/market-prices/market-prices.types.ts +0 -41
  32. package/src/read/market-trades/market-trades.reader.ts +0 -46
  33. package/src/read/market-trades/market-trades.types.ts +0 -34
  34. package/src/read/markets/markets.reader.ts +0 -82
  35. package/src/read/markets/markets.types.ts +0 -54
  36. package/src/read/pagination.types.ts +0 -18
  37. package/src/read/portfolio-chart/portfolio-chart.reader.ts +0 -20
  38. package/src/read/portfolio-chart/portfolio-chart.types.ts +0 -21
  39. package/src/read/types.ts +0 -130
  40. package/src/read/user-active-twaps/user-active-twaps.reader.ts +0 -36
  41. package/src/read/user-active-twaps/user-active-twaps.types.ts +0 -33
  42. package/src/read/user-bulk-orders/user-bulk-orders.reader.ts +0 -37
  43. package/src/read/user-bulk-orders/user-bulk-orders.types.ts +0 -32
  44. package/src/read/user-funding-history/user-funding-history.reader.ts +0 -38
  45. package/src/read/user-funding-history/user-funding-history.types.ts +0 -29
  46. package/src/read/user-notifications/user-notifications.reader.ts +0 -17
  47. package/src/read/user-notifications/user-notifications.types.ts +0 -61
  48. package/src/read/user-open-orders/user-open-orders.reader.ts +0 -36
  49. package/src/read/user-open-orders/user-open-orders.types.ts +0 -42
  50. package/src/read/user-order-history/user-order-history.reader.ts +0 -34
  51. package/src/read/user-order-history/user-order-history.types.ts +0 -48
  52. package/src/read/user-positions/user-positions.reader.ts +0 -55
  53. package/src/read/user-positions/user-positions.types.ts +0 -42
  54. package/src/read/user-subaccounts/user-subaccounts.reader.ts +0 -30
  55. package/src/read/user-subaccounts/user-subaccounts.types.ts +0 -21
  56. package/src/read/user-trade-history/user-trade-history.reader.ts +0 -38
  57. package/src/read/user-trade-history/user-trade-history.types.ts +0 -33
  58. package/src/read/vaults/vaults.reader.ts +0 -81
  59. package/src/read/vaults/vaults.types.ts +0 -109
  60. package/src/read/ws-subscription.ts +0 -206
  61. package/src/release-config.ts +0 -47
  62. package/src/subaccount-types.ts +0 -31
  63. package/src/transaction-builder.ts +0 -76
  64. package/src/utils.ts +0 -289
  65. package/src/write.ts +0 -979
  66. package/tsconfig.json +0 -8
package/src/write.ts DELETED
@@ -1,979 +0,0 @@
1
- import { Account, AccountAddress, CommittedTransactionResponse } from "@aptos-labs/ts-sdk";
2
-
3
- import { BaseSDK, Options } from "./base";
4
- import { DecibelConfig, getVaultApiModule } from "./constants";
5
- import { OrderEvent, PlaceOrderResult, TwapEvent } from "./order-event.types";
6
- import { OrderStatusClient } from "./order-status";
7
- import {
8
- ActivateVaultArgs,
9
- CreateVaultArgs,
10
- DepositToVaultArgs,
11
- WithdrawFromVaultArgs,
12
- } from "./read";
13
- import { RenameSubaccountArgs, RenameSubaccountSchema } from "./subaccount-types";
14
- import { getMarketAddr, getPrimarySubaccountAddr, postRequest } from "./utils";
15
-
16
- export const TimeInForce = {
17
- GoodTillCanceled: 0,
18
- PostOnly: 1,
19
- ImmediateOrCancel: 2,
20
- } as const;
21
- export type TimeInForce = (typeof TimeInForce)[keyof typeof TimeInForce];
22
-
23
- interface Cache {
24
- usdcDecimals?: number;
25
- }
26
-
27
- type WithSignerAddress<T> = T & {
28
- signerAddress: AccountAddress;
29
- };
30
-
31
- /**
32
- * Rounds price to the nearest tick size multiple
33
- * @param price The price to round
34
- * @param tickSize The market's tick size
35
- * @returns Price rounded to nearest tick size multiple
36
- */
37
- function roundToTickSize(price: number, tickSize: number): number {
38
- if (price === 0 || tickSize === 0) return 0;
39
- return Math.round(price / tickSize) * tickSize;
40
- }
41
-
42
- export class DecibelWriteDex extends BaseSDK {
43
- readonly cache: Cache;
44
- readonly orderStatusClient: OrderStatusClient;
45
-
46
- constructor(config: DecibelConfig, account: Account, opts?: Options) {
47
- super(config, account, opts);
48
- this.cache = {};
49
- this.orderStatusClient = new OrderStatusClient(config);
50
- }
51
-
52
- /**
53
- * Extract order_id from OrderEvent in transaction response
54
- */
55
- private extractOrderIdFromTransaction(
56
- txResponse: CommittedTransactionResponse,
57
- subaccountAddr?: string,
58
- ): string | null {
59
- const orderEvents = ["market_types::OrderEvent", "async_matching_engine::TwapEvent"];
60
- try {
61
- // Check if the response is a UserTransactionResponse with events
62
- if ("events" in txResponse && Array.isArray(txResponse.events)) {
63
- for (const event of txResponse.events) {
64
- // Check if this is an OrderEvent from the market module
65
- for (const orderEvent of orderEvents) {
66
- if (event.type.includes(orderEvent)) {
67
- const orderEvent = event.data as OrderEvent | TwapEvent;
68
- // Verify the event's user field matches the subaccount placing the order
69
- const userAddress = subaccountAddr ?? this.account.accountAddress;
70
- const orderUserAddress = (orderEvent as OrderEvent).user;
71
- const twapUserAddress = (orderEvent as TwapEvent).account;
72
- if (orderUserAddress === userAddress || twapUserAddress === userAddress) {
73
- return typeof orderEvent.order_id === "string"
74
- ? orderEvent.order_id
75
- : orderEvent.order_id.order_id;
76
- }
77
- }
78
- }
79
- }
80
- }
81
- return null;
82
- } catch (error) {
83
- console.error("Error extracting order_id from transaction:", error);
84
- return null;
85
- }
86
- }
87
-
88
- async renameSubaccount({ subaccountAddress, newName }: RenameSubaccountArgs) {
89
- return await postRequest({
90
- schema: RenameSubaccountSchema,
91
- url: `${this.config.tradingHttpUrl}/api/v1/subaccounts/${subaccountAddress}`,
92
- body: { name: newName },
93
- });
94
- }
95
-
96
- async createSubaccount() {
97
- return await this.sendTx({
98
- function: `${this.config.deployment.package}::dex_accounts::create_new_subaccount`,
99
- typeArguments: [],
100
- functionArguments: [],
101
- });
102
- }
103
-
104
- async sendSubaccountTx(
105
- sendTx: (subaccountAddr: string) => Promise<CommittedTransactionResponse>,
106
- subaccountAddr?: string,
107
- ) {
108
- if (!subaccountAddr) {
109
- subaccountAddr = getPrimarySubaccountAddr(
110
- this.account.accountAddress,
111
- this.config.subaccountVariant,
112
- );
113
- }
114
- return await sendTx(subaccountAddr);
115
- }
116
-
117
- async withSubaccount<T>(fn: (subaccountAddr: string) => Promise<T>, subaccountAddr?: string) {
118
- if (!subaccountAddr) {
119
- subaccountAddr = getPrimarySubaccountAddr(
120
- this.account.accountAddress,
121
- this.config.subaccountVariant,
122
- );
123
- }
124
- return await fn(subaccountAddr);
125
- }
126
- /**
127
- * @param amount u64 amount of collateral to deposit
128
- */
129
- async deposit(amount: number, subaccountAddr?: string) {
130
- if (!subaccountAddr) {
131
- return await this.sendTx({
132
- function: `${this.config.deployment.package}::dex_accounts::deposit_to_subaccount`,
133
- typeArguments: [],
134
- functionArguments: [this.config.deployment.usdc, amount],
135
- });
136
- } else {
137
- return await this.sendSubaccountTx(
138
- (subaccountAddr) =>
139
- this.sendTx({
140
- function: `${this.config.deployment.package}::dex_accounts::deposit_to_subaccount_at`,
141
- typeArguments: [],
142
- functionArguments: [subaccountAddr, this.config.deployment.usdc, amount],
143
- }),
144
- subaccountAddr,
145
- );
146
- }
147
- }
148
-
149
- /**
150
- * @param amount u64 amount of collateral to withdraw
151
- */
152
- async withdraw(amount: number, subaccountAddr?: string) {
153
- return await this.sendSubaccountTx(
154
- (subaccountAddr) =>
155
- this.sendTx({
156
- function: `${this.config.deployment.package}::dex_accounts::withdraw_from_subaccount`,
157
- typeArguments: [],
158
- functionArguments: [subaccountAddr, this.config.deployment.usdc, amount],
159
- }),
160
- subaccountAddr,
161
- );
162
- }
163
-
164
- async configureUserSettingsForMarket({
165
- marketAddr,
166
- subaccountAddr,
167
- isCross,
168
- userLeverage,
169
- }: {
170
- marketAddr: string;
171
- subaccountAddr: string;
172
- isCross: boolean;
173
- userLeverage: number;
174
- }) {
175
- return await this.sendSubaccountTx(
176
- (subaccountAddr) =>
177
- this.sendTx({
178
- function: `${this.config.deployment.package}::dex_accounts::configure_user_settings_for_market`,
179
- typeArguments: [],
180
- functionArguments: [subaccountAddr, marketAddr, isCross, userLeverage],
181
- }),
182
- subaccountAddr,
183
- );
184
- }
185
-
186
- async placeOrder({
187
- marketName,
188
- price,
189
- size,
190
- isBuy,
191
- timeInForce,
192
- isReduceOnly,
193
- clientOrderId,
194
- stopPrice,
195
- tpTriggerPrice,
196
- tpLimitPrice,
197
- slTriggerPrice,
198
- slLimitPrice,
199
- builderAddr,
200
- builderFee,
201
- subaccountAddr,
202
- accountOverride,
203
- tickSize,
204
- }: {
205
- marketName: string;
206
- price: number;
207
- size: number;
208
- isBuy: boolean;
209
- timeInForce: TimeInForce;
210
- isReduceOnly: boolean;
211
- clientOrderId?: string;
212
- stopPrice?: number;
213
- tpTriggerPrice?: number;
214
- tpLimitPrice?: number;
215
- slTriggerPrice?: number;
216
- slLimitPrice?: number;
217
- builderAddr?: string;
218
- builderFee?: number;
219
- subaccountAddr?: string;
220
- /**
221
- * Optional account to use for the transaction. Primarily set as the session
222
- * account. If not provided, the default constructor account will be used
223
- */
224
- accountOverride?: Account;
225
- /**
226
- * Market tick size for price rounding. If not provided, no rounding is applied.
227
- */
228
- tickSize?: number;
229
- }): Promise<PlaceOrderResult> {
230
- try {
231
- const marketAddr = getMarketAddr(marketName, this.config.deployment.perpEngineGlobal);
232
-
233
- // Apply tick size rounding if tickSize is provided
234
- const roundedPrice = tickSize ? roundToTickSize(price, tickSize) : price;
235
- const roundedStopPrice =
236
- stopPrice !== undefined && tickSize ? roundToTickSize(stopPrice, tickSize) : stopPrice;
237
- const roundedTpTriggerPrice =
238
- tpTriggerPrice !== undefined && tickSize
239
- ? roundToTickSize(tpTriggerPrice, tickSize)
240
- : tpTriggerPrice;
241
- const roundedTpLimitPrice =
242
- tpLimitPrice !== undefined && tickSize
243
- ? roundToTickSize(tpLimitPrice, tickSize)
244
- : tpLimitPrice;
245
- const roundedSlTriggerPrice =
246
- slTriggerPrice !== undefined && tickSize
247
- ? roundToTickSize(slTriggerPrice, tickSize)
248
- : slTriggerPrice;
249
- const roundedSlLimitPrice =
250
- slLimitPrice !== undefined && tickSize
251
- ? roundToTickSize(slLimitPrice, tickSize)
252
- : slLimitPrice;
253
-
254
- const txResponse = await this.sendSubaccountTx(
255
- (subaccountAddr) =>
256
- this.sendTx(
257
- {
258
- function: `${this.config.deployment.package}::dex_accounts::place_order_to_subaccount`,
259
- typeArguments: [],
260
- functionArguments: [
261
- subaccountAddr,
262
- marketAddr.toString(),
263
- roundedPrice,
264
- size,
265
- isBuy,
266
- timeInForce,
267
- isReduceOnly,
268
- clientOrderId,
269
- roundedStopPrice,
270
- roundedTpTriggerPrice,
271
- roundedTpLimitPrice,
272
- roundedSlTriggerPrice,
273
- roundedSlLimitPrice,
274
- builderAddr,
275
- builderFee,
276
- ],
277
- },
278
- accountOverride,
279
- ),
280
- subaccountAddr,
281
- );
282
-
283
- // Extract order_id from the transaction events
284
- const orderId = this.extractOrderIdFromTransaction(txResponse, subaccountAddr);
285
-
286
- return {
287
- success: true,
288
- orderId: orderId || undefined,
289
- transactionHash: txResponse.hash,
290
- };
291
- } catch (error) {
292
- console.error("Error placing order:", error);
293
- return {
294
- success: false,
295
- error: error instanceof Error ? error.message : "Unknown error",
296
- };
297
- }
298
- }
299
-
300
- async triggerMatching({ marketAddr, maxWorkUnit }: { marketAddr: string; maxWorkUnit: number }) {
301
- const txResponse = await this.sendTx({
302
- function: `${this.config.deployment.package}::public_apis::trigger_matching`,
303
- typeArguments: [],
304
- functionArguments: [marketAddr, maxWorkUnit],
305
- });
306
- return {
307
- success: true,
308
- transactionHash: txResponse.hash,
309
- };
310
- }
311
-
312
- async placeTwapOrder({
313
- marketName,
314
- size,
315
- isBuy,
316
- isReduceOnly,
317
- // clientOrderId,
318
- twapFrequencySeconds,
319
- twapDurationSeconds,
320
- builderAddress,
321
- builderFees,
322
- subaccountAddr,
323
- accountOverride,
324
- }: {
325
- marketName: string;
326
- size: number;
327
- isBuy: boolean;
328
- isReduceOnly: boolean;
329
- // clientOrderId?: string;
330
- twapFrequencySeconds: number;
331
- twapDurationSeconds: number;
332
- builderAddress?: string;
333
- builderFees?: number;
334
- subaccountAddr?: string;
335
- /**
336
- * Optional account to use for the transaction. Primarily set as the session
337
- * account. If not provided, the default constructor account will be used
338
- */
339
- accountOverride?: Account;
340
- }) {
341
- const marketAddr = getMarketAddr(marketName, this.config.deployment.perpEngineGlobal);
342
- const txResponse = await this.sendSubaccountTx(
343
- (subaccountAddr) =>
344
- this.sendTx(
345
- {
346
- // TODO: update to place_twap_order_to_subaccount_v2 once available
347
- function: `${this.config.deployment.package}::dex_accounts::place_twap_order_to_subaccount`,
348
- typeArguments: [],
349
- functionArguments: [
350
- subaccountAddr,
351
- marketAddr.toString(),
352
- size,
353
- isBuy,
354
- isReduceOnly,
355
- // clientOrderId, // TODO: include once v2 is available
356
- twapFrequencySeconds,
357
- twapDurationSeconds,
358
- builderAddress,
359
- builderFees,
360
- ],
361
- },
362
- accountOverride,
363
- ),
364
- subaccountAddr,
365
- );
366
-
367
- const orderId = this.extractOrderIdFromTransaction(txResponse, subaccountAddr);
368
-
369
- return {
370
- success: true,
371
- orderId: orderId || undefined,
372
- transactionHash: txResponse.hash,
373
- };
374
- }
375
-
376
- /**
377
- * Cancel an order on the exchange
378
- * @param orderId The id of the order to cancel
379
- * @param marketId The id of the market the order is in
380
- * @param subaccountAddr Optional subaccount address, will use primary if not provided
381
- * @returns Transaction response
382
- */
383
- async cancelOrder({
384
- orderId,
385
- subaccountAddr,
386
- accountOverride,
387
- ...args
388
- }: {
389
- orderId: number | string;
390
-
391
- subaccountAddr?: string;
392
- /**
393
- * Optional account to use for the transaction. Primarily set as the session
394
- * account. If not provided, the default constructor account will be used
395
- */
396
- accountOverride?: Account;
397
- } & ({ marketName: string } | { marketAddr: string })) {
398
- // Either marketName or marketAddr must be provided
399
- const marketAddr =
400
- "marketName" in args
401
- ? getMarketAddr(args.marketName, this.config.deployment.perpEngineGlobal)
402
- : args.marketAddr;
403
-
404
- return await this.sendSubaccountTx(
405
- (subaccountAddr) =>
406
- this.sendTx(
407
- {
408
- function: `${this.config.deployment.package}::dex_accounts::cancel_order_to_subaccount`,
409
- typeArguments: [],
410
- functionArguments: [subaccountAddr, BigInt(orderId.toString()), marketAddr.toString()],
411
- },
412
- accountOverride,
413
- ),
414
- subaccountAddr,
415
- );
416
- }
417
-
418
- async cancelClientOrder({
419
- clientOrderId,
420
- marketName,
421
- subaccountAddr,
422
- accountOverride,
423
- }: {
424
- clientOrderId: string;
425
- marketName: string;
426
- subaccountAddr?: string;
427
- /**
428
- * Optional account to use for the transaction. Primarily set as the session
429
- * account. If not provided, the default constructor account will be used
430
- */
431
- accountOverride?: Account;
432
- }) {
433
- const marketAddr = getMarketAddr(marketName, this.config.deployment.perpEngineGlobal);
434
- return await this.sendSubaccountTx(
435
- (subaccountAddr) =>
436
- this.sendTx(
437
- {
438
- function: `${this.config.deployment.package}::dex_accounts::cancel_client_order_to_subaccount`,
439
- typeArguments: [],
440
- functionArguments: [subaccountAddr, clientOrderId, marketAddr.toString()],
441
- },
442
- accountOverride,
443
- ),
444
- subaccountAddr,
445
- );
446
- }
447
-
448
- async delegateTradingToForSubaccount({
449
- subaccountAddr,
450
- accountToDelegateTo,
451
- expirationTimestampSecs,
452
- }: {
453
- subaccountAddr: string;
454
- accountToDelegateTo: string;
455
- expirationTimestampSecs?: number;
456
- }) {
457
- return await this.sendSubaccountTx(
458
- (subaccountAddr) =>
459
- this.sendTx({
460
- function: `${this.config.deployment.package}::dex_accounts::delegate_trading_to_for_subaccount`,
461
- typeArguments: [],
462
- functionArguments: [subaccountAddr, accountToDelegateTo, expirationTimestampSecs ?? null],
463
- }),
464
- subaccountAddr,
465
- );
466
- }
467
-
468
- async revokeDelegation({
469
- subaccountAddr,
470
- accountToRevoke,
471
- }: {
472
- subaccountAddr?: string;
473
- accountToRevoke: string;
474
- }) {
475
- return await this.sendSubaccountTx(
476
- (subaccountAddr) =>
477
- this.sendTx({
478
- function: `${this.config.deployment.package}::dex_accounts::revoke_delegation`,
479
- typeArguments: [],
480
- functionArguments: [subaccountAddr, accountToRevoke],
481
- }),
482
- subaccountAddr,
483
- );
484
- }
485
-
486
- /**
487
- * Place a TP/SL order for a position
488
- */
489
- async placeTpSlOrderForPosition({
490
- marketAddr,
491
- tpTriggerPrice,
492
- tpLimitPrice,
493
- tpSize,
494
- slTriggerPrice,
495
- slLimitPrice,
496
- slSize,
497
- subaccountAddr,
498
- accountOverride,
499
- tickSize,
500
- }: {
501
- marketAddr: string;
502
- tpTriggerPrice?: number;
503
- tpLimitPrice?: number;
504
- tpSize?: number;
505
- slTriggerPrice?: number;
506
- slLimitPrice?: number;
507
- slSize?: number;
508
- subaccountAddr?: string;
509
- accountOverride?: Account;
510
- tickSize?: number;
511
- }) {
512
- const roundedTpTriggerPrice =
513
- tpTriggerPrice !== undefined && tickSize
514
- ? roundToTickSize(tpTriggerPrice, tickSize)
515
- : tpTriggerPrice;
516
- const roundedTpLimitPrice =
517
- tpLimitPrice !== undefined && tickSize
518
- ? roundToTickSize(tpLimitPrice, tickSize)
519
- : tpLimitPrice;
520
- const roundedSlTriggerPrice =
521
- slTriggerPrice !== undefined && tickSize
522
- ? roundToTickSize(slTriggerPrice, tickSize)
523
- : slTriggerPrice;
524
- const roundedSlLimitPrice =
525
- slLimitPrice !== undefined && tickSize
526
- ? roundToTickSize(slLimitPrice, tickSize)
527
- : slLimitPrice;
528
-
529
- return await this.sendSubaccountTx(
530
- (subaccountAddr) =>
531
- this.sendTx(
532
- {
533
- function: `${this.config.deployment.package}::dex_accounts::place_tp_sl_order_for_position`,
534
- typeArguments: [],
535
- functionArguments: [
536
- subaccountAddr,
537
- marketAddr,
538
- roundedTpTriggerPrice,
539
- roundedTpLimitPrice,
540
- tpSize,
541
- roundedSlTriggerPrice,
542
- roundedSlLimitPrice,
543
- slSize,
544
- undefined, // builderAddr
545
- undefined, // builderFees
546
- ],
547
- },
548
- accountOverride,
549
- ),
550
- subaccountAddr,
551
- );
552
- }
553
-
554
- /**
555
- * Update TP for a position
556
- */
557
- async updateTpOrderForPosition({
558
- marketAddr,
559
- prevOrderId,
560
- tpTriggerPrice,
561
- tpLimitPrice,
562
- tpSize,
563
- subaccountAddr,
564
- accountOverride,
565
- }: {
566
- marketAddr: string;
567
- prevOrderId: number | string;
568
- tpTriggerPrice?: number;
569
- tpLimitPrice?: number;
570
- tpSize?: number;
571
- subaccountAddr?: string;
572
- accountOverride?: Account;
573
- }) {
574
- return await this.sendSubaccountTx(
575
- (subaccountAddr) =>
576
- this.sendTx(
577
- {
578
- function: `${this.config.deployment.package}::dex_accounts::update_tp_order_for_position`,
579
- typeArguments: [],
580
- functionArguments: [
581
- subaccountAddr,
582
- BigInt(prevOrderId.toString()),
583
- marketAddr,
584
- tpTriggerPrice,
585
- tpLimitPrice,
586
- tpSize,
587
- ],
588
- },
589
- accountOverride,
590
- ),
591
- subaccountAddr,
592
- );
593
- }
594
-
595
- /**
596
- * Update SL for a position
597
- */
598
- async updateSlOrderForPosition({
599
- marketAddr,
600
- prevOrderId,
601
- slTriggerPrice,
602
- slLimitPrice,
603
- slSize,
604
- subaccountAddr,
605
- accountOverride,
606
- }: {
607
- marketAddr: string;
608
- prevOrderId: number | string;
609
- slTriggerPrice?: number;
610
- slLimitPrice?: number;
611
- slSize?: number;
612
- subaccountAddr?: string;
613
- accountOverride?: Account;
614
- }) {
615
- return await this.sendSubaccountTx(
616
- (subaccountAddr) =>
617
- this.sendTx(
618
- {
619
- function: `${this.config.deployment.package}::dex_accounts::update_sl_order_for_position`,
620
- typeArguments: [],
621
- functionArguments: [
622
- subaccountAddr,
623
- BigInt(prevOrderId.toString()),
624
- marketAddr,
625
- slTriggerPrice,
626
- slLimitPrice,
627
- slSize,
628
- ],
629
- },
630
- accountOverride,
631
- ),
632
- subaccountAddr,
633
- );
634
- }
635
-
636
- /**
637
- * Cancel a TP/SL order for a position
638
- */
639
- async cancelTpSlOrderForPosition({
640
- marketAddr,
641
- orderId,
642
- subaccountAddr,
643
- accountOverride,
644
- }: {
645
- marketAddr: string;
646
- orderId: number | string;
647
- subaccountAddr?: string;
648
- accountOverride?: Account;
649
- }) {
650
- return await this.sendSubaccountTx(
651
- (subaccountAddr) =>
652
- this.sendTx(
653
- {
654
- function: `${this.config.deployment.package}::dex_accounts::cancel_tp_sl_order_for_position`,
655
- typeArguments: [],
656
- functionArguments: [subaccountAddr, marketAddr, BigInt(orderId.toString())],
657
- },
658
- accountOverride,
659
- ),
660
- subaccountAddr,
661
- );
662
- }
663
-
664
- async cancelTwapOrder({
665
- orderId,
666
- marketAddr,
667
- subaccountAddr,
668
- accountOverride,
669
- }: {
670
- orderId: string;
671
- marketAddr: string;
672
- subaccountAddr?: string;
673
- /**
674
- * Optional account to use for the transaction. Primarily set as the session
675
- * account. If not provided, the default constructor account will be used
676
- */
677
- accountOverride?: Account;
678
- }) {
679
- return await this.sendSubaccountTx(
680
- (subaccountAddr) =>
681
- this.sendTx(
682
- {
683
- function: `${this.config.deployment.package}::dex_accounts::cancel_twap_orders_to_subaccount`,
684
- typeArguments: [],
685
- functionArguments: [subaccountAddr, marketAddr, orderId],
686
- },
687
- accountOverride,
688
- ),
689
- subaccountAddr,
690
- );
691
- }
692
-
693
- async buildDeactiveSubaccountTx({
694
- subaccountAddr,
695
- revokeAllDelegations = true,
696
- signerAddress,
697
- }: WithSignerAddress<{
698
- subaccountAddr: string;
699
- revokeAllDelegations: boolean;
700
- }>) {
701
- const transaction = await this.buildTx(
702
- {
703
- function: `${this.config.deployment.package}::dex_accounts::deactivate_subaccount`,
704
- typeArguments: [],
705
- functionArguments: [subaccountAddr, revokeAllDelegations],
706
- },
707
- signerAddress,
708
- );
709
- return transaction;
710
- }
711
-
712
- // ======= VAULT FUNCTIONS =======
713
-
714
- // @Todo: We can move this to another Class and this doesnt requires subaccount so dont belong in here
715
- /**
716
- * Create a new vault with optional initial funding
717
- */
718
- async buildCreateVaultTx({
719
- contributionAssetType,
720
- vaultName,
721
- vaultShareSymbol,
722
- vaultShareIconUri = "",
723
- vaultShareProjectUri = "",
724
- feeBps,
725
- feeIntervalS,
726
- contributionLockupDurationS,
727
- initialFunding = 0,
728
- acceptsContributions = false,
729
- delegateToCreator = false,
730
- signerAddress,
731
- vaultDescription,
732
- vaultSocialLinks,
733
- }: WithSignerAddress<CreateVaultArgs>) {
734
- const vaultApiModule = getVaultApiModule(this.config.compatVersion);
735
- const transaction = await this.buildTx(
736
- {
737
- function: `${this.config.deployment.package}::${vaultApiModule}::create_and_fund_vault`,
738
- typeArguments: [],
739
- functionArguments: [
740
- null,
741
- contributionAssetType,
742
- vaultName,
743
- vaultDescription,
744
- vaultSocialLinks,
745
- vaultShareSymbol,
746
- vaultShareIconUri,
747
- vaultShareProjectUri,
748
- feeBps,
749
- feeIntervalS,
750
- contributionLockupDurationS,
751
- initialFunding,
752
- acceptsContributions,
753
- delegateToCreator,
754
- ],
755
- },
756
- signerAddress,
757
- );
758
-
759
- return transaction;
760
- }
761
-
762
- async createVault(
763
- args: CreateVaultArgs & {
764
- /**
765
- * Optional account to use for the transaction. Primarily set as the session
766
- * account. If not provided, the default constructor account will be used
767
- */
768
- accountOverride?: Account;
769
- subaccountAddr?: string;
770
- },
771
- ) {
772
- const vaultApiModule = getVaultApiModule(this.config.compatVersion);
773
- const txResponse = await this.sendSubaccountTx(
774
- () =>
775
- this.sendTx(
776
- {
777
- function: `${this.config.deployment.package}::${vaultApiModule}::create_and_fund_vault`,
778
- typeArguments: [],
779
- functionArguments: [
780
- args.subaccountAddr ?? null,
781
- args.contributionAssetType,
782
- args.vaultName,
783
- args.vaultDescription,
784
- args.vaultSocialLinks,
785
- args.vaultShareSymbol,
786
- args.vaultShareIconUri,
787
- args.vaultShareProjectUri,
788
- args.feeBps,
789
- args.feeIntervalS,
790
- args.contributionLockupDurationS,
791
- args.initialFunding,
792
- args.acceptsContributions,
793
- args.delegateToCreator,
794
- ],
795
- },
796
- args.accountOverride,
797
- ),
798
- args.subaccountAddr,
799
- );
800
-
801
- return txResponse;
802
- }
803
-
804
- /**
805
- * Activate a vault to accept contributions
806
- */
807
- async buildActivateVaultTx({
808
- vaultAddress,
809
- additionalFunding = 0,
810
- signerAddress,
811
- }: WithSignerAddress<ActivateVaultArgs>) {
812
- const vaultApiModule = getVaultApiModule(this.config.compatVersion);
813
- return await this.buildTx(
814
- {
815
- function: `${this.config.deployment.package}::${vaultApiModule}::activate_vault`,
816
- typeArguments: [],
817
- functionArguments: [vaultAddress, additionalFunding],
818
- },
819
- signerAddress,
820
- );
821
- }
822
-
823
- /**
824
- * Contribute funds to a vault in exchange for shares
825
- */
826
- async buildDepositToVaultTx({
827
- vaultAddress,
828
- amount,
829
- signerAddress,
830
- }: WithSignerAddress<DepositToVaultArgs>) {
831
- const vaultApiModule = getVaultApiModule(this.config.compatVersion);
832
- return await this.buildTx(
833
- {
834
- function: `${this.config.deployment.package}::${vaultApiModule}::contribute`,
835
- typeArguments: [],
836
- functionArguments: [vaultAddress, amount],
837
- },
838
- signerAddress,
839
- );
840
- }
841
-
842
- async depositToVault(
843
- args: DepositToVaultArgs & {
844
- subaccountAddr: string;
845
- },
846
- ) {
847
- const txResponse = await this.sendSubaccountTx(
848
- (subaccountAddr) =>
849
- this.sendTx({
850
- function: `${this.config.deployment.package}::dex_accounts_vault_extension::contribute_to_vault`,
851
- typeArguments: [],
852
- functionArguments: [
853
- subaccountAddr,
854
- args.vaultAddress,
855
- this.config.deployment.usdc,
856
- args.amount,
857
- ],
858
- }),
859
- args.subaccountAddr,
860
- );
861
-
862
- return txResponse;
863
- }
864
-
865
- /**
866
- * Redeem shares from a vault for underlying assets
867
- */
868
- async buildWithdrawFromVaultTx({
869
- vaultAddress,
870
- shares,
871
- signerAddress,
872
- }: WithSignerAddress<WithdrawFromVaultArgs>) {
873
- return await this.buildTx(
874
- {
875
- function: `${this.config.deployment.package}::vault_api::redeem`,
876
- typeArguments: [],
877
- functionArguments: [vaultAddress, shares],
878
- },
879
- signerAddress,
880
- );
881
- }
882
-
883
- async withdrawFromVault(
884
- args: WithdrawFromVaultArgs & {
885
- /**
886
- * Optional account to use for the transaction. Primarily set as the session
887
- * account. If not provided, the default constructor account will be used
888
- */
889
- accountOverride?: Account;
890
- subaccountAddr?: string;
891
- },
892
- ) {
893
- const txResponse = await this.sendSubaccountTx(
894
- (subaccountAddr) =>
895
- this.sendTx(
896
- {
897
- function: `${this.config.deployment.package}::dex_accounts_vault_extension::redeem_from_vault`,
898
- typeArguments: [],
899
- functionArguments: [subaccountAddr, args.vaultAddress, args.shares],
900
- },
901
- args.accountOverride,
902
- ),
903
- args.subaccountAddr,
904
- );
905
-
906
- return txResponse;
907
- }
908
- /**
909
- * Delegate trading to another account for a vault
910
- */
911
- async buildDelegateDexActionsToTx({
912
- vaultAddress,
913
- accountToDelegateTo,
914
- signerAddress,
915
- expirationTimestampSecs,
916
- }: WithSignerAddress<{
917
- vaultAddress: string;
918
- accountToDelegateTo: string;
919
- expirationTimestampSecs?: number;
920
- }>) {
921
- return await this.buildTx(
922
- {
923
- function: `${this.config.deployment.package}::vault::delegate_dex_actions_to`,
924
- typeArguments: [],
925
- functionArguments: [vaultAddress, accountToDelegateTo, expirationTimestampSecs],
926
- },
927
- signerAddress,
928
- );
929
- }
930
-
931
- /**
932
- * Approve max builder fee for a subaccount
933
- * @param builderAddr The address of the builder
934
- * @param maxFee The maximum fee in basis points (e.g., 100 = 0.01%)
935
- * @param subaccountAddr Optional subaccount address, will use primary if not provided
936
- */
937
- async approveMaxBuilderFee({
938
- builderAddr,
939
- maxFee,
940
- subaccountAddr,
941
- }: {
942
- builderAddr: string;
943
- maxFee: number;
944
- subaccountAddr?: string;
945
- }) {
946
- return await this.sendSubaccountTx(
947
- (subaccountAddr) =>
948
- this.sendTx({
949
- function: `${this.config.deployment.package}::dex_accounts::approve_max_builder_fee_for_subaccount`,
950
- typeArguments: [],
951
- functionArguments: [subaccountAddr, builderAddr, maxFee],
952
- }),
953
- subaccountAddr,
954
- );
955
- }
956
-
957
- /**
958
- * Revoke max builder fee for a subaccount
959
- * @param builderAddr The address of the builder
960
- * @param subaccountAddr Optional subaccount address, will use primary if not provided
961
- */
962
- async revokeMaxBuilderFee({
963
- builderAddr,
964
- subaccountAddr,
965
- }: {
966
- builderAddr: string;
967
- subaccountAddr?: string;
968
- }) {
969
- return await this.sendSubaccountTx(
970
- (subaccountAddr) =>
971
- this.sendTx({
972
- function: `${this.config.deployment.package}::dex_accounts::revoke_max_builder_fee_for_subaccount`,
973
- typeArguments: [],
974
- functionArguments: [subaccountAddr, builderAddr],
975
- }),
976
- subaccountAddr,
977
- );
978
- }
979
- }