@drift-labs/sdk 0.2.0-master.1 → 0.2.0-master.12

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 (142) hide show
  1. package/lib/accounts/types.d.ts +1 -0
  2. package/lib/admin.d.ts +8 -5
  3. package/lib/admin.js +43 -11
  4. package/lib/clearingHouse.d.ts +35 -20
  5. package/lib/clearingHouse.js +497 -154
  6. package/lib/clearingHouseUser.d.ts +12 -17
  7. package/lib/clearingHouseUser.js +97 -88
  8. package/lib/config.js +1 -1
  9. package/lib/constants/banks.d.ts +2 -2
  10. package/lib/constants/banks.js +12 -4
  11. package/lib/constants/numericConstants.d.ts +4 -0
  12. package/lib/constants/numericConstants.js +5 -1
  13. package/lib/events/eventList.js +3 -0
  14. package/lib/events/types.d.ts +2 -1
  15. package/lib/factory/bigNum.d.ts +9 -2
  16. package/lib/factory/bigNum.js +50 -16
  17. package/lib/idl/clearing_house.json +858 -177
  18. package/lib/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  19. package/lib/index.d.ts +4 -2
  20. package/lib/index.js +8 -2
  21. package/lib/math/amm.d.ts +6 -1
  22. package/lib/math/amm.js +124 -41
  23. package/lib/math/auction.js +4 -1
  24. package/lib/math/bankBalance.d.ts +3 -1
  25. package/lib/math/bankBalance.js +54 -1
  26. package/lib/math/margin.d.ts +11 -0
  27. package/lib/math/margin.js +72 -0
  28. package/lib/math/market.d.ts +4 -1
  29. package/lib/math/market.js +35 -1
  30. package/lib/math/orders.d.ts +2 -2
  31. package/lib/math/orders.js +18 -11
  32. package/lib/math/position.d.ts +8 -0
  33. package/lib/math/position.js +44 -12
  34. package/lib/math/repeg.js +1 -1
  35. package/lib/math/trade.d.ts +1 -1
  36. package/lib/math/trade.js +7 -10
  37. package/lib/orderParams.d.ts +14 -5
  38. package/lib/orderParams.js +8 -96
  39. package/lib/orders.d.ts +2 -4
  40. package/lib/orders.js +7 -161
  41. package/lib/slot/SlotSubscriber.d.ts +7 -0
  42. package/lib/slot/SlotSubscriber.js +3 -0
  43. package/lib/{mockUSDCFaucet.d.ts → tokenFaucet.d.ts} +8 -5
  44. package/lib/{mockUSDCFaucet.js → tokenFaucet.js} +63 -51
  45. package/lib/tx/retryTxSender.js +9 -2
  46. package/lib/tx/utils.js +1 -1
  47. package/lib/types.d.ts +159 -15
  48. package/lib/types.js +59 -1
  49. package/lib/util/computeUnits.js +1 -1
  50. package/lib/util/getTokenAddress.d.ts +2 -0
  51. package/lib/util/getTokenAddress.js +9 -0
  52. package/package.json +3 -3
  53. package/src/accounts/bulkAccountLoader.js +197 -0
  54. package/src/accounts/bulkUserSubscription.js +33 -0
  55. package/src/accounts/pollingClearingHouseAccountSubscriber.js +311 -0
  56. package/src/accounts/pollingOracleSubscriber.js +93 -0
  57. package/src/accounts/pollingTokenAccountSubscriber.js +90 -0
  58. package/src/accounts/pollingUserAccountSubscriber.js +132 -0
  59. package/src/accounts/types.js +10 -0
  60. package/src/accounts/utils.js +7 -0
  61. package/src/accounts/webSocketAccountSubscriber.js +93 -0
  62. package/src/accounts/webSocketClearingHouseAccountSubscriber.js +233 -0
  63. package/src/accounts/webSocketUserAccountSubscriber.js +62 -0
  64. package/src/addresses/marketAddresses.js +26 -0
  65. package/src/admin.ts +66 -14
  66. package/src/assert/assert.js +9 -0
  67. package/src/clearingHouse.ts +836 -254
  68. package/src/clearingHouseConfig.js +2 -0
  69. package/src/clearingHouseUser.ts +219 -121
  70. package/src/clearingHouseUserConfig.js +2 -0
  71. package/src/config.ts +1 -1
  72. package/src/constants/banks.js +42 -0
  73. package/src/constants/banks.ts +14 -4
  74. package/src/constants/markets.js +42 -0
  75. package/src/constants/numericConstants.js +41 -0
  76. package/src/constants/numericConstants.ts +5 -0
  77. package/src/events/eventList.js +77 -0
  78. package/src/events/eventList.ts +3 -0
  79. package/src/events/eventSubscriber.js +139 -0
  80. package/src/events/fetchLogs.js +50 -0
  81. package/src/events/pollingLogProvider.js +64 -0
  82. package/src/events/sort.js +44 -0
  83. package/src/events/txEventCache.js +71 -0
  84. package/src/events/types.js +20 -0
  85. package/src/events/types.ts +2 -0
  86. package/src/events/webSocketLogProvider.js +41 -0
  87. package/src/examples/makeTradeExample.js +80 -0
  88. package/src/factory/bigNum.js +390 -0
  89. package/src/factory/bigNum.ts +65 -18
  90. package/src/factory/oracleClient.js +20 -0
  91. package/src/idl/clearing_house.json +858 -177
  92. package/src/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  93. package/src/index.js +69 -0
  94. package/src/index.ts +4 -2
  95. package/src/math/amm.js +369 -0
  96. package/src/math/amm.ts +207 -52
  97. package/src/math/auction.js +42 -0
  98. package/src/math/auction.ts +5 -1
  99. package/src/math/bankBalance.ts +98 -1
  100. package/src/math/conversion.js +11 -0
  101. package/src/math/funding.js +248 -0
  102. package/src/math/margin.ts +124 -0
  103. package/src/math/market.ts +66 -1
  104. package/src/math/oracles.js +26 -0
  105. package/src/math/orders.ts +17 -13
  106. package/src/math/position.ts +63 -9
  107. package/src/math/repeg.js +128 -0
  108. package/src/math/repeg.ts +2 -1
  109. package/src/math/state.js +15 -0
  110. package/src/math/trade.js +253 -0
  111. package/src/math/trade.ts +23 -25
  112. package/src/math/utils.js +0 -1
  113. package/src/mockUSDCFaucet.js +280 -0
  114. package/src/oracles/oracleClientCache.js +19 -0
  115. package/src/oracles/pythClient.js +46 -0
  116. package/src/oracles/quoteAssetOracleClient.js +32 -0
  117. package/src/oracles/switchboardClient.js +69 -0
  118. package/src/oracles/types.js +2 -0
  119. package/src/orderParams.js +20 -0
  120. package/src/orderParams.ts +20 -141
  121. package/src/orders.ts +10 -287
  122. package/src/slot/SlotSubscriber.js +39 -0
  123. package/src/slot/SlotSubscriber.ts +11 -1
  124. package/src/token/index.js +38 -0
  125. package/src/tokenFaucet.js +189 -0
  126. package/src/{mockUSDCFaucet.ts → tokenFaucet.ts} +82 -70
  127. package/src/tx/retryTxSender.ts +11 -3
  128. package/src/tx/types.js +2 -0
  129. package/src/tx/utils.js +17 -0
  130. package/src/tx/utils.ts +1 -1
  131. package/src/types.js +125 -0
  132. package/src/types.ts +155 -17
  133. package/src/userName.js +20 -0
  134. package/src/util/computeUnits.js +21 -11
  135. package/src/util/computeUnits.ts +1 -1
  136. package/src/util/getTokenAddress.js +9 -0
  137. package/src/util/getTokenAddress.ts +18 -0
  138. package/src/util/promiseTimeout.js +14 -0
  139. package/src/util/tps.js +27 -0
  140. package/src/wallet.js +35 -0
  141. package/tests/bn/test.ts +2 -0
  142. 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: {} };
@@ -48,6 +53,26 @@ export class OrderAction {
48
53
  static readonly CANCEL = { cancel: {} };
49
54
  static readonly EXPIRE = { expire: {} };
50
55
  static readonly FILL = { fill: {} };
56
+ static readonly TRIGGER = { trigger: {} };
57
+ }
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
+ };
51
76
  }
52
77
 
53
78
  export class OrderTriggerCondition {
@@ -91,6 +116,7 @@ export type DepositRecord = {
91
116
  };
92
117
  bankIndex: BN;
93
118
  amount: BN;
119
+ oraclePrice: BN;
94
120
  from?: PublicKey;
95
121
  to?: PublicKey;
96
122
  };
@@ -141,20 +167,78 @@ export type FundingPaymentRecord = {
141
167
 
142
168
  export type LiquidationRecord = {
143
169
  ts: BN;
144
- recordId: BN;
145
- userAuthority: PublicKey;
146
170
  user: PublicKey;
147
- partial: boolean;
148
- baseAssetValue: BN;
149
- baseAssetValueClosed: BN;
150
- liquidationFee: BN;
151
- feeToLiquidator: BN;
152
- feeToInsuranceFund: BN;
153
171
  liquidator: PublicKey;
172
+ liquidationType: LiquidationType;
173
+ marginRequirement: BN;
154
174
  totalCollateral: BN;
155
- collateral: BN;
156
- unrealizedPnl: BN;
157
- marginRatio: BN;
175
+ liquidationId: number;
176
+ liquidatePerp: LiquidatePerpRecord;
177
+ liquidateBorrow: LiquidateBorrowRecord;
178
+ liquidateBorrowForPerpPnl: LiquidateBorrowForPerpPnlRecord;
179
+ liquidatePerpPnlForDeposit: LiquidatePerpPnlForDepositRecord;
180
+ };
181
+
182
+ export class LiquidationType {
183
+ static readonly LIQUIDATE_PERP = { liquidatePerp: {} };
184
+ static readonly LIQUIDATE_BORROW = { liquidateBorrow: {} };
185
+ static readonly LIQUIDATE_BORROW_FOR_PERP_PNL = {
186
+ liquidateBorrowForPerpPnl: {},
187
+ };
188
+ static readonly LIQUIDATE_PERP_PNL_FOR_DEPOSIT = {
189
+ liquidatePerpPnlForDeposit: {},
190
+ };
191
+ }
192
+
193
+ export type LiquidatePerpRecord = {
194
+ marketIndex: BN;
195
+ orderIds: BN[];
196
+ oraclePrice: BN;
197
+ baseAssetAmount: BN;
198
+ quoteAssetAmount: BN;
199
+ userPnl: BN;
200
+ liquidatorPnl: BN;
201
+ canceledOrdersFee: BN;
202
+ userOrderId: BN;
203
+ liquidatorOrderId: BN;
204
+ fillRecordId: BN;
205
+ };
206
+
207
+ export type LiquidateBorrowRecord = {
208
+ assetBankIndex: BN;
209
+ assetPrice: BN;
210
+ assetTransfer: BN;
211
+ liabilityBankIndex: BN;
212
+ liabilityPrice: BN;
213
+ liabilityTransfer: BN;
214
+ };
215
+
216
+ export type LiquidateBorrowForPerpPnlRecord = {
217
+ marketIndex: BN;
218
+ marketOraclePrice: BN;
219
+ pnlTransfer: BN;
220
+ liabilityBankIndex: BN;
221
+ liabilityPrice: BN;
222
+ liabilityTransfer: BN;
223
+ };
224
+
225
+ export type LiquidatePerpPnlForDepositRecord = {
226
+ marketIndex: BN;
227
+ marketOraclePrice: BN;
228
+ pnlTransfer: BN;
229
+ assetBankIndex: BN;
230
+ assetPrice: BN;
231
+ assetTransfer: BN;
232
+ };
233
+
234
+ export type SettlePnlRecord = {
235
+ ts: BN;
236
+ marketIndex: BN;
237
+ pnl: BN;
238
+ baseAssetAmount: BN;
239
+ quoteAssetAmountAfter: BN;
240
+ quoteEntryamount: BN;
241
+ oraclePrice: BN;
158
242
  };
159
243
 
160
244
  export type OrderRecord = {
@@ -163,7 +247,10 @@ export type OrderRecord = {
163
247
  maker: PublicKey;
164
248
  takerOrder: Order;
165
249
  makerOrder: Order;
250
+ takerPnl: BN;
251
+ makerPnl: BN;
166
252
  action: OrderAction;
253
+ actionExplanation: OrderActionExplanation;
167
254
  filler: PublicKey;
168
255
  fillRecordId: BN;
169
256
  marketIndex: BN;
@@ -218,9 +305,13 @@ export type MarketAccount = {
218
305
  openInterest: BN;
219
306
  marginRatioInitial: number;
220
307
  marginRatioMaintenance: number;
221
- marginRatioPartial: number;
222
308
  nextFillRecordId: BN;
223
309
  pnlPool: PoolBalance;
310
+ liquidationFee: BN;
311
+ imfFactor: BN;
312
+ unsettledImfFactor: BN;
313
+ unsettledInitialAssetWeight: number;
314
+ unsettledMaintenanceAssetWeight: number;
224
315
  };
225
316
 
226
317
  export type BankAccount = {
@@ -244,6 +335,8 @@ export type BankAccount = {
244
335
  maintenanceAssetWeight: BN;
245
336
  initialLiabilityWeight: BN;
246
337
  maintenanceLiabilityWeight: BN;
338
+ liquidationFee: BN;
339
+ imfFactor: BN;
247
340
  };
248
341
 
249
342
  export type PoolBalance = {
@@ -260,6 +353,8 @@ export type AMM = {
260
353
  lastMarkPriceTwapTs: BN;
261
354
  lastOraclePriceTwap: BN;
262
355
  lastOraclePriceTwapTs: BN;
356
+ lastOracleMarkSpreadPct: BN;
357
+ lastOracleConfPct: BN;
263
358
  oracle: PublicKey;
264
359
  oracleSource: OracleSource;
265
360
  fundingPeriod: BN;
@@ -274,6 +369,8 @@ export type AMM = {
274
369
  totalFee: BN;
275
370
  minimumQuoteAssetTradeSize: BN;
276
371
  baseAssetAmountStepSize: BN;
372
+ maxBaseAssetAmountRatio: number;
373
+ maxSlippageRatio: number;
277
374
  lastOraclePrice: BN;
278
375
  baseSpread: number;
279
376
  curveUpdateIntensity: number;
@@ -290,6 +387,7 @@ export type AMM = {
290
387
  lastAskPriceTwap: BN;
291
388
  longSpread: BN;
292
389
  shortSpread: BN;
390
+ maxSpread: number;
293
391
  };
294
392
 
295
393
  // # User Account Types
@@ -300,7 +398,6 @@ export type UserPosition = {
300
398
  quoteAssetAmount: BN;
301
399
  quoteEntryAmount: BN;
302
400
  openOrders: BN;
303
- unsettledPnl: BN;
304
401
  openBids: BN;
305
402
  openAsks: BN;
306
403
  };
@@ -321,6 +418,8 @@ export type UserAccount = {
321
418
  };
322
419
  positions: UserPosition[];
323
420
  orders: Order[];
421
+ beingLiquidated: boolean;
422
+ nextLiquidationId: number;
324
423
  };
325
424
 
326
425
  export type UserBankBalance = {
@@ -347,8 +446,9 @@ export type Order = {
347
446
  reduceOnly: boolean;
348
447
  triggerPrice: BN;
349
448
  triggerCondition: OrderTriggerCondition;
449
+ triggered: boolean;
350
450
  discountTier: OrderDiscountTier;
351
- existingPositionDirection: PositionDirection,
451
+ existingPositionDirection: PositionDirection;
352
452
  referrer: PublicKey;
353
453
  postOnly: boolean;
354
454
  immediateOrCancel: boolean;
@@ -362,7 +462,6 @@ export type OrderParams = {
362
462
  orderType: OrderType;
363
463
  userOrderId: number;
364
464
  direction: PositionDirection;
365
- quoteAssetAmount: BN;
366
465
  baseAssetAmount: BN;
367
466
  price: BN;
368
467
  marketIndex: BN;
@@ -381,11 +480,49 @@ export type OrderParams = {
381
480
  };
382
481
  };
383
482
 
483
+ export type NecessaryOrderParams = {
484
+ orderType: OrderType;
485
+ marketIndex: BN;
486
+ baseAssetAmount: BN;
487
+ direction: PositionDirection;
488
+ };
489
+
490
+ export type OptionalOrderParams = {
491
+ [Property in keyof OrderParams]?: OrderParams[Property];
492
+ } & NecessaryOrderParams;
493
+
494
+ export const DefaultOrderParams = {
495
+ orderType: OrderType.MARKET,
496
+ userOrderId: 0,
497
+ direction: PositionDirection.LONG,
498
+ baseAssetAmount: ZERO,
499
+ price: ZERO,
500
+ marketIndex: ZERO,
501
+ reduceOnly: false,
502
+ postOnly: false,
503
+ immediateOrCancel: false,
504
+ triggerPrice: ZERO,
505
+ triggerCondition: OrderTriggerCondition.ABOVE,
506
+ positionLimit: ZERO,
507
+ oraclePriceOffset: ZERO,
508
+ padding0: ZERO,
509
+ padding1: ZERO,
510
+ optionalAccounts: {
511
+ discountToken: false,
512
+ referrer: false,
513
+ },
514
+ };
515
+
384
516
  export type MakerInfo = {
385
517
  maker: PublicKey;
386
518
  order: Order;
387
519
  };
388
520
 
521
+ export type TakerInfo = {
522
+ taker: PublicKey;
523
+ order: Order;
524
+ };
525
+
389
526
  // # Misc Types
390
527
  export interface IWallet {
391
528
  signTransaction(tx: Transaction): Promise<Transaction>;
@@ -427,6 +564,7 @@ export type FeeStructure = {
427
564
  makerRebateNumerator: BN;
428
565
  makerRebateDenominator: BN;
429
566
  fillerRewardStructure: OrderFillerRewardStructure;
567
+ cancelOrderFee: BN;
430
568
  };
431
569
 
432
570
  export type OracleGuardRails = {
@@ -448,4 +586,4 @@ export type OrderFillerRewardStructure = {
448
586
  timeBasedRewardLowerBound: BN;
449
587
  };
450
588
 
451
- export type MarginCategory = 'Initial' | 'Partial' | 'Maintenance';
589
+ 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,8 @@ 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');
128
130
  });
129
131
 
130
132
  it('can initialise from string values correctly', () => {
@@ -1 +0,0 @@
1
- {"version":3,"file":"computeUnits.js","sourceRoot":"","sources":["computeUnits.ts"],"names":[],"mappings":";;;AAEO,KAAK,UAAU,0BAA0B,CAC/C,SAAoB,EACpB,UAAsB,EACtB,WAAmB,EACnB,aAAuB,WAAW;IAElC,MAAM,EAAE,GAAG,MAAM,UAAU,CAAC,cAAc,CAAC,WAAW,EAAE,EAAE,UAAU,EAAE,CAAC,CAAC;IACxE,MAAM,YAAY,GAAG,EAAE,CAAC;IACxB,MAAM,KAAK,GAAG,IAAI,MAAM,CACvB,WAAW,SAAS,CAAC,QAAQ,EAAE,gDAAgD,CAC/E,CAAC;IACF,EAAE,CAAC,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,UAAU,EAAE,EAAE;QAC1C,MAAM,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QACtC,IAAI,KAAK,IAAI,KAAK,CAAC,CAAC,CAAC,EAAE;YACtB,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;SAC5B;IACF,CAAC,CAAC,CAAC;IACH,OAAO,YAAY,CAAC;AACrB,CAAC;AAlBD,gEAkBC"}