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

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 (149) 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 +736 -200
  17. package/lib/clearingHouseConfig.d.ts +1 -0
  18. package/lib/clearingHouseUser.d.ts +24 -16
  19. package/lib/clearingHouseUser.js +223 -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 +1603 -377
  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 +6 -2
  50. package/lib/math/orders.js +62 -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 +236 -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 +1232 -323
  80. package/src/clearingHouseConfig.ts +1 -0
  81. package/src/clearingHouseUser.ts +343 -155
  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/sort.js +44 -0
  94. package/src/events/txEventCache.js +71 -0
  95. package/src/events/types.ts +6 -0
  96. package/src/examples/makeTradeExample.js +80 -0
  97. package/src/factory/bigNum.js +390 -0
  98. package/src/factory/bigNum.ts +42 -13
  99. package/src/factory/oracleClient.js +20 -0
  100. package/src/idl/clearing_house.json +1603 -377
  101. package/src/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  102. package/src/index.ts +9 -3
  103. package/src/math/amm.ts +54 -55
  104. package/src/math/auction.js +42 -0
  105. package/src/math/auction.ts +5 -1
  106. package/src/math/bankBalance.ts +148 -2
  107. package/src/math/conversion.js +11 -0
  108. package/src/math/funding.js +248 -0
  109. package/src/math/margin.ts +124 -0
  110. package/src/math/market.ts +66 -1
  111. package/src/math/oracles.js +26 -0
  112. package/src/math/oracles.ts +42 -5
  113. package/src/math/orders.ts +129 -13
  114. package/src/math/position.ts +64 -9
  115. package/src/math/repeg.js +128 -0
  116. package/src/math/state.js +15 -0
  117. package/src/math/trade.js +253 -0
  118. package/src/math/trade.ts +23 -25
  119. package/src/math/utils.js +0 -1
  120. package/src/oracles/oracleClientCache.js +19 -0
  121. package/src/oracles/pythClient.js +46 -0
  122. package/src/oracles/quoteAssetOracleClient.js +32 -0
  123. package/src/oracles/switchboardClient.js +69 -0
  124. package/src/oracles/types.js +2 -0
  125. package/src/orderParams.js +20 -0
  126. package/src/orderParams.ts +20 -141
  127. package/src/slot/SlotSubscriber.js +39 -0
  128. package/src/slot/SlotSubscriber.ts +11 -1
  129. package/src/token/index.js +38 -0
  130. package/src/tokenFaucet.js +189 -0
  131. package/src/{mockUSDCFaucet.ts → tokenFaucet.ts} +82 -70
  132. package/src/tx/retryTxSender.ts +11 -3
  133. package/src/tx/types.js +2 -0
  134. package/src/tx/utils.js +17 -0
  135. package/src/tx/utils.ts +1 -1
  136. package/src/types.ts +239 -27
  137. package/src/userName.js +20 -0
  138. package/src/util/computeUnits.js +21 -11
  139. package/src/util/computeUnits.ts +1 -1
  140. package/src/util/getTokenAddress.js +9 -0
  141. package/src/util/getTokenAddress.ts +18 -0
  142. package/src/util/promiseTimeout.js +14 -0
  143. package/src/util/tps.js +27 -0
  144. package/src/wallet.js +35 -0
  145. package/tests/bn/test.ts +10 -0
  146. package/lib/orders.d.ts +0 -8
  147. package/lib/orders.js +0 -142
  148. package/src/orders.ts +0 -251
  149. 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 = {
@@ -206,6 +326,8 @@ export type StateAccount = {
206
326
  numberOfMarkets: BN;
207
327
  numberOfBanks: BN;
208
328
  minOrderQuoteAssetAmount: BN;
329
+ maxAuctionDuration: number;
330
+ minAuctionDuration: number;
209
331
  };
210
332
 
211
333
  export type MarketAccount = {
@@ -219,9 +341,13 @@ export type MarketAccount = {
219
341
  openInterest: BN;
220
342
  marginRatioInitial: number;
221
343
  marginRatioMaintenance: number;
222
- marginRatioPartial: number;
223
344
  nextFillRecordId: BN;
224
345
  pnlPool: PoolBalance;
346
+ liquidationFee: BN;
347
+ imfFactor: BN;
348
+ unrealizedImfFactor: BN;
349
+ unrealizedInitialAssetWeight: number;
350
+ unrealizedMaintenanceAssetWeight: number;
225
351
  };
226
352
 
227
353
  export type BankAccount = {
@@ -239,12 +365,20 @@ export type BankAccount = {
239
365
  cumulativeBorrowInterest: BN;
240
366
  depositBalance: BN;
241
367
  borrowBalance: BN;
242
- lastUpdated: BN;
368
+ lastInterestTs: BN;
369
+ lastTwapTs: BN;
243
370
  oracle: PublicKey;
244
371
  initialAssetWeight: BN;
245
372
  maintenanceAssetWeight: BN;
246
373
  initialLiabilityWeight: BN;
247
374
  maintenanceLiabilityWeight: BN;
375
+ liquidationFee: BN;
376
+ imfFactor: BN;
377
+
378
+ withdrawGuardThreshold: BN;
379
+ depositTokenTwap: BN;
380
+ borrowTokenTwap: BN;
381
+ utilizationTwap: BN;
248
382
  };
249
383
 
250
384
  export type PoolBalance = {
@@ -258,9 +392,13 @@ export type AMM = {
258
392
  lastFundingRate: BN;
259
393
  lastFundingRateTs: BN;
260
394
  lastMarkPriceTwap: BN;
395
+ lastMarkPriceTwap5min: BN;
261
396
  lastMarkPriceTwapTs: BN;
262
397
  lastOraclePriceTwap: BN;
398
+ lastOraclePriceTwap5min: BN;
263
399
  lastOraclePriceTwapTs: BN;
400
+ lastOracleMarkSpreadPct: BN;
401
+ lastOracleConfPct: BN;
264
402
  oracle: PublicKey;
265
403
  oracleSource: OracleSource;
266
404
  fundingPeriod: BN;
@@ -268,13 +406,20 @@ export type AMM = {
268
406
  pegMultiplier: BN;
269
407
  cumulativeFundingRateLong: BN;
270
408
  cumulativeFundingRateShort: BN;
409
+ cumulativeFundingRateLp: BN;
271
410
  cumulativeRepegRebateLong: BN;
272
411
  cumulativeRepegRebateShort: BN;
273
412
  totalFeeMinusDistributions: BN;
274
413
  totalFeeWithdrawn: BN;
275
414
  totalFee: BN;
415
+ cumulativeFundingPaymentPerLp: BN;
416
+ cumulativeFeePerLp: BN;
417
+ cumulativeNetBaseAssetAmountPerLp: BN;
418
+ userLpShares: BN;
276
419
  minimumQuoteAssetTradeSize: BN;
277
420
  baseAssetAmountStepSize: BN;
421
+ maxBaseAssetAmountRatio: number;
422
+ maxSlippageRatio: number;
278
423
  lastOraclePrice: BN;
279
424
  baseSpread: number;
280
425
  curveUpdateIntensity: number;
@@ -292,6 +437,10 @@ export type AMM = {
292
437
  longSpread: BN;
293
438
  shortSpread: BN;
294
439
  maxSpread: number;
440
+ marketPosition: UserPosition;
441
+ marketPositionPerLp: UserPosition;
442
+ maxBaseAssetReserve: BN;
443
+ minBaseAssetReserve: BN;
295
444
  };
296
445
 
297
446
  // # User Account Types
@@ -302,27 +451,46 @@ export type UserPosition = {
302
451
  quoteAssetAmount: BN;
303
452
  quoteEntryAmount: BN;
304
453
  openOrders: BN;
305
- unsettledPnl: BN;
306
454
  openBids: BN;
307
455
  openAsks: BN;
456
+ realizedPnl: BN;
457
+ lpShares: BN;
458
+ lastFeePerLp: BN;
459
+ lastNetBaseAssetAmountPerLp: BN;
460
+ lastNetQuoteAssetAmountPerLp: BN;
308
461
  };
309
462
 
310
- export type UserAccount = {
311
- authority: PublicKey;
312
- name: number[];
313
- userId: number;
314
- bankBalances: UserBankBalance[];
315
- collateral: BN;
316
- cumulativeDeposits: BN;
463
+ export type UserStatsAccount = {
464
+ numberOfUsers: number;
465
+ makerVolume30D: BN;
466
+ takerVolume30D: BN;
467
+ fillerVolume30D: BN;
468
+ lastMakerVolume30DTs: BN;
469
+ lastTakerVolume30DTs: BN;
470
+ lastFillerVolume30DTs: BN;
317
471
  fees: {
318
472
  totalFeePaid: BN;
319
473
  totalFeeRebate: BN;
320
474
  totalTokenDiscount: BN;
321
- totalReferralReward: BN;
322
475
  totalRefereeDiscount: BN;
323
476
  };
477
+ referrer: PublicKey;
478
+ isReferrer: boolean;
479
+ totalReferrerReward: BN;
480
+ authority: PublicKey;
481
+ };
482
+
483
+ export type UserAccount = {
484
+ authority: PublicKey;
485
+ name: number[];
486
+ userId: number;
487
+ bankBalances: UserBankBalance[];
324
488
  positions: UserPosition[];
325
489
  orders: Order[];
490
+ beingLiquidated: boolean;
491
+ bankrupt: boolean;
492
+ nextLiquidationId: number;
493
+ nextOrderId: BN;
326
494
  };
327
495
 
328
496
  export type UserBankBalance = {
@@ -350,9 +518,7 @@ export type Order = {
350
518
  triggerPrice: BN;
351
519
  triggerCondition: OrderTriggerCondition;
352
520
  triggered: boolean;
353
- discountTier: OrderDiscountTier;
354
521
  existingPositionDirection: PositionDirection;
355
- referrer: PublicKey;
356
522
  postOnly: boolean;
357
523
  immediateOrCancel: boolean;
358
524
  oraclePriceOffset: BN;
@@ -365,7 +531,6 @@ export type OrderParams = {
365
531
  orderType: OrderType;
366
532
  userOrderId: number;
367
533
  direction: PositionDirection;
368
- quoteAssetAmount: BN;
369
534
  baseAssetAmount: BN;
370
535
  price: BN;
371
536
  marketIndex: BN;
@@ -384,11 +549,57 @@ export type OrderParams = {
384
549
  };
385
550
  };
386
551
 
552
+ export type NecessaryOrderParams = {
553
+ orderType: OrderType;
554
+ marketIndex: BN;
555
+ baseAssetAmount: BN;
556
+ direction: PositionDirection;
557
+ };
558
+
559
+ export type OptionalOrderParams = {
560
+ [Property in keyof OrderParams]?: OrderParams[Property];
561
+ } & NecessaryOrderParams;
562
+
563
+ export const DefaultOrderParams = {
564
+ orderType: OrderType.MARKET,
565
+ userOrderId: 0,
566
+ direction: PositionDirection.LONG,
567
+ baseAssetAmount: ZERO,
568
+ price: ZERO,
569
+ marketIndex: ZERO,
570
+ reduceOnly: false,
571
+ postOnly: false,
572
+ immediateOrCancel: false,
573
+ triggerPrice: ZERO,
574
+ triggerCondition: OrderTriggerCondition.ABOVE,
575
+ positionLimit: ZERO,
576
+ oraclePriceOffset: ZERO,
577
+ padding0: ZERO,
578
+ padding1: ZERO,
579
+ optionalAccounts: {
580
+ discountToken: false,
581
+ referrer: false,
582
+ },
583
+ };
584
+
387
585
  export type MakerInfo = {
388
586
  maker: PublicKey;
587
+ makerStats: PublicKey;
389
588
  order: Order;
390
589
  };
391
590
 
591
+ export type TakerInfo = {
592
+ taker: PublicKey;
593
+ takerStats: PublicKey;
594
+ takerUserAccount: UserAccount;
595
+ order: Order;
596
+ };
597
+
598
+ export type ReferrerInfo = {
599
+ referrer: PublicKey;
600
+ referrerStats: PublicKey;
601
+ };
602
+
392
603
  // # Misc Types
393
604
  export interface IWallet {
394
605
  signTransaction(tx: Transaction): Promise<Transaction>;
@@ -430,6 +641,7 @@ export type FeeStructure = {
430
641
  makerRebateNumerator: BN;
431
642
  makerRebateDenominator: BN;
432
643
  fillerRewardStructure: OrderFillerRewardStructure;
644
+ cancelOrderFee: BN;
433
645
  };
434
646
 
435
647
  export type OracleGuardRails = {
@@ -451,4 +663,4 @@ export type OrderFillerRewardStructure = {
451
663
  timeBasedRewardLowerBound: BN;
452
664
  };
453
665
 
454
- export type MarginCategory = 'Initial' | 'Partial' | 'Maintenance';
666
+ 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;