@drift-labs/sdk 0.2.0-master.19 → 0.2.0-master.21

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 (86) hide show
  1. package/lib/accounts/types.d.ts +0 -1
  2. package/lib/clearingHouse.d.ts +13 -13
  3. package/lib/clearingHouse.js +98 -37
  4. package/lib/clearingHouseUser.d.ts +9 -1
  5. package/lib/clearingHouseUser.js +64 -45
  6. package/lib/clearingHouseUserStats.d.ts +2 -1
  7. package/lib/clearingHouseUserStats.js +13 -0
  8. package/lib/config.js +1 -1
  9. package/lib/events/types.d.ts +2 -1
  10. package/lib/events/types.js +1 -0
  11. package/lib/idl/clearing_house.json +200 -129
  12. package/lib/index.d.ts +0 -1
  13. package/lib/index.js +0 -1
  14. package/lib/math/amm.d.ts +1 -0
  15. package/lib/math/amm.js +13 -1
  16. package/lib/math/market.d.ts +1 -1
  17. package/lib/math/market.js +5 -5
  18. package/lib/math/orders.d.ts +4 -0
  19. package/lib/math/orders.js +45 -2
  20. package/lib/types.d.ts +28 -7
  21. package/my-script/.env +7 -0
  22. package/my-script/getUserStats.ts +124 -0
  23. package/my-script/multiConnections.ts +137 -0
  24. package/my-script/test-regex.ts +11 -0
  25. package/my-script/utils.ts +52 -0
  26. package/my-script/ww18NdhuLSQPCrHSx7V68eZJpe2y311heWeXJfSmP3Q.json +1 -0
  27. package/my-script/ww2z7N9TG1PLLUQGQF2VKzCFaPtQ5FBhRfeEAuy6c5C.json +1 -0
  28. package/my-script/ww3StJtTubhwssqAhvSSAc5ifCgKjzmF8hz7Gt2DmSa.json +1 -0
  29. package/package.json +1 -1
  30. package/src/clearingHouse.ts +132 -42
  31. package/src/clearingHouseUser.ts +78 -91
  32. package/src/clearingHouseUserStats.ts +23 -1
  33. package/src/config.ts +1 -1
  34. package/src/events/types.ts +3 -0
  35. package/src/idl/clearing_house.json +200 -129
  36. package/src/index.ts +0 -1
  37. package/src/math/amm.ts +27 -1
  38. package/src/math/market.ts +6 -6
  39. package/src/math/orders.ts +114 -2
  40. package/src/types.ts +30 -7
  41. package/lib/orders.d.ts +0 -7
  42. package/lib/orders.js +0 -59
  43. package/src/addresses/marketAddresses.js +0 -26
  44. package/src/assert/assert.js +0 -9
  45. package/src/constants/banks.js +0 -42
  46. package/src/constants/markets.js +0 -42
  47. package/src/constants/numericConstants.js +0 -41
  48. package/src/events/eventList.js +0 -77
  49. package/src/events/eventSubscriber.js +0 -139
  50. package/src/events/fetchLogs.js +0 -50
  51. package/src/events/pollingLogProvider.js +0 -64
  52. package/src/events/sort.js +0 -44
  53. package/src/events/txEventCache.js +0 -71
  54. package/src/events/types.js +0 -20
  55. package/src/events/webSocketLogProvider.js +0 -41
  56. package/src/examples/makeTradeExample.js +0 -80
  57. package/src/factory/bigNum.js +0 -390
  58. package/src/factory/oracleClient.js +0 -20
  59. package/src/math/amm.js +0 -369
  60. package/src/math/auction.js +0 -42
  61. package/src/math/conversion.js +0 -11
  62. package/src/math/funding.js +0 -248
  63. package/src/math/oracles.js +0 -26
  64. package/src/math/repeg.js +0 -128
  65. package/src/math/state.js +0 -15
  66. package/src/math/trade.js +0 -253
  67. package/src/math/utils.js +0 -26
  68. package/src/math/utils.js.map +0 -1
  69. package/src/oracles/oracleClientCache.js +0 -19
  70. package/src/oracles/pythClient.js +0 -46
  71. package/src/oracles/quoteAssetOracleClient.js +0 -32
  72. package/src/oracles/switchboardClient.js +0 -69
  73. package/src/oracles/types.js +0 -2
  74. package/src/orderParams.js +0 -20
  75. package/src/orders.ts +0 -91
  76. package/src/slot/SlotSubscriber.js +0 -39
  77. package/src/token/index.js +0 -38
  78. package/src/tokenFaucet.js +0 -189
  79. package/src/tx/types.js +0 -2
  80. package/src/tx/utils.js +0 -17
  81. package/src/userName.js +0 -20
  82. package/src/util/computeUnits.js +0 -27
  83. package/src/util/getTokenAddress.js +0 -9
  84. package/src/util/promiseTimeout.js +0 -14
  85. package/src/util/tps.js +0 -27
  86. package/src/wallet.js +0 -35
package/lib/index.d.ts CHANGED
@@ -40,7 +40,6 @@ export * from './math/trade';
40
40
  export * from './math/orders';
41
41
  export * from './math/repeg';
42
42
  export * from './math/margin';
43
- export * from './orders';
44
43
  export * from './orderParams';
45
44
  export * from './slot/SlotSubscriber';
46
45
  export * from './wallet';
package/lib/index.js CHANGED
@@ -63,7 +63,6 @@ __exportStar(require("./math/trade"), exports);
63
63
  __exportStar(require("./math/orders"), exports);
64
64
  __exportStar(require("./math/repeg"), exports);
65
65
  __exportStar(require("./math/margin"), exports);
66
- __exportStar(require("./orders"), exports);
67
66
  __exportStar(require("./orderParams"), exports);
68
67
  __exportStar(require("./slot/SlotSubscriber"), exports);
69
68
  __exportStar(require("./wallet"), exports);
package/lib/math/amm.d.ts CHANGED
@@ -67,3 +67,4 @@ export declare function getSwapDirection(inputAssetType: AssetType, positionDire
67
67
  export declare function calculateTerminalPrice(market: MarketAccount): BN;
68
68
  export declare function calculateMaxBaseAssetAmountToTrade(amm: AMM, limit_price: BN, direction: PositionDirection, oraclePriceData?: OraclePriceData): [BN, PositionDirection];
69
69
  export declare function calculateQuoteAssetAmountSwapped(quoteAssetReserves: BN, pegMultiplier: BN, swapDirection: SwapDirection): BN;
70
+ export declare function calculateMaxBaseAssetAmountFillable(amm: AMM, orderDirection: PositionDirection): BN;
package/lib/math/amm.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.calculateQuoteAssetAmountSwapped = exports.calculateMaxBaseAssetAmountToTrade = exports.calculateTerminalPrice = exports.getSwapDirection = exports.calculateSwapOutput = exports.calculateSpreadReserves = exports.calculateSpread = exports.calculateSpreadBN = exports.calculateMaxSpread = exports.calculateEffectiveLeverage = exports.calculateAmmReservesAfterSwap = exports.calculatePrice = exports.calculateBidAskPrice = exports.calculateUpdatedAMMSpreadReserves = exports.calculateUpdatedAMM = exports.calculateNewAmm = exports.calculateOptimalPegAndBudget = exports.calculatePegFromTargetPrice = void 0;
3
+ exports.calculateMaxBaseAssetAmountFillable = exports.calculateQuoteAssetAmountSwapped = exports.calculateMaxBaseAssetAmountToTrade = exports.calculateTerminalPrice = exports.getSwapDirection = exports.calculateSwapOutput = exports.calculateSpreadReserves = exports.calculateSpread = exports.calculateSpreadBN = exports.calculateMaxSpread = exports.calculateEffectiveLeverage = exports.calculateAmmReservesAfterSwap = exports.calculatePrice = exports.calculateBidAskPrice = exports.calculateUpdatedAMMSpreadReserves = exports.calculateUpdatedAMM = exports.calculateNewAmm = exports.calculateOptimalPegAndBudget = exports.calculatePegFromTargetPrice = void 0;
4
4
  const anchor_1 = require("@project-serum/anchor");
5
5
  const numericConstants_1 = require("../constants/numericConstants");
6
6
  const types_1 = require("../types");
@@ -367,3 +367,15 @@ function calculateQuoteAssetAmountSwapped(quoteAssetReserves, pegMultiplier, swa
367
367
  return quoteAssetAmount;
368
368
  }
369
369
  exports.calculateQuoteAssetAmountSwapped = calculateQuoteAssetAmountSwapped;
370
+ function calculateMaxBaseAssetAmountFillable(amm, orderDirection) {
371
+ const maxFillSize = amm.baseAssetReserve.div(new anchor_1.BN(amm.maxBaseAssetAmountRatio));
372
+ let maxBaseAssetAmountOnSide;
373
+ if ((0, types_1.isVariant)(orderDirection, 'long')) {
374
+ maxBaseAssetAmountOnSide = anchor_1.BN.max(numericConstants_1.ZERO, amm.maxBaseAssetReserve.sub(amm.baseAssetReserve));
375
+ }
376
+ else {
377
+ maxBaseAssetAmountOnSide = anchor_1.BN.max(numericConstants_1.ZERO, amm.baseAssetReserve.sub(amm.minBaseAssetReserve));
378
+ }
379
+ return (0, __1.standardizeBaseAssetAmount)(anchor_1.BN.min(maxFillSize, maxBaseAssetAmountOnSide), amm.baseAssetAmountStepSize);
380
+ }
381
+ exports.calculateMaxBaseAssetAmountFillable = calculateMaxBaseAssetAmountFillable;
@@ -27,5 +27,5 @@ export declare function calculateNewMarketAfterTrade(baseAssetAmount: BN, direct
27
27
  export declare function calculateMarkOracleSpread(market: MarketAccount, oraclePriceData: OraclePriceData): BN;
28
28
  export declare function calculateOracleSpread(price: BN, oraclePriceData: OraclePriceData): BN;
29
29
  export declare function calculateMarketMarginRatio(market: MarketAccount, size: BN, marginCategory: MarginCategory): number;
30
- export declare function calculateUnsettledAssetWeight(market: MarketAccount, unsettledPnl: BN, marginCategory: MarginCategory): BN;
30
+ export declare function calculateUnrealizedAssetWeight(market: MarketAccount, unrealizedPnl: BN, marginCategory: MarginCategory): BN;
31
31
  export declare function calculateMarketAvailablePNL(market: MarketAccount, bank: BankAccount): BN;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.calculateMarketAvailablePNL = exports.calculateUnsettledAssetWeight = exports.calculateMarketMarginRatio = exports.calculateOracleSpread = exports.calculateMarkOracleSpread = exports.calculateNewMarketAfterTrade = exports.calculateAskPrice = exports.calculateBidPrice = exports.calculateMarkPrice = void 0;
3
+ exports.calculateMarketAvailablePNL = exports.calculateUnrealizedAssetWeight = exports.calculateMarketMarginRatio = exports.calculateOracleSpread = exports.calculateMarkOracleSpread = exports.calculateNewMarketAfterTrade = exports.calculateAskPrice = exports.calculateBidPrice = exports.calculateMarkPrice = void 0;
4
4
  const anchor_1 = require("@project-serum/anchor");
5
5
  const types_1 = require("../types");
6
6
  const amm_1 = require("./amm");
@@ -72,19 +72,19 @@ function calculateMarketMarginRatio(market, size, marginCategory) {
72
72
  return marginRatio;
73
73
  }
74
74
  exports.calculateMarketMarginRatio = calculateMarketMarginRatio;
75
- function calculateUnsettledAssetWeight(market, unsettledPnl, marginCategory) {
75
+ function calculateUnrealizedAssetWeight(market, unrealizedPnl, marginCategory) {
76
76
  let assetWeight;
77
77
  switch (marginCategory) {
78
78
  case 'Initial':
79
- assetWeight = (0, margin_1.calculateSizeDiscountAssetWeight)(unsettledPnl, market.unsettledImfFactor, new anchor_1.BN(market.unsettledInitialAssetWeight));
79
+ assetWeight = (0, margin_1.calculateSizeDiscountAssetWeight)(unrealizedPnl, market.unrealizedImfFactor, new anchor_1.BN(market.unrealizedInitialAssetWeight));
80
80
  break;
81
81
  case 'Maintenance':
82
- assetWeight = new anchor_1.BN(market.unsettledMaintenanceAssetWeight);
82
+ assetWeight = new anchor_1.BN(market.unrealizedMaintenanceAssetWeight);
83
83
  break;
84
84
  }
85
85
  return assetWeight;
86
86
  }
87
- exports.calculateUnsettledAssetWeight = calculateUnsettledAssetWeight;
87
+ exports.calculateUnrealizedAssetWeight = calculateUnrealizedAssetWeight;
88
88
  function calculateMarketAvailablePNL(market, bank) {
89
89
  return (0, bankBalance_1.getTokenAmount)(market.pnlPool.balance, bank, types_1.BankBalanceType.DEPOSIT);
90
90
  }
@@ -8,3 +8,7 @@ export declare function isOrderRiskIncreasingInSameDirection(user: ClearingHouse
8
8
  export declare function isOrderReduceOnly(user: ClearingHouseUser, order: Order): boolean;
9
9
  export declare function standardizeBaseAssetAmount(baseAssetAmount: BN, stepSize: BN): BN;
10
10
  export declare function getLimitPrice(order: Order, market: MarketAccount, oraclePriceData: OraclePriceData, slot: number): BN;
11
+ export declare function isFillableByVAMM(order: Order, market: MarketAccount, oraclePriceData: OraclePriceData, slot: number, maxAuctionDuration: number): boolean;
12
+ export declare function calculateBaseAssetAmountForAmmToFulfill(order: Order, market: MarketAccount, oraclePriceData: OraclePriceData, slot: number): BN;
13
+ export declare function calculateBaseAssetAmountToFillUpToLimitPrice(order: Order, market: MarketAccount, limitPrice: BN, oraclePriceData: OraclePriceData): BN;
14
+ export declare function isOrderExpired(order: Order, slot: number, maxAuctionDuration: number): boolean;
@@ -1,11 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getLimitPrice = exports.standardizeBaseAssetAmount = exports.isOrderReduceOnly = exports.isOrderRiskIncreasingInSameDirection = exports.isOrderRiskIncreasing = void 0;
3
+ exports.isOrderExpired = exports.calculateBaseAssetAmountToFillUpToLimitPrice = exports.calculateBaseAssetAmountForAmmToFulfill = exports.isFillableByVAMM = exports.getLimitPrice = exports.standardizeBaseAssetAmount = exports.isOrderReduceOnly = exports.isOrderRiskIncreasingInSameDirection = exports.isOrderRiskIncreasing = void 0;
4
4
  const types_1 = require("../types");
5
5
  const numericConstants_1 = require("../constants/numericConstants");
6
6
  const anchor_1 = require("@project-serum/anchor");
7
7
  const auction_1 = require("./auction");
8
8
  const market_1 = require("./market");
9
+ const amm_1 = require("./amm");
9
10
  function isOrderRiskIncreasing(user, order) {
10
11
  if ((0, types_1.isVariant)(order.status, 'init')) {
11
12
  return false;
@@ -85,7 +86,7 @@ function getLimitPrice(order, market, oraclePriceData, slot) {
85
86
  limitPrice = oraclePriceData.price.add(order.oraclePriceOffset);
86
87
  }
87
88
  else if ((0, types_1.isOneOfVariant)(order.orderType, ['market', 'triggerMarket'])) {
88
- if ((0, auction_1.isAuctionComplete)(order, slot)) {
89
+ if (!(0, auction_1.isAuctionComplete)(order, slot)) {
89
90
  limitPrice = (0, auction_1.getAuctionPrice)(order, slot);
90
91
  }
91
92
  else if (!order.price.eq(numericConstants_1.ZERO)) {
@@ -108,3 +109,45 @@ function getLimitPrice(order, market, oraclePriceData, slot) {
108
109
  return limitPrice;
109
110
  }
110
111
  exports.getLimitPrice = getLimitPrice;
112
+ function isFillableByVAMM(order, market, oraclePriceData, slot, maxAuctionDuration) {
113
+ return (((0, auction_1.isAuctionComplete)(order, slot) &&
114
+ !calculateBaseAssetAmountForAmmToFulfill(order, market, oraclePriceData, slot).eq(numericConstants_1.ZERO)) ||
115
+ isOrderExpired(order, slot, maxAuctionDuration));
116
+ }
117
+ exports.isFillableByVAMM = isFillableByVAMM;
118
+ function calculateBaseAssetAmountForAmmToFulfill(order, market, oraclePriceData, slot) {
119
+ if ((0, types_1.isOneOfVariant)(order.orderType, ['triggerMarket', 'triggerLimit']) &&
120
+ order.triggered === false) {
121
+ return numericConstants_1.ZERO;
122
+ }
123
+ const limitPrice = getLimitPrice(order, market, oraclePriceData, slot);
124
+ const baseAssetAmount = calculateBaseAssetAmountToFillUpToLimitPrice(order, market, limitPrice, oraclePriceData);
125
+ const maxBaseAssetAmount = (0, amm_1.calculateMaxBaseAssetAmountFillable)(market.amm, order.direction);
126
+ return anchor_1.BN.min(maxBaseAssetAmount, baseAssetAmount);
127
+ }
128
+ exports.calculateBaseAssetAmountForAmmToFulfill = calculateBaseAssetAmountForAmmToFulfill;
129
+ function calculateBaseAssetAmountToFillUpToLimitPrice(order, market, limitPrice, oraclePriceData) {
130
+ const [maxAmountToTrade, direction] = (0, amm_1.calculateMaxBaseAssetAmountToTrade)(market.amm, limitPrice, order.direction, oraclePriceData);
131
+ const baseAssetAmount = standardizeBaseAssetAmount(maxAmountToTrade, market.amm.baseAssetAmountStepSize);
132
+ // Check that directions are the same
133
+ const sameDirection = isSameDirection(direction, order.direction);
134
+ if (!sameDirection) {
135
+ return numericConstants_1.ZERO;
136
+ }
137
+ return baseAssetAmount.gt(order.baseAssetAmount)
138
+ ? order.baseAssetAmount
139
+ : baseAssetAmount;
140
+ }
141
+ exports.calculateBaseAssetAmountToFillUpToLimitPrice = calculateBaseAssetAmountToFillUpToLimitPrice;
142
+ function isSameDirection(firstDirection, secondDirection) {
143
+ return (((0, types_1.isVariant)(firstDirection, 'long') && (0, types_1.isVariant)(secondDirection, 'long')) ||
144
+ ((0, types_1.isVariant)(firstDirection, 'short') && (0, types_1.isVariant)(secondDirection, 'short')));
145
+ }
146
+ function isOrderExpired(order, slot, maxAuctionDuration) {
147
+ if (!(0, types_1.isVariant)(order.orderType, 'market') ||
148
+ !(0, types_1.isVariant)(order.status, 'open')) {
149
+ return false;
150
+ }
151
+ return new anchor_1.BN(slot).sub(order.slot).gt(new anchor_1.BN(maxAuctionDuration));
152
+ }
153
+ exports.isOrderExpired = isOrderExpired;
package/lib/types.d.ts CHANGED
@@ -136,6 +136,14 @@ export declare enum TradeSide {
136
136
  Sell = 2
137
137
  }
138
138
  export declare type CandleResolution = '1' | '5' | '15' | '60' | '240' | 'D' | 'W' | 'M';
139
+ export declare type NewUserRecord = {
140
+ ts: BN;
141
+ userAuthority: PublicKey;
142
+ user: PublicKey;
143
+ userId: number;
144
+ name: number[];
145
+ referrer: PublicKey;
146
+ };
139
147
  export declare type DepositRecord = {
140
148
  ts: BN;
141
149
  userAuthority: PublicKey;
@@ -147,6 +155,7 @@ export declare type DepositRecord = {
147
155
  bankIndex: BN;
148
156
  amount: BN;
149
157
  oraclePrice: BN;
158
+ referrer: PublicKey;
150
159
  from?: PublicKey;
151
160
  to?: PublicKey;
152
161
  };
@@ -303,6 +312,9 @@ export declare type OrderRecord = {
303
312
  fillerReward: BN;
304
313
  quoteAssetAmountSurplus: BN;
305
314
  oraclePrice: BN;
315
+ referrer: PublicKey;
316
+ referrerReward: BN;
317
+ refereeDiscount: BN;
306
318
  };
307
319
  export declare type StateAccount = {
308
320
  admin: PublicKey;
@@ -333,6 +345,8 @@ export declare type StateAccount = {
333
345
  numberOfMarkets: BN;
334
346
  numberOfBanks: BN;
335
347
  minOrderQuoteAssetAmount: BN;
348
+ maxAuctionDuration: number;
349
+ minAuctionDuration: number;
336
350
  };
337
351
  export declare type MarketAccount = {
338
352
  initialized: boolean;
@@ -349,9 +363,9 @@ export declare type MarketAccount = {
349
363
  pnlPool: PoolBalance;
350
364
  liquidationFee: BN;
351
365
  imfFactor: BN;
352
- unsettledImfFactor: BN;
353
- unsettledInitialAssetWeight: number;
354
- unsettledMaintenanceAssetWeight: number;
366
+ unrealizedImfFactor: BN;
367
+ unrealizedInitialAssetWeight: number;
368
+ unrealizedMaintenanceAssetWeight: number;
355
369
  };
356
370
  export declare type BankAccount = {
357
371
  bankIndex: BN;
@@ -439,6 +453,8 @@ export declare type AMM = {
439
453
  maxSpread: number;
440
454
  marketPosition: UserPosition;
441
455
  marketPositionPerLp: UserPosition;
456
+ maxBaseAssetReserve: BN;
457
+ minBaseAssetReserve: BN;
442
458
  };
443
459
  export declare type UserPosition = {
444
460
  baseAssetAmount: BN;
@@ -467,11 +483,12 @@ export declare type UserStatsAccount = {
467
483
  totalFeePaid: BN;
468
484
  totalFeeRebate: BN;
469
485
  totalTokenDiscount: BN;
470
- totalReferralReward: BN;
471
486
  totalRefereeDiscount: BN;
472
487
  };
473
- authority: PublicKey;
474
488
  referrer: PublicKey;
489
+ isReferrer: boolean;
490
+ totalReferrerReward: BN;
491
+ authority: PublicKey;
475
492
  };
476
493
  export declare type UserAccount = {
477
494
  authority: PublicKey;
@@ -483,6 +500,7 @@ export declare type UserAccount = {
483
500
  beingLiquidated: boolean;
484
501
  bankrupt: boolean;
485
502
  nextLiquidationId: number;
503
+ nextOrderId: BN;
486
504
  };
487
505
  export declare type UserBankBalance = {
488
506
  bankIndex: BN;
@@ -508,9 +526,7 @@ export declare type Order = {
508
526
  triggerPrice: BN;
509
527
  triggerCondition: OrderTriggerCondition;
510
528
  triggered: boolean;
511
- discountTier: OrderDiscountTier;
512
529
  existingPositionDirection: PositionDirection;
513
- referrer: PublicKey;
514
530
  postOnly: boolean;
515
531
  immediateOrCancel: boolean;
516
532
  oraclePriceOffset: BN;
@@ -583,8 +599,13 @@ export declare type MakerInfo = {
583
599
  export declare type TakerInfo = {
584
600
  taker: PublicKey;
585
601
  takerStats: PublicKey;
602
+ takerUserAccount: UserAccount;
586
603
  order: Order;
587
604
  };
605
+ export declare type ReferrerInfo = {
606
+ referrer: PublicKey;
607
+ referrerStats: PublicKey;
608
+ };
588
609
  export interface IWallet {
589
610
  signTransaction(tx: Transaction): Promise<Transaction>;
590
611
  signAllTransactions(txs: Transaction[]): Promise<Transaction[]>;
package/my-script/.env ADDED
@@ -0,0 +1,7 @@
1
+ #ANCHOR_WALLET=/Users/ww/.config/solana/id.json
2
+
3
+ #ANCHOR_WALLET=/Users/ww/.config/solana/bot2RzYy9oY5s3z71Yubo4MmRxyDBQP3qNNCqyqLcPp.json
4
+
5
+ ANCHOR_WALLET=./ww18NdhuLSQPCrHSx7V68eZJpe2y311heWeXJfSmP3Q.json
6
+ #ANCHOR_WALLET=./ww2z7N9TG1PLLUQGQF2VKzCFaPtQ5FBhRfeEAuy6c5C.json
7
+ #ANCHOR_WALLET=./ww3StJtTubhwssqAhvSSAc5ifCgKjzmF8hz7Gt2DmSa.json
@@ -0,0 +1,124 @@
1
+ import * as anchor from '@project-serum/anchor';
2
+ // import { AnchorProvider } from '@project-serum/anchor';
3
+ import { PublicKey, clusterApiUrl } from '@solana/web3.js';
4
+
5
+ import {
6
+ DriftEnv,
7
+ initialize,
8
+ BN,
9
+ BulkAccountLoader,
10
+ convertToNumber,
11
+ calculateAdjustKCost,
12
+ calculateBidAskPrice,
13
+ EventSubscriber,
14
+ UserAccount,
15
+ DevnetBanks,
16
+ DevnetMarkets,
17
+ MARK_PRICE_PRECISION,
18
+ BASE_PRECISION,
19
+ QUOTE_PRECISION,
20
+ ClearingHouse,
21
+ getMarketOrderParams,
22
+ PositionDirection,
23
+ ZERO,
24
+ } from '..';
25
+ import { printUserStats } from './utils';
26
+
27
+ require('dotenv').config();
28
+ const driftEnv = process.env.ENV as DriftEnv;
29
+
30
+ function sleep(ms) {
31
+ return new Promise((resolve) => setTimeout(resolve, ms));
32
+ }
33
+
34
+ async function main(provider: anchor.AnchorProvider) {
35
+ const connection = provider.connection;
36
+ const config = initialize({ env: 'devnet' });
37
+ const clearingHousePublicKey = new PublicKey(
38
+ config.CLEARING_HOUSE_PROGRAM_ID
39
+ );
40
+
41
+ const bulkAccountLoader = new BulkAccountLoader(connection, 'confirmed', 1000);
42
+ const clearingHouse = new ClearingHouse({
43
+ connection,
44
+ wallet: provider.wallet,
45
+ programID: clearingHousePublicKey,
46
+ env: 'devnet',
47
+ // accountSubscription: {
48
+ // type: 'websocket',
49
+ // }
50
+ accountSubscription: {
51
+ type: 'polling',
52
+ accountLoader: bulkAccountLoader,
53
+ }
54
+ });
55
+
56
+ console.log(`clearingHouseProgramID: ${clearingHousePublicKey}`)
57
+ console.log(`provider.wallet: ${provider.wallet.publicKey.toBase58()}`)
58
+
59
+ const eventSubscriber = new EventSubscriber(connection, clearingHouse.program, {
60
+ maxTx: 8192,
61
+ maxEventsPerType: 4096,
62
+ orderBy: 'blockchain',
63
+ orderDir: 'desc',
64
+ commitment: 'confirmed',
65
+ logProviderConfig: {
66
+ type: 'websocket',
67
+ },
68
+ });
69
+
70
+ if (!(await clearingHouse.getUser().exists())) {
71
+ console.error(`ClearingHouseUser for ${provider.wallet.publicKey} does not exist`);
72
+ console.info(`Creating ClearingHouseUser for ${provider.wallet.publicKey}`);
73
+ const [txSig] = await clearingHouse.initializeUserAccount();
74
+ console.log(`Initialized user account in transaction: ${txSig}`);
75
+ }
76
+
77
+ if (!await clearingHouse.subscribe()) {
78
+ throw new Error("fail clearingHouse.subscribe");
79
+ }
80
+ if (!await clearingHouse.accountSubscriber.subscribe()) {
81
+ throw new Error("fail clearingHouse.accountSubscriber.subscribe");
82
+ }
83
+ if (!eventSubscriber.subscribe()) {
84
+ throw new Error("fail eventSubscriber.subscribe");
85
+ }
86
+
87
+ const chUser = clearingHouse.getUser();
88
+ const chUserAccount = clearingHouse.getUserAccount();
89
+ console.log(`chUserAcc.authority: ${chUserAccount!.authority.toBase58()}`);
90
+ console.log(` chUserAccount pubkey: ${chUser.userAccountPublicKey.toBase58()}`)
91
+
92
+ const keyToSymbol = new Map<string, string>();
93
+ const marketIndexToSymbol = new Map<number, string>();
94
+ for (const market of DevnetMarkets) {
95
+ keyToSymbol.set(market.oracle.toBase58(), market.baseAssetSymbol);
96
+ marketIndexToSymbol.set(market.marketIndex.toNumber(), market.symbol);
97
+ }
98
+
99
+ const run = async () => {
100
+ await clearingHouse.fetchAccounts();
101
+ await chUser.fetchAccounts();
102
+ printUserStats(chUserAccount!, marketIndexToSymbol);
103
+ }
104
+ await run();
105
+ setInterval(run, 1000);
106
+ }
107
+
108
+
109
+ try {
110
+ if (!process.env.ANCHOR_WALLET) {
111
+ throw new Error('ANCHOR_WALLET must be set.');
112
+ }
113
+ main(
114
+ anchor.AnchorProvider.local(clusterApiUrl("devnet"), {
115
+ // anchor.AnchorProvider.local('https://devnet.genesysgo.net', {
116
+ preflightCommitment: 'confirmed',
117
+ skipPreflight: false,
118
+ commitment: 'confirmed',
119
+ })
120
+ );
121
+ // anchor.AnchorProvider.local('https://psytrbhymqlkfrhudd.dev.genesysgo.net:8899/');
122
+ } catch (e) {
123
+ console.error(e);
124
+ }
@@ -0,0 +1,137 @@
1
+ import * as anchor from '@project-serum/anchor';
2
+ // import { AnchorProvider } from '@project-serum/anchor';
3
+ import { PublicKey, clusterApiUrl } from '@solana/web3.js';
4
+
5
+ import {
6
+ DriftEnv,
7
+ initialize,
8
+ BN,
9
+ BulkAccountLoader,
10
+ convertToNumber,
11
+ calculateAdjustKCost,
12
+ calculateBidAskPrice,
13
+ EventSubscriber,
14
+ UserAccount,
15
+ DevnetBanks,
16
+ DevnetMarkets,
17
+ MARK_PRICE_PRECISION,
18
+ BASE_PRECISION,
19
+ QUOTE_PRECISION,
20
+ ClearingHouse,
21
+ getMarketOrderParams,
22
+ PositionDirection,
23
+ ZERO,
24
+ } from '..';
25
+ import { printUserStats } from './utils';
26
+
27
+ require('dotenv').config();
28
+ const driftEnv = process.env.ENV as DriftEnv;
29
+
30
+ function sleep(ms) {
31
+ return new Promise((resolve) => setTimeout(resolve, ms));
32
+ }
33
+
34
+ async function main(provider: anchor.AnchorProvider) {
35
+ const connection = provider.connection;
36
+ const config = initialize({ env: 'devnet' });
37
+ const clearingHousePublicKey = new PublicKey(
38
+ config.CLEARING_HOUSE_PROGRAM_ID
39
+ );
40
+
41
+ const bulkAccountLoader = new BulkAccountLoader(
42
+ connection,
43
+ 'confirmed',
44
+ 1000
45
+ );
46
+ const clearingHouse = new ClearingHouse({
47
+ connection,
48
+ wallet: provider.wallet,
49
+ programID: clearingHousePublicKey,
50
+ env: 'devnet',
51
+ // accountSubscription: {
52
+ // type: 'websocket',
53
+ // }
54
+ accountSubscription: {
55
+ type: 'polling',
56
+ accountLoader: bulkAccountLoader,
57
+ },
58
+ });
59
+
60
+ console.log(`clearingHouseProgramID: ${clearingHousePublicKey}`);
61
+ console.log(
62
+ `provider.wallet: ${provider.wallet.publicKey.toBase58()}`
63
+ );
64
+
65
+ const eventSubscriber = new EventSubscriber(
66
+ connection,
67
+ clearingHouse.program,
68
+ {
69
+ maxTx: 8192,
70
+ maxEventsPerType: 4096,
71
+ orderBy: 'blockchain',
72
+ orderDir: 'desc',
73
+ commitment: 'confirmed',
74
+ logProviderConfig: {
75
+ type: 'websocket',
76
+ },
77
+ }
78
+ );
79
+
80
+ if (!(await clearingHouse.getUser().exists())) {
81
+ console.error(
82
+ `ClearingHouseUser for ${provider.wallet.publicKey} does not exist`
83
+ );
84
+ console.info(`Creating ClearingHouseUser for ${provider.wallet.publicKey}`);
85
+ const [txSig] = await clearingHouse.initializeUserAccount();
86
+ console.log(`Initialized user account in transaction: ${txSig}`);
87
+ }
88
+
89
+ if (!(await clearingHouse.subscribe())) {
90
+ throw new Error('fail clearingHouse.subscribe');
91
+ }
92
+ if (!(await clearingHouse.accountSubscriber.subscribe())) {
93
+ throw new Error('fail clearingHouse.accountSubscriber.subscribe');
94
+ }
95
+ if (!eventSubscriber.subscribe()) {
96
+ throw new Error('fail eventSubscriber.subscribe');
97
+ }
98
+
99
+ const chUser = clearingHouse.getUser();
100
+ const chUserAccount = clearingHouse.getUserAccount();
101
+ console.log(`chUserAcc.authority: ${chUserAccount!.authority.toBase58()}`);
102
+ console.log(
103
+ ` chUserAccount pubkey: ${chUser.userAccountPublicKey.toBase58()}`
104
+ );
105
+
106
+ const keyToSymbol = new Map<string, string>();
107
+ const marketIndexToSymbol = new Map<number, string>();
108
+ for (const market of DevnetMarkets) {
109
+ keyToSymbol.set(market.oracle.toBase58(), market.baseAssetSymbol);
110
+ marketIndexToSymbol.set(market.marketIndex.toNumber(), market.symbol);
111
+ }
112
+
113
+ const run = async () => {
114
+ await clearingHouse.fetchAccounts();
115
+ await chUser.fetchAccounts();
116
+ printUserStats(chUserAccount!, marketIndexToSymbol);
117
+ };
118
+ await run();
119
+ setInterval(run, 1000);
120
+ }
121
+
122
+ try {
123
+ if (!process.env.ANCHOR_WALLET) {
124
+ throw new Error('ANCHOR_WALLET must be set.');
125
+ }
126
+ main(
127
+ anchor.AnchorProvider.local(clusterApiUrl('devnet'), {
128
+ // anchor.AnchorProvider.local('https://devnet.genesysgo.net', {
129
+ preflightCommitment: 'confirmed',
130
+ skipPreflight: false,
131
+ commitment: 'confirmed',
132
+ })
133
+ );
134
+ // anchor.AnchorProvider.local('https://psytrbhymqlkfrhudd.dev.genesysgo.net:8899/');
135
+ } catch (e) {
136
+ console.error(e);
137
+ }
@@ -0,0 +1,11 @@
1
+ try {
2
+ // const msg = 'Program 65sz7dRiWDRPZjiRxcTxPM7AE6VK4Nag9HEK6oBJXhJn failed: custom program error: 0x179e'
3
+ const msg = 'Program log: AnchorError occurred. Error Code: OrderDoesNotExist. Error Number: 6046. Error Message: Order does not exist.'
4
+ const code = msg.match(
5
+ /Program log: AnchorError occurred. Error Code: ([0-9,a-z,A-Z]+). Error Number/
6
+ );
7
+ console.log(code[1]);
8
+ } catch (e) {
9
+ console.log("nothing");
10
+ // no problem if couldn't match error code
11
+ }
@@ -0,0 +1,52 @@
1
+ import {
2
+ ClearingHouse,
3
+ UserAccount,
4
+ } from '..';
5
+
6
+ export function printUserStats(chUserAccount: UserAccount, marketIndexToSymbol: Map<number, string>) {
7
+
8
+ console.log("")
9
+ console.log(`${new Date(Date.now())}`)
10
+ console.log("Open positions:");
11
+ let openPositions = 0;
12
+ for (const p of chUserAccount!.positions) {
13
+ if (p.baseAssetAmount.isZero()) {
14
+ continue;
15
+ }
16
+ console.log(` [${marketIndexToSymbol.get(p.marketIndex.toNumber())}]`);
17
+ console.log(` . baseAssetAmount: ${p.baseAssetAmount.toString()}`);
18
+ console.log(` . quoteAssetAmount: ${p.quoteAssetAmount.toString()}`);
19
+ console.log(` . quoteEntryAmount: ${p.quoteEntryAmount.toString()}`);
20
+ console.log(` . lastCumulativeFundingRate: ${p.lastCumulativeFundingRate.toString()}`);
21
+ console.log(` . openOrders: ${p.openOrders}`);
22
+ console.log(` . openBids: ${p.openBids.toString()}`);
23
+ console.log(` . openAsks: ${p.openAsks.toString()}`);
24
+ openPositions++;
25
+ }
26
+ console.log(`count: ${openPositions}`);
27
+
28
+ let openOrders = 0
29
+ console.log("")
30
+ console.log("Open orders:");
31
+ for (const o of chUserAccount!.orders) {
32
+ if (o.baseAssetAmount.isZero()) {
33
+ continue
34
+ }
35
+ console.log(` . [OrderId: ${o.orderId.toString()}, ${JSON.stringify(o.status)} ${JSON.stringify(o.direction)}, mktIdx: ${o.marketIndex.toString()}]: ${o.baseAssetAmountFilled.toString()}/${o.baseAssetAmount.toString()}`)
36
+ openOrders++;
37
+ }
38
+ console.log(`count: ${openOrders}`);
39
+
40
+ return;
41
+ }
42
+
43
+ export async function cancelOpenOrders(clearingHouse: ClearingHouse, chUserAccount: UserAccount) {
44
+ for (const o of chUserAccount!.orders) {
45
+ if (o.baseAssetAmount.isZero()) {
46
+ continue
47
+ }
48
+
49
+ const tx = await clearingHouse.cancelOrder(o.orderId);
50
+ console.log(`Canceled orderID ${o.orderId.toString()} on market ${o.marketIndex.toString()}, tx: ${tx}`);
51
+ }
52
+ }
@@ -0,0 +1 @@
1
+ [149,94,114,124,219,221,15,219,156,59,219,91,53,1,121,158,237,212,164,155,68,189,58,136,87,97,154,140,23,246,148,112,14,18,108,149,240,175,10,38,108,111,73,206,93,83,134,205,168,159,203,151,219,125,105,254,244,61,190,29,211,107,13,19]
@@ -0,0 +1 @@
1
+ [240,167,34,21,160,221,50,92,208,80,210,26,131,127,167,209,55,203,154,72,195,156,103,167,91,95,76,29,235,92,57,167,14,18,117,219,39,14,43,171,96,125,33,203,219,16,219,60,194,217,59,116,35,116,255,1,179,89,243,9,41,181,81,103]
@@ -0,0 +1 @@
1
+ [5,60,137,129,213,3,6,50,181,118,108,215,24,4,33,79,191,86,110,99,115,149,212,216,240,15,229,159,228,144,75,215,14,18,120,40,242,92,142,39,104,193,163,8,30,13,91,89,147,117,144,82,156,127,20,66,10,222,188,128,65,29,15,139]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@drift-labs/sdk",
3
- "version": "0.2.0-master.19",
3
+ "version": "0.2.0-master.21",
4
4
  "main": "lib/index.js",
5
5
  "types": "lib/index.d.ts",
6
6
  "author": "crispheaney",