@drift-labs/sdk 0.2.0-master.2 → 0.2.0-master.20

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 (152) hide show
  1. package/lib/accounts/bulkUserStatsSubscription.d.ts +7 -0
  2. package/lib/accounts/bulkUserStatsSubscription.js +21 -0
  3. package/lib/accounts/bulkUserSubscription.js +0 -1
  4. package/lib/accounts/fetch.d.ts +2 -1
  5. package/lib/accounts/fetch.js +9 -1
  6. package/lib/accounts/pollingUserStatsAccountSubscriber.d.ts +27 -0
  7. package/lib/accounts/pollingUserStatsAccountSubscriber.js +113 -0
  8. package/lib/accounts/types.d.ts +14 -1
  9. package/lib/accounts/webSocketUserStatsAccountSubsriber.d.ts +20 -0
  10. package/lib/accounts/webSocketUserStatsAccountSubsriber.js +47 -0
  11. package/lib/addresses/pda.d.ts +1 -0
  12. package/lib/addresses/pda.js +8 -1
  13. package/lib/admin.d.ts +9 -5
  14. package/lib/admin.js +52 -11
  15. package/lib/clearingHouse.d.ts +52 -23
  16. package/lib/clearingHouse.js +727 -197
  17. package/lib/clearingHouseConfig.d.ts +1 -0
  18. package/lib/clearingHouseUser.d.ts +17 -17
  19. package/lib/clearingHouseUser.js +186 -101
  20. package/lib/clearingHouseUserStats.d.ts +18 -0
  21. package/lib/clearingHouseUserStats.js +49 -0
  22. package/lib/clearingHouseUserStatsConfig.d.ts +14 -0
  23. package/lib/clearingHouseUserStatsConfig.js +2 -0
  24. package/lib/config.js +1 -1
  25. package/lib/constants/banks.d.ts +2 -2
  26. package/lib/constants/banks.js +12 -4
  27. package/lib/constants/numericConstants.d.ts +5 -0
  28. package/lib/constants/numericConstants.js +8 -3
  29. package/lib/events/eventList.js +3 -0
  30. package/lib/events/types.d.ts +3 -1
  31. package/lib/events/types.js +2 -0
  32. package/lib/factory/bigNum.d.ts +1 -0
  33. package/lib/factory/bigNum.js +34 -10
  34. package/lib/idl/clearing_house.json +1609 -388
  35. package/lib/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  36. package/lib/index.d.ts +9 -3
  37. package/lib/index.js +13 -3
  38. package/lib/math/amm.d.ts +1 -0
  39. package/lib/math/amm.js +22 -38
  40. package/lib/math/auction.js +4 -1
  41. package/lib/math/bankBalance.d.ts +7 -1
  42. package/lib/math/bankBalance.js +77 -2
  43. package/lib/math/margin.d.ts +11 -0
  44. package/lib/math/margin.js +72 -0
  45. package/lib/math/market.d.ts +4 -1
  46. package/lib/math/market.js +35 -1
  47. package/lib/math/oracles.d.ts +3 -0
  48. package/lib/math/oracles.js +25 -5
  49. package/lib/math/orders.d.ts +5 -2
  50. package/lib/math/orders.js +53 -12
  51. package/lib/math/position.d.ts +8 -0
  52. package/lib/math/position.js +45 -12
  53. package/lib/math/trade.d.ts +1 -1
  54. package/lib/math/trade.js +7 -10
  55. package/lib/orderParams.d.ts +14 -5
  56. package/lib/orderParams.js +8 -96
  57. package/lib/slot/SlotSubscriber.d.ts +7 -0
  58. package/lib/slot/SlotSubscriber.js +3 -0
  59. package/lib/{mockUSDCFaucet.d.ts → tokenFaucet.d.ts} +8 -5
  60. package/lib/{mockUSDCFaucet.js → tokenFaucet.js} +63 -51
  61. package/lib/tx/retryTxSender.js +9 -2
  62. package/lib/tx/utils.js +1 -1
  63. package/lib/types.d.ts +233 -26
  64. package/lib/types.js +64 -1
  65. package/lib/util/computeUnits.js +1 -1
  66. package/lib/util/getTokenAddress.d.ts +2 -0
  67. package/lib/util/getTokenAddress.js +9 -0
  68. package/package.json +3 -3
  69. package/src/accounts/bulkUserStatsSubscription.ts +33 -0
  70. package/src/accounts/bulkUserSubscription.ts +0 -1
  71. package/src/accounts/fetch.ts +27 -2
  72. package/src/accounts/pollingUserStatsAccountSubscriber.ts +172 -0
  73. package/src/accounts/types.ts +18 -0
  74. package/src/accounts/webSocketUserStatsAccountSubsriber.ts +80 -0
  75. package/src/addresses/marketAddresses.js +26 -0
  76. package/src/addresses/pda.ts +13 -0
  77. package/src/admin.ts +82 -15
  78. package/src/assert/assert.js +9 -0
  79. package/src/clearingHouse.ts +1224 -319
  80. package/src/clearingHouseConfig.ts +1 -0
  81. package/src/clearingHouseUser.ts +311 -148
  82. package/src/clearingHouseUserStats.ts +75 -0
  83. package/src/clearingHouseUserStatsConfig.ts +18 -0
  84. package/src/config.ts +1 -1
  85. package/src/constants/banks.js +42 -0
  86. package/src/constants/banks.ts +14 -4
  87. package/src/constants/markets.js +42 -0
  88. package/src/constants/numericConstants.js +41 -0
  89. package/src/constants/numericConstants.ts +14 -2
  90. package/src/events/eventList.js +77 -0
  91. package/src/events/eventList.ts +3 -0
  92. package/src/events/eventSubscriber.js +139 -0
  93. package/src/events/fetchLogs.js +50 -0
  94. package/src/events/pollingLogProvider.js +64 -0
  95. package/src/events/sort.js +44 -0
  96. package/src/events/txEventCache.js +71 -0
  97. package/src/events/types.ts +6 -0
  98. package/src/events/webSocketLogProvider.js +41 -0
  99. package/src/examples/makeTradeExample.js +80 -0
  100. package/src/factory/bigNum.js +390 -0
  101. package/src/factory/bigNum.ts +42 -13
  102. package/src/factory/oracleClient.js +20 -0
  103. package/src/idl/clearing_house.json +1609 -388
  104. package/src/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  105. package/src/index.ts +9 -3
  106. package/src/math/amm.ts +54 -55
  107. package/src/math/auction.js +42 -0
  108. package/src/math/auction.ts +5 -1
  109. package/src/math/bankBalance.ts +148 -2
  110. package/src/math/conversion.js +11 -0
  111. package/src/math/funding.js +248 -0
  112. package/src/math/margin.ts +124 -0
  113. package/src/math/market.ts +66 -1
  114. package/src/math/oracles.js +26 -0
  115. package/src/math/oracles.ts +42 -5
  116. package/src/math/orders.ts +112 -13
  117. package/src/math/position.ts +64 -9
  118. package/src/math/repeg.js +128 -0
  119. package/src/math/state.js +15 -0
  120. package/src/math/trade.js +253 -0
  121. package/src/math/trade.ts +23 -25
  122. package/src/math/utils.js +0 -1
  123. package/src/oracles/oracleClientCache.js +19 -0
  124. package/src/oracles/pythClient.js +46 -0
  125. package/src/oracles/quoteAssetOracleClient.js +32 -0
  126. package/src/oracles/switchboardClient.js +69 -0
  127. package/src/oracles/types.js +2 -0
  128. package/src/orderParams.js +20 -0
  129. package/src/orderParams.ts +20 -141
  130. package/src/slot/SlotSubscriber.js +39 -0
  131. package/src/slot/SlotSubscriber.ts +11 -1
  132. package/src/token/index.js +38 -0
  133. package/src/tokenFaucet.js +189 -0
  134. package/src/{mockUSDCFaucet.ts → tokenFaucet.ts} +82 -70
  135. package/src/tx/retryTxSender.ts +11 -3
  136. package/src/tx/types.js +2 -0
  137. package/src/tx/utils.js +17 -0
  138. package/src/tx/utils.ts +1 -1
  139. package/src/types.ts +236 -27
  140. package/src/userName.js +20 -0
  141. package/src/util/computeUnits.js +21 -11
  142. package/src/util/computeUnits.ts +1 -1
  143. package/src/util/getTokenAddress.js +9 -0
  144. package/src/util/getTokenAddress.ts +18 -0
  145. package/src/util/promiseTimeout.js +14 -0
  146. package/src/util/tps.js +27 -0
  147. package/src/wallet.js +35 -0
  148. package/tests/bn/test.ts +10 -0
  149. package/lib/orders.d.ts +0 -8
  150. package/lib/orders.js +0 -142
  151. package/src/orders.ts +0 -251
  152. package/src/util/computeUnits.js.map +0 -1
package/src/types.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { PublicKey, Transaction } from '@solana/web3.js';
2
- import { BN } from '.';
2
+ import { BN, ZERO } from '.';
3
3
 
4
4
  // # Utility Types / Enums / Constants
5
5
  export class SwapDirection {
@@ -17,6 +17,11 @@ export class PositionDirection {
17
17
  static readonly SHORT = { short: {} };
18
18
  }
19
19
 
20
+ export class DepositDirection {
21
+ static readonly DEPOSIT = { deposit: {} };
22
+ static readonly WITHDRAW = { withdraw: {} };
23
+ }
24
+
20
25
  export class OracleSource {
21
26
  static readonly PYTH = { pyth: {} };
22
27
  static readonly SWITCHBOARD = { switchboard: {} };
@@ -51,6 +56,25 @@ export class OrderAction {
51
56
  static readonly TRIGGER = { trigger: {} };
52
57
  }
53
58
 
59
+ export class OrderActionExplanation {
60
+ static readonly NONE = { none: {} };
61
+ static readonly BREACHED_MARGIN_REQUIREMENT = {
62
+ breachedMarginRequirement: {},
63
+ };
64
+ static readonly ORACLE_PRICE_BREACHED_LIMIT_PRICE = {
65
+ oraclePriceBreachedLimitPrice: {},
66
+ };
67
+ static readonly MARKET_ORDER_FILLED_TO_LIMIT_PRICE = {
68
+ marketOrderFilledToLimitPrice: {},
69
+ };
70
+ static readonly CANCELED_FOR_LIQUIDATION = {
71
+ canceledForLiquidation: {},
72
+ };
73
+ static readonly MARKET_ORDER_AUCTION_EXPIRED = {
74
+ marketOrderAuctionExpired: {},
75
+ };
76
+ }
77
+
54
78
  export class OrderTriggerCondition {
55
79
  static readonly ABOVE = { above: {} };
56
80
  static readonly BELOW = { below: {} };
@@ -82,6 +106,15 @@ export type CandleResolution =
82
106
  | 'W'
83
107
  | 'M';
84
108
 
109
+ export type NewUserRecord = {
110
+ ts: BN;
111
+ userAuthority: PublicKey;
112
+ user: PublicKey;
113
+ userId: number;
114
+ name: number[];
115
+ referrer: PublicKey;
116
+ };
117
+
85
118
  export type DepositRecord = {
86
119
  ts: BN;
87
120
  userAuthority: PublicKey;
@@ -92,6 +125,8 @@ export type DepositRecord = {
92
125
  };
93
126
  bankIndex: BN;
94
127
  amount: BN;
128
+ oraclePrice: BN;
129
+ referrer: PublicKey;
95
130
  from?: PublicKey;
96
131
  to?: PublicKey;
97
132
  };
@@ -142,20 +177,99 @@ export type FundingPaymentRecord = {
142
177
 
143
178
  export type LiquidationRecord = {
144
179
  ts: BN;
145
- recordId: BN;
146
- userAuthority: PublicKey;
147
180
  user: PublicKey;
148
- partial: boolean;
149
- baseAssetValue: BN;
150
- baseAssetValueClosed: BN;
151
- liquidationFee: BN;
152
- feeToLiquidator: BN;
153
- feeToInsuranceFund: BN;
154
181
  liquidator: PublicKey;
182
+ liquidationType: LiquidationType;
183
+ marginRequirement: BN;
155
184
  totalCollateral: BN;
156
- collateral: BN;
157
- unrealizedPnl: BN;
158
- marginRatio: BN;
185
+ liquidationId: number;
186
+ liquidatePerp: LiquidatePerpRecord;
187
+ liquidateBorrow: LiquidateBorrowRecord;
188
+ liquidateBorrowForPerpPnl: LiquidateBorrowForPerpPnlRecord;
189
+ liquidatePerpPnlForDeposit: LiquidatePerpPnlForDepositRecord;
190
+ perpBankruptcy: PerpBankruptcyRecord;
191
+ borrowBankruptcy: BorrowBankruptcyRecord;
192
+ };
193
+
194
+ export class LiquidationType {
195
+ static readonly LIQUIDATE_PERP = { liquidatePerp: {} };
196
+ static readonly LIQUIDATE_BORROW = { liquidateBorrow: {} };
197
+ static readonly LIQUIDATE_BORROW_FOR_PERP_PNL = {
198
+ liquidateBorrowForPerpPnl: {},
199
+ };
200
+ static readonly LIQUIDATE_PERP_PNL_FOR_DEPOSIT = {
201
+ liquidatePerpPnlForDeposit: {},
202
+ };
203
+ static readonly PERP_BANKRUPTCY = {
204
+ perpBankruptcy: {},
205
+ };
206
+ static readonly BORROW_BANKRUPTCY = {
207
+ borrowBankruptcy: {},
208
+ };
209
+ }
210
+
211
+ export type LiquidatePerpRecord = {
212
+ marketIndex: BN;
213
+ orderIds: BN[];
214
+ oraclePrice: BN;
215
+ baseAssetAmount: BN;
216
+ quoteAssetAmount: BN;
217
+ userPnl: BN;
218
+ liquidatorPnl: BN;
219
+ canceledOrdersFee: BN;
220
+ userOrderId: BN;
221
+ liquidatorOrderId: BN;
222
+ fillRecordId: BN;
223
+ };
224
+
225
+ export type LiquidateBorrowRecord = {
226
+ assetBankIndex: BN;
227
+ assetPrice: BN;
228
+ assetTransfer: BN;
229
+ liabilityBankIndex: BN;
230
+ liabilityPrice: BN;
231
+ liabilityTransfer: BN;
232
+ };
233
+
234
+ export type LiquidateBorrowForPerpPnlRecord = {
235
+ marketIndex: BN;
236
+ marketOraclePrice: BN;
237
+ pnlTransfer: BN;
238
+ liabilityBankIndex: BN;
239
+ liabilityPrice: BN;
240
+ liabilityTransfer: BN;
241
+ };
242
+
243
+ export type LiquidatePerpPnlForDepositRecord = {
244
+ marketIndex: BN;
245
+ marketOraclePrice: BN;
246
+ pnlTransfer: BN;
247
+ assetBankIndex: BN;
248
+ assetPrice: BN;
249
+ assetTransfer: BN;
250
+ };
251
+
252
+ export type PerpBankruptcyRecord = {
253
+ marketIndex: BN;
254
+ pnl: BN;
255
+ cumulativeFundingRateDelta: BN;
256
+ };
257
+
258
+ export type BorrowBankruptcyRecord = {
259
+ bankIndex: BN;
260
+ borrowAmount: BN;
261
+ cumulativeDepositInterestDelta: BN;
262
+ };
263
+
264
+ export type SettlePnlRecord = {
265
+ ts: BN;
266
+ user: PublicKey;
267
+ marketIndex: BN;
268
+ pnl: BN;
269
+ baseAssetAmount: BN;
270
+ quoteAssetAmountAfter: BN;
271
+ quoteEntryamount: BN;
272
+ settlePrice: BN;
159
273
  };
160
274
 
161
275
  export type OrderRecord = {
@@ -164,7 +278,10 @@ export type OrderRecord = {
164
278
  maker: PublicKey;
165
279
  takerOrder: Order;
166
280
  makerOrder: Order;
281
+ takerPnl: BN;
282
+ makerPnl: BN;
167
283
  action: OrderAction;
284
+ actionExplanation: OrderActionExplanation;
168
285
  filler: PublicKey;
169
286
  fillRecordId: BN;
170
287
  marketIndex: BN;
@@ -175,6 +292,9 @@ export type OrderRecord = {
175
292
  fillerReward: BN;
176
293
  quoteAssetAmountSurplus: BN;
177
294
  oraclePrice: BN;
295
+ referrer: PublicKey;
296
+ referrerReward: BN;
297
+ refereeDiscount: BN;
178
298
  };
179
299
 
180
300
  export type StateAccount = {
@@ -219,9 +339,13 @@ export type MarketAccount = {
219
339
  openInterest: BN;
220
340
  marginRatioInitial: number;
221
341
  marginRatioMaintenance: number;
222
- marginRatioPartial: number;
223
342
  nextFillRecordId: BN;
224
343
  pnlPool: PoolBalance;
344
+ liquidationFee: BN;
345
+ imfFactor: BN;
346
+ unrealizedImfFactor: BN;
347
+ unrealizedInitialAssetWeight: number;
348
+ unrealizedMaintenanceAssetWeight: number;
225
349
  };
226
350
 
227
351
  export type BankAccount = {
@@ -239,12 +363,20 @@ export type BankAccount = {
239
363
  cumulativeBorrowInterest: BN;
240
364
  depositBalance: BN;
241
365
  borrowBalance: BN;
242
- lastUpdated: BN;
366
+ lastInterestTs: BN;
367
+ lastTwapTs: BN;
243
368
  oracle: PublicKey;
244
369
  initialAssetWeight: BN;
245
370
  maintenanceAssetWeight: BN;
246
371
  initialLiabilityWeight: BN;
247
372
  maintenanceLiabilityWeight: BN;
373
+ liquidationFee: BN;
374
+ imfFactor: BN;
375
+
376
+ withdrawGuardThreshold: BN;
377
+ depositTokenTwap: BN;
378
+ borrowTokenTwap: BN;
379
+ utilizationTwap: BN;
248
380
  };
249
381
 
250
382
  export type PoolBalance = {
@@ -258,9 +390,13 @@ export type AMM = {
258
390
  lastFundingRate: BN;
259
391
  lastFundingRateTs: BN;
260
392
  lastMarkPriceTwap: BN;
393
+ lastMarkPriceTwap5min: BN;
261
394
  lastMarkPriceTwapTs: BN;
262
395
  lastOraclePriceTwap: BN;
396
+ lastOraclePriceTwap5min: BN;
263
397
  lastOraclePriceTwapTs: BN;
398
+ lastOracleMarkSpreadPct: BN;
399
+ lastOracleConfPct: BN;
264
400
  oracle: PublicKey;
265
401
  oracleSource: OracleSource;
266
402
  fundingPeriod: BN;
@@ -268,13 +404,20 @@ export type AMM = {
268
404
  pegMultiplier: BN;
269
405
  cumulativeFundingRateLong: BN;
270
406
  cumulativeFundingRateShort: BN;
407
+ cumulativeFundingRateLp: BN;
271
408
  cumulativeRepegRebateLong: BN;
272
409
  cumulativeRepegRebateShort: BN;
273
410
  totalFeeMinusDistributions: BN;
274
411
  totalFeeWithdrawn: BN;
275
412
  totalFee: BN;
413
+ cumulativeFundingPaymentPerLp: BN;
414
+ cumulativeFeePerLp: BN;
415
+ cumulativeNetBaseAssetAmountPerLp: BN;
416
+ userLpShares: BN;
276
417
  minimumQuoteAssetTradeSize: BN;
277
418
  baseAssetAmountStepSize: BN;
419
+ maxBaseAssetAmountRatio: number;
420
+ maxSlippageRatio: number;
278
421
  lastOraclePrice: BN;
279
422
  baseSpread: number;
280
423
  curveUpdateIntensity: number;
@@ -292,6 +435,10 @@ export type AMM = {
292
435
  longSpread: BN;
293
436
  shortSpread: BN;
294
437
  maxSpread: number;
438
+ marketPosition: UserPosition;
439
+ marketPositionPerLp: UserPosition;
440
+ maxBaseAssetReserve: BN;
441
+ minBaseAssetReserve: BN;
295
442
  };
296
443
 
297
444
  // # User Account Types
@@ -302,27 +449,46 @@ export type UserPosition = {
302
449
  quoteAssetAmount: BN;
303
450
  quoteEntryAmount: BN;
304
451
  openOrders: BN;
305
- unsettledPnl: BN;
306
452
  openBids: BN;
307
453
  openAsks: BN;
454
+ realizedPnl: BN;
455
+ lpShares: BN;
456
+ lastFeePerLp: BN;
457
+ lastNetBaseAssetAmountPerLp: BN;
458
+ lastNetQuoteAssetAmountPerLp: BN;
308
459
  };
309
460
 
310
- export type UserAccount = {
311
- authority: PublicKey;
312
- name: number[];
313
- userId: number;
314
- bankBalances: UserBankBalance[];
315
- collateral: BN;
316
- cumulativeDeposits: BN;
461
+ export type UserStatsAccount = {
462
+ numberOfUsers: number;
463
+ makerVolume30D: BN;
464
+ takerVolume30D: BN;
465
+ fillerVolume30D: BN;
466
+ lastMakerVolume30DTs: BN;
467
+ lastTakerVolume30DTs: BN;
468
+ lastFillerVolume30DTs: BN;
317
469
  fees: {
318
470
  totalFeePaid: BN;
319
471
  totalFeeRebate: BN;
320
472
  totalTokenDiscount: BN;
321
- totalReferralReward: BN;
322
473
  totalRefereeDiscount: BN;
323
474
  };
475
+ referrer: PublicKey;
476
+ isReferrer: boolean;
477
+ totalReferrerReward: BN;
478
+ authority: PublicKey;
479
+ };
480
+
481
+ export type UserAccount = {
482
+ authority: PublicKey;
483
+ name: number[];
484
+ userId: number;
485
+ bankBalances: UserBankBalance[];
324
486
  positions: UserPosition[];
325
487
  orders: Order[];
488
+ beingLiquidated: boolean;
489
+ bankrupt: boolean;
490
+ nextLiquidationId: number;
491
+ nextOrderId: BN;
326
492
  };
327
493
 
328
494
  export type UserBankBalance = {
@@ -350,9 +516,7 @@ export type Order = {
350
516
  triggerPrice: BN;
351
517
  triggerCondition: OrderTriggerCondition;
352
518
  triggered: boolean;
353
- discountTier: OrderDiscountTier;
354
519
  existingPositionDirection: PositionDirection;
355
- referrer: PublicKey;
356
520
  postOnly: boolean;
357
521
  immediateOrCancel: boolean;
358
522
  oraclePriceOffset: BN;
@@ -365,7 +529,6 @@ export type OrderParams = {
365
529
  orderType: OrderType;
366
530
  userOrderId: number;
367
531
  direction: PositionDirection;
368
- quoteAssetAmount: BN;
369
532
  baseAssetAmount: BN;
370
533
  price: BN;
371
534
  marketIndex: BN;
@@ -384,11 +547,56 @@ export type OrderParams = {
384
547
  };
385
548
  };
386
549
 
550
+ export type NecessaryOrderParams = {
551
+ orderType: OrderType;
552
+ marketIndex: BN;
553
+ baseAssetAmount: BN;
554
+ direction: PositionDirection;
555
+ };
556
+
557
+ export type OptionalOrderParams = {
558
+ [Property in keyof OrderParams]?: OrderParams[Property];
559
+ } & NecessaryOrderParams;
560
+
561
+ export const DefaultOrderParams = {
562
+ orderType: OrderType.MARKET,
563
+ userOrderId: 0,
564
+ direction: PositionDirection.LONG,
565
+ baseAssetAmount: ZERO,
566
+ price: ZERO,
567
+ marketIndex: ZERO,
568
+ reduceOnly: false,
569
+ postOnly: false,
570
+ immediateOrCancel: false,
571
+ triggerPrice: ZERO,
572
+ triggerCondition: OrderTriggerCondition.ABOVE,
573
+ positionLimit: ZERO,
574
+ oraclePriceOffset: ZERO,
575
+ padding0: ZERO,
576
+ padding1: ZERO,
577
+ optionalAccounts: {
578
+ discountToken: false,
579
+ referrer: false,
580
+ },
581
+ };
582
+
387
583
  export type MakerInfo = {
388
584
  maker: PublicKey;
585
+ makerStats: PublicKey;
389
586
  order: Order;
390
587
  };
391
588
 
589
+ export type TakerInfo = {
590
+ taker: PublicKey;
591
+ takerStats: PublicKey;
592
+ order: Order;
593
+ };
594
+
595
+ export type ReferrerInfo = {
596
+ referrer: PublicKey;
597
+ referrerStats: PublicKey;
598
+ };
599
+
392
600
  // # Misc Types
393
601
  export interface IWallet {
394
602
  signTransaction(tx: Transaction): Promise<Transaction>;
@@ -430,6 +638,7 @@ export type FeeStructure = {
430
638
  makerRebateNumerator: BN;
431
639
  makerRebateDenominator: BN;
432
640
  fillerRewardStructure: OrderFillerRewardStructure;
641
+ cancelOrderFee: BN;
433
642
  };
434
643
 
435
644
  export type OracleGuardRails = {
@@ -451,4 +660,4 @@ export type OrderFillerRewardStructure = {
451
660
  timeBasedRewardLowerBound: BN;
452
661
  };
453
662
 
454
- export type MarginCategory = 'Initial' | 'Partial' | 'Maintenance';
663
+ export type MarginCategory = 'Initial' | 'Maintenance';
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.decodeName = exports.encodeName = exports.DEFAULT_USER_NAME = exports.MAX_NAME_LENGTH = void 0;
4
+ exports.MAX_NAME_LENGTH = 32;
5
+ exports.DEFAULT_USER_NAME = 'Main Account';
6
+ function encodeName(name) {
7
+ if (name.length > exports.MAX_NAME_LENGTH) {
8
+ throw Error(`User name (${name}) longer than 32 characters`);
9
+ }
10
+ const buffer = Buffer.alloc(32);
11
+ buffer.fill(name);
12
+ buffer.fill(' ', name.length);
13
+ return Array(...buffer);
14
+ }
15
+ exports.encodeName = encodeName;
16
+ function decodeName(bytes) {
17
+ const buffer = Buffer.from(bytes);
18
+ return buffer.toString('utf8').trim();
19
+ }
20
+ exports.decodeName = decodeName;
@@ -1,17 +1,27 @@
1
1
  "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
2
11
  Object.defineProperty(exports, "__esModule", { value: true });
3
12
  exports.findComputeUnitConsumption = void 0;
4
- async function findComputeUnitConsumption(programId, connection, txSignature, commitment = 'confirmed') {
5
- const tx = await connection.getTransaction(txSignature, { commitment });
6
- const computeUnits = [];
7
- const regex = new RegExp(`Program ${programId.toString()} consumed ([0-9]{0,6}) of 200000 compute units`);
8
- tx.meta.logMessages.forEach((logMessage) => {
9
- const match = logMessage.match(regex);
10
- if (match && match[1]) {
11
- computeUnits.push(match[1]);
12
- }
13
+ function findComputeUnitConsumption(programId, connection, txSignature, commitment = 'confirmed') {
14
+ return __awaiter(this, void 0, void 0, function* () {
15
+ const tx = yield connection.getTransaction(txSignature, { commitment });
16
+ const computeUnits = [];
17
+ const regex = new RegExp(`Program ${programId.toString()} consumed ([0-9]{0,6}) of ([0-9]{0,7}) compute units`);
18
+ tx.meta.logMessages.forEach((logMessage) => {
19
+ const match = logMessage.match(regex);
20
+ if (match && match[1]) {
21
+ computeUnits.push(match[1]);
22
+ }
23
+ });
24
+ return computeUnits;
13
25
  });
14
- return computeUnits;
15
26
  }
16
27
  exports.findComputeUnitConsumption = findComputeUnitConsumption;
17
- //# sourceMappingURL=computeUnits.js.map
@@ -9,7 +9,7 @@ export async function findComputeUnitConsumption(
9
9
  const tx = await connection.getTransaction(txSignature, { commitment });
10
10
  const computeUnits = [];
11
11
  const regex = new RegExp(
12
- `Program ${programId.toString()} consumed ([0-9]{0,6}) of 200000 compute units`
12
+ `Program ${programId.toString()} consumed ([0-9]{0,6}) of ([0-9]{0,7}) compute units`
13
13
  );
14
14
  tx.meta.logMessages.forEach((logMessage) => {
15
15
  const match = logMessage.match(regex);
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getTokenAddress = void 0;
4
+ const spl_token_1 = require("@solana/spl-token");
5
+ const web3_js_1 = require("@solana/web3.js");
6
+ const getTokenAddress = (mintAddress, userPubKey) => {
7
+ return spl_token_1.Token.getAssociatedTokenAddress(spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID, spl_token_1.TOKEN_PROGRAM_ID, new web3_js_1.PublicKey(mintAddress), new web3_js_1.PublicKey(userPubKey));
8
+ };
9
+ exports.getTokenAddress = getTokenAddress;
@@ -0,0 +1,18 @@
1
+ import {
2
+ Token,
3
+ ASSOCIATED_TOKEN_PROGRAM_ID,
4
+ TOKEN_PROGRAM_ID,
5
+ } from '@solana/spl-token';
6
+ import { PublicKey } from '@solana/web3.js';
7
+
8
+ export const getTokenAddress = (
9
+ mintAddress: string,
10
+ userPubKey: string
11
+ ): Promise<PublicKey> => {
12
+ return Token.getAssociatedTokenAddress(
13
+ ASSOCIATED_TOKEN_PROGRAM_ID,
14
+ TOKEN_PROGRAM_ID,
15
+ new PublicKey(mintAddress),
16
+ new PublicKey(userPubKey)
17
+ );
18
+ };
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.promiseTimeout = void 0;
4
+ function promiseTimeout(promise, timeoutMs) {
5
+ let timeoutId;
6
+ const timeoutPromise = new Promise((resolve) => {
7
+ timeoutId = setTimeout(() => resolve(null), timeoutMs);
8
+ });
9
+ return Promise.race([promise, timeoutPromise]).then((result) => {
10
+ clearTimeout(timeoutId);
11
+ return result;
12
+ });
13
+ }
14
+ exports.promiseTimeout = promiseTimeout;
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.estimateTps = void 0;
13
+ function estimateTps(programId, connection, failed) {
14
+ return __awaiter(this, void 0, void 0, function* () {
15
+ let signatures = yield connection.getSignaturesForAddress(programId, undefined, 'finalized');
16
+ if (failed) {
17
+ signatures = signatures.filter((signature) => signature.err);
18
+ }
19
+ const numberOfSignatures = signatures.length;
20
+ if (numberOfSignatures === 0) {
21
+ return 0;
22
+ }
23
+ return (numberOfSignatures /
24
+ (signatures[0].blockTime - signatures[numberOfSignatures - 1].blockTime));
25
+ });
26
+ }
27
+ exports.estimateTps = estimateTps;
package/src/wallet.js ADDED
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.Wallet = void 0;
13
+ class Wallet {
14
+ constructor(payer) {
15
+ this.payer = payer;
16
+ }
17
+ signTransaction(tx) {
18
+ return __awaiter(this, void 0, void 0, function* () {
19
+ tx.partialSign(this.payer);
20
+ return tx;
21
+ });
22
+ }
23
+ signAllTransactions(txs) {
24
+ return __awaiter(this, void 0, void 0, function* () {
25
+ return txs.map((t) => {
26
+ t.partialSign(this.payer);
27
+ return t;
28
+ });
29
+ });
30
+ }
31
+ get publicKey() {
32
+ return this.payer.publicKey;
33
+ }
34
+ }
35
+ exports.Wallet = Wallet;
package/tests/bn/test.ts CHANGED
@@ -125,6 +125,16 @@ describe('BigNum Tests', () => {
125
125
  expect(BigNum.fromPrint('1234567').toMillified(5)).to.equal('1.2345M');
126
126
  expect(BigNum.fromPrint('12345678').toMillified(5)).to.equal('12.345M');
127
127
  expect(BigNum.fromPrint('123456789').toMillified(5)).to.equal('123.45M');
128
+
129
+ expect(BigNum.from(-95, 2).print()).to.equal('-0.95');
130
+
131
+ // Case 6 strange numbers
132
+ expect(BigNum.from('-100', 2).print()).to.equal('-1.00');
133
+ expect(BigNum.from('-8402189', 13).print()).to.equal('-0.0000008402189');
134
+ expect(BigNum.from('-10000000000000', 13).print()).to.equal(
135
+ '-1.0000000000000'
136
+ );
137
+ expect(BigNum.from('-100', 6).print()).to.equal('-0.000100');
128
138
  });
129
139
 
130
140
  it('can initialise from string values correctly', () => {
package/lib/orders.d.ts DELETED
@@ -1,8 +0,0 @@
1
- /// <reference types="bn.js" />
2
- import { MarketAccount, Order, UserAccount, UserPosition } from './types';
3
- import { BN } from '.';
4
- import { OraclePriceData } from '.';
5
- export declare function calculateNewStateAfterOrder(userAccount: UserAccount, userPosition: UserPosition, market: MarketAccount, order: Order): [UserAccount, UserPosition, MarketAccount] | null;
6
- export declare function calculateBaseAssetAmountMarketCanExecute(market: MarketAccount, order: Order, oraclePriceData?: OraclePriceData): BN;
7
- export declare function calculateAmountToTradeForLimit(market: MarketAccount, order: Order, oraclePriceData?: OraclePriceData): BN;
8
- export declare function calculateAmountToTradeForTriggerLimit(market: MarketAccount, order: Order): BN;