@drift-labs/sdk 2.96.0-beta.2 → 2.96.0-beta.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 (110) hide show
  1. package/README.md +2 -0
  2. package/VERSION +1 -1
  3. package/bun.lockb +0 -0
  4. package/lib/accounts/pollingDriftClientAccountSubscriber.d.ts +5 -3
  5. package/lib/accounts/pollingDriftClientAccountSubscriber.js +24 -1
  6. package/lib/accounts/types.d.ts +5 -8
  7. package/lib/accounts/types.js +7 -1
  8. package/lib/accounts/utils.d.ts +7 -0
  9. package/lib/accounts/utils.js +33 -1
  10. package/lib/accounts/webSocketAccountSubscriber.d.ts +1 -1
  11. package/lib/accounts/webSocketDriftClientAccountSubscriber.d.ts +8 -7
  12. package/lib/accounts/webSocketDriftClientAccountSubscriber.js +24 -1
  13. package/lib/accounts/webSocketProgramAccountSubscriber.d.ts +1 -1
  14. package/lib/config.d.ts +5 -1
  15. package/lib/config.js +9 -1
  16. package/lib/constants/perpMarkets.js +21 -0
  17. package/lib/constants/spotMarkets.js +12 -1
  18. package/lib/driftClient.d.ts +44 -9
  19. package/lib/driftClient.js +181 -61
  20. package/lib/driftClientConfig.d.ts +2 -6
  21. package/lib/events/eventSubscriber.js +9 -8
  22. package/lib/events/types.js +1 -5
  23. package/lib/idl/drift.json +169 -1
  24. package/lib/index.d.ts +1 -0
  25. package/lib/index.js +1 -0
  26. package/lib/math/margin.d.ts +16 -1
  27. package/lib/math/margin.js +67 -1
  28. package/lib/orderParams.js +8 -8
  29. package/lib/orderSubscriber/OrderSubscriber.d.ts +1 -2
  30. package/lib/orderSubscriber/OrderSubscriber.js +4 -19
  31. package/lib/orderSubscriber/types.d.ts +0 -9
  32. package/lib/tokenFaucet.js +2 -1
  33. package/lib/tx/baseTxSender.js +2 -2
  34. package/lib/tx/fastSingleTxSender.js +2 -2
  35. package/lib/tx/forwardOnlyTxSender.js +2 -2
  36. package/lib/tx/retryTxSender.js +2 -2
  37. package/lib/tx/txHandler.js +10 -7
  38. package/lib/tx/whileValidTxSender.d.ts +2 -4
  39. package/lib/tx/whileValidTxSender.js +16 -17
  40. package/lib/types.d.ts +21 -1
  41. package/lib/types.js +6 -1
  42. package/lib/user.d.ts +4 -1
  43. package/lib/user.js +13 -13
  44. package/lib/userConfig.d.ts +1 -6
  45. package/lib/userMap/userMap.js +0 -14
  46. package/lib/userMap/userMapConfig.d.ts +0 -7
  47. package/lib/userStatsConfig.d.ts +0 -6
  48. package/lib/util/TransactionConfirmationManager.d.ts +14 -0
  49. package/lib/util/TransactionConfirmationManager.js +96 -0
  50. package/package.json +4 -5
  51. package/src/accounts/pollingDriftClientAccountSubscriber.ts +41 -5
  52. package/src/accounts/types.ts +6 -9
  53. package/src/accounts/utils.ts +42 -0
  54. package/src/accounts/webSocketAccountSubscriber.ts +1 -1
  55. package/src/accounts/webSocketDriftClientAccountSubscriber.ts +43 -8
  56. package/src/accounts/webSocketProgramAccountSubscriber.ts +1 -1
  57. package/src/config.ts +15 -1
  58. package/src/constants/perpMarkets.ts +22 -0
  59. package/src/constants/spotMarkets.ts +14 -1
  60. package/src/driftClient.ts +423 -91
  61. package/src/driftClientConfig.ts +2 -7
  62. package/src/events/eventSubscriber.ts +18 -11
  63. package/src/events/types.ts +1 -5
  64. package/src/idl/drift.json +169 -1
  65. package/src/index.ts +1 -0
  66. package/src/math/margin.ts +137 -1
  67. package/src/orderParams.ts +20 -12
  68. package/src/orderSubscriber/OrderSubscriber.ts +1 -15
  69. package/src/orderSubscriber/types.ts +0 -10
  70. package/src/tokenFaucet.ts +2 -2
  71. package/src/tx/baseTxSender.ts +2 -2
  72. package/src/tx/fastSingleTxSender.ts +2 -2
  73. package/src/tx/forwardOnlyTxSender.ts +2 -2
  74. package/src/tx/retryTxSender.ts +2 -2
  75. package/src/tx/txHandler.ts +8 -2
  76. package/src/tx/whileValidTxSender.ts +23 -26
  77. package/src/types.ts +30 -1
  78. package/src/user.ts +35 -13
  79. package/src/userConfig.ts +1 -7
  80. package/src/userMap/userMap.ts +1 -17
  81. package/src/userMap/userMapConfig.ts +0 -8
  82. package/src/userStatsConfig.ts +0 -7
  83. package/src/util/TransactionConfirmationManager.ts +155 -0
  84. package/tests/ci/idl.ts +12 -3
  85. package/tests/ci/verifyConstants.ts +13 -0
  86. package/tests/tx/TransactionConfirmationManager.test.ts +286 -0
  87. package/lib/accounts/grpcAccountSubscriber.d.ts +0 -16
  88. package/lib/accounts/grpcAccountSubscriber.js +0 -155
  89. package/lib/accounts/grpcDriftClientAccountSubscriber.d.ts +0 -13
  90. package/lib/accounts/grpcDriftClientAccountSubscriber.js +0 -96
  91. package/lib/accounts/grpcInsuranceFundStakeAccountSubscriber.d.ts +0 -10
  92. package/lib/accounts/grpcInsuranceFundStakeAccountSubscriber.js +0 -30
  93. package/lib/accounts/grpcProgramAccountSubscriber.d.ts +0 -19
  94. package/lib/accounts/grpcProgramAccountSubscriber.js +0 -161
  95. package/lib/accounts/grpcUserAccountSubscriber.d.ts +0 -10
  96. package/lib/accounts/grpcUserAccountSubscriber.js +0 -28
  97. package/lib/accounts/grpcUserStatsAccountSubscriber.d.ts +0 -10
  98. package/lib/accounts/grpcUserStatsAccountSubscriber.js +0 -28
  99. package/lib/orderSubscriber/grpcSubscription.d.ts +0 -25
  100. package/lib/orderSubscriber/grpcSubscription.js +0 -68
  101. package/lib/userMap/grpcSubscription.d.ts +0 -26
  102. package/lib/userMap/grpcSubscription.js +0 -42
  103. package/src/accounts/grpcAccountSubscriber.ts +0 -158
  104. package/src/accounts/grpcDriftClientAccountSubscriber.ts +0 -196
  105. package/src/accounts/grpcInsuranceFundStakeAccountSubscriber.ts +0 -62
  106. package/src/accounts/grpcProgramAccountSubscriber.ts +0 -181
  107. package/src/accounts/grpcUserAccountSubscriber.ts +0 -48
  108. package/src/accounts/grpcUserStatsAccountSubscriber.ts +0 -51
  109. package/src/orderSubscriber/grpcSubscription.ts +0 -126
  110. package/src/userMap/grpcSubscription.ts +0 -83
@@ -554,7 +554,7 @@
554
554
  }
555
555
  },
556
556
  {
557
- "name": "makerOrderId",
557
+ "name": "successCondition",
558
558
  "type": {
559
559
  "option": "u32"
560
560
  }
@@ -608,6 +608,60 @@
608
608
  }
609
609
  ]
610
610
  },
611
+ {
612
+ "name": "placeSwiftTakerOrder",
613
+ "accounts": [
614
+ {
615
+ "name": "state",
616
+ "isMut": false,
617
+ "isSigner": false
618
+ },
619
+ {
620
+ "name": "user",
621
+ "isMut": true,
622
+ "isSigner": false
623
+ },
624
+ {
625
+ "name": "userStats",
626
+ "isMut": true,
627
+ "isSigner": false
628
+ },
629
+ {
630
+ "name": "authority",
631
+ "isMut": false,
632
+ "isSigner": true
633
+ },
634
+ {
635
+ "name": "ixSysvar",
636
+ "isMut": false,
637
+ "isSigner": false,
638
+ "docs": [
639
+ "the supplied Sysvar could be anything else.",
640
+ "The Instruction Sysvar has not been implemented",
641
+ "in the Anchor framework yet, so this is the safe approach."
642
+ ]
643
+ }
644
+ ],
645
+ "args": [
646
+ {
647
+ "name": "swiftMessageBytes",
648
+ "type": "bytes"
649
+ },
650
+ {
651
+ "name": "swiftOrderParamsMessageBytes",
652
+ "type": "bytes"
653
+ },
654
+ {
655
+ "name": "swiftMessageSignature",
656
+ "type": {
657
+ "array": [
658
+ "u8",
659
+ 64
660
+ ]
661
+ }
662
+ }
663
+ ]
664
+ },
611
665
  {
612
666
  "name": "placeSpotOrder",
613
667
  "accounts": [
@@ -8050,6 +8104,81 @@
8050
8104
  ]
8051
8105
  }
8052
8106
  },
8107
+ {
8108
+ "name": "SwiftServerMessage",
8109
+ "type": {
8110
+ "kind": "struct",
8111
+ "fields": [
8112
+ {
8113
+ "name": "swiftOrderSignature",
8114
+ "type": {
8115
+ "array": [
8116
+ "u8",
8117
+ 64
8118
+ ]
8119
+ }
8120
+ },
8121
+ {
8122
+ "name": "slot",
8123
+ "type": "u64"
8124
+ }
8125
+ ]
8126
+ }
8127
+ },
8128
+ {
8129
+ "name": "SwiftOrderParamsMessage",
8130
+ "type": {
8131
+ "kind": "struct",
8132
+ "fields": [
8133
+ {
8134
+ "name": "swiftOrderParams",
8135
+ "type": {
8136
+ "defined": "OrderParams"
8137
+ }
8138
+ },
8139
+ {
8140
+ "name": "expectedOrderId",
8141
+ "type": "i32"
8142
+ },
8143
+ {
8144
+ "name": "subAccountId",
8145
+ "type": "u16"
8146
+ },
8147
+ {
8148
+ "name": "takeProfitOrderParams",
8149
+ "type": {
8150
+ "option": {
8151
+ "defined": "SwiftTriggerOrderParams"
8152
+ }
8153
+ }
8154
+ },
8155
+ {
8156
+ "name": "stopLossOrderParams",
8157
+ "type": {
8158
+ "option": {
8159
+ "defined": "SwiftTriggerOrderParams"
8160
+ }
8161
+ }
8162
+ }
8163
+ ]
8164
+ }
8165
+ },
8166
+ {
8167
+ "name": "SwiftTriggerOrderParams",
8168
+ "type": {
8169
+ "kind": "struct",
8170
+ "fields": [
8171
+ {
8172
+ "name": "triggerPrice",
8173
+ "type": "u64"
8174
+ },
8175
+ {
8176
+ "name": "baseAssetAmount",
8177
+ "type": "u64"
8178
+ }
8179
+ ]
8180
+ }
8181
+ },
8053
8182
  {
8054
8183
  "name": "ModifyOrderParams",
8055
8184
  "type": {
@@ -10122,6 +10251,20 @@
10122
10251
  ]
10123
10252
  }
10124
10253
  },
10254
+ {
10255
+ "name": "PlaceAndTakeOrderSuccessCondition",
10256
+ "type": {
10257
+ "kind": "enum",
10258
+ "variants": [
10259
+ {
10260
+ "name": "PartialFill"
10261
+ },
10262
+ {
10263
+ "name": "FullFill"
10264
+ }
10265
+ ]
10266
+ }
10267
+ },
10125
10268
  {
10126
10269
  "name": "PerpOperation",
10127
10270
  "type": {
@@ -12958,6 +13101,31 @@
12958
13101
  "code": 6284,
12959
13102
  "name": "InvalidPredictionMarketOrder",
12960
13103
  "msg": "Invalid prediction market order"
13104
+ },
13105
+ {
13106
+ "code": 6285,
13107
+ "name": "InvalidVerificationIxIndex",
13108
+ "msg": "Ed25519 Ix must be before place and make swift order ix"
13109
+ },
13110
+ {
13111
+ "code": 6286,
13112
+ "name": "SigVerificationFailed",
13113
+ "msg": "Swift message verificaiton failed"
13114
+ },
13115
+ {
13116
+ "code": 6287,
13117
+ "name": "MismatchedSwiftOrderParamsMarketIndex",
13118
+ "msg": "Market index mismatched b/w taker and maker swift order params"
13119
+ },
13120
+ {
13121
+ "code": 6288,
13122
+ "name": "InvalidSwiftOrderParam",
13123
+ "msg": "Swift only available for market/oracle perp orders"
13124
+ },
13125
+ {
13126
+ "code": 6289,
13127
+ "name": "PlaceAndTakeOrderSuccessConditionFailed",
13128
+ "msg": "Place and take order success condition failed"
12961
13129
  }
12962
13130
  ],
12963
13131
  "metadata": {
package/lib/index.d.ts CHANGED
@@ -107,5 +107,6 @@ export * from './memcmp';
107
107
  export * from './decode/user';
108
108
  export * from './blockhashSubscriber';
109
109
  export * from './util/chainClock';
110
+ export * from './util/TransactionConfirmationManager';
110
111
  export * from './clock/clockSubscriber';
111
112
  export { BN, PublicKey, pyth };
package/lib/index.js CHANGED
@@ -130,4 +130,5 @@ __exportStar(require("./memcmp"), exports);
130
130
  __exportStar(require("./decode/user"), exports);
131
131
  __exportStar(require("./blockhashSubscriber"), exports);
132
132
  __exportStar(require("./util/chainClock"), exports);
133
+ __exportStar(require("./util/TransactionConfirmationManager"), exports);
133
134
  __exportStar(require("./clock/clockSubscriber"), exports);
@@ -1,7 +1,7 @@
1
1
  /// <reference types="bn.js" />
2
2
  import { BN } from '@coral-xyz/anchor';
3
3
  import { OraclePriceData } from '../oracles/types';
4
- import { PerpMarketAccount, PerpPosition } from '..';
4
+ import { DriftClient, PerpMarketAccount, PerpPosition } from '..';
5
5
  export declare function calculateSizePremiumLiabilityWeight(size: BN, // AMM_RESERVE_PRECISION
6
6
  imfFactor: BN, liabilityWeight: BN, precision: BN): BN;
7
7
  export declare function calculateSizeDiscountAssetWeight(size: BN, // AMM_RESERVE_PRECISION
@@ -22,3 +22,18 @@ export declare function calculateWorstCasePerpLiabilityValue(perpPosition: PerpP
22
22
  worstCaseLiabilityValue: BN;
23
23
  };
24
24
  export declare function calculatePerpLiabilityValue(baseAssetAmount: BN, oraclePrice: BN, isPredictionMarket: boolean): BN;
25
+ /**
26
+ * Calculates the margin required to open a trade, in quote amount. Only accounts for the trade size as a scalar value, does not account for the trade direction or current open positions and whether the trade would _actually_ be risk-increasing and use any extra collateral.
27
+ * @param targetMarketIndex
28
+ * @param baseSize
29
+ * @returns
30
+ */
31
+ export declare function calculateMarginUSDCRequiredForTrade(driftClient: DriftClient, targetMarketIndex: number, baseSize: BN, userMaxMarginRatio?: number): BN;
32
+ /**
33
+ * Similar to calculatetMarginUSDCRequiredForTrade, but calculates how much of a given collateral is required to cover the margin requirements for a given trade. Basically does the same thing as getMarginUSDCRequiredForTrade but also accounts for asset weight of the selected collateral.
34
+ *
35
+ * Returns collateral required in the precision of the target collateral market.
36
+ */
37
+ export declare function calculateCollateralDepositRequiredForTrade(driftClient: DriftClient, targetMarketIndex: number, baseSize: BN, collateralIndex: number, userMaxMarginRatio?: number): BN;
38
+ export declare function calculateCollateralValueOfDeposit(driftClient: DriftClient, collateralIndex: number, baseSize: BN): BN;
39
+ export declare function calculateLiquidationPrice(freeCollateral: BN, freeCollateralDelta: BN, oraclePrice: BN): BN;
@@ -1,9 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.calculatePerpLiabilityValue = exports.calculateWorstCasePerpLiabilityValue = exports.calculateWorstCaseBaseAssetAmount = exports.calculateBaseAssetValueWithOracle = exports.calculateOraclePriceForPerpMargin = exports.calculateSizeDiscountAssetWeight = exports.calculateSizePremiumLiabilityWeight = void 0;
3
+ exports.calculateLiquidationPrice = exports.calculateCollateralValueOfDeposit = exports.calculateCollateralDepositRequiredForTrade = exports.calculateMarginUSDCRequiredForTrade = exports.calculatePerpLiabilityValue = exports.calculateWorstCasePerpLiabilityValue = exports.calculateWorstCaseBaseAssetAmount = exports.calculateBaseAssetValueWithOracle = exports.calculateOraclePriceForPerpMargin = exports.calculateSizeDiscountAssetWeight = exports.calculateSizePremiumLiabilityWeight = void 0;
4
4
  const utils_1 = require("./utils");
5
5
  const numericConstants_1 = require("../constants/numericConstants");
6
6
  const anchor_1 = require("@coral-xyz/anchor");
7
+ const __1 = require("..");
7
8
  const types_1 = require("../types");
8
9
  const assert_1 = require("../assert/assert");
9
10
  function calculateSizePremiumLiabilityWeight(size, // AMM_RESERVE_PRECISION
@@ -116,3 +117,68 @@ function calculatePerpLiabilityValue(baseAssetAmount, oraclePrice, isPredictionM
116
117
  }
117
118
  }
118
119
  exports.calculatePerpLiabilityValue = calculatePerpLiabilityValue;
120
+ /**
121
+ * Calculates the margin required to open a trade, in quote amount. Only accounts for the trade size as a scalar value, does not account for the trade direction or current open positions and whether the trade would _actually_ be risk-increasing and use any extra collateral.
122
+ * @param targetMarketIndex
123
+ * @param baseSize
124
+ * @returns
125
+ */
126
+ function calculateMarginUSDCRequiredForTrade(driftClient, targetMarketIndex, baseSize, userMaxMarginRatio) {
127
+ const targetMarket = driftClient.getPerpMarketAccount(targetMarketIndex);
128
+ const oracleData = driftClient.getOracleDataForPerpMarket(targetMarket.marketIndex);
129
+ const perpLiabilityValue = calculatePerpLiabilityValue(baseSize, oracleData.price, (0, types_1.isVariant)(targetMarket.contractType, 'prediction'));
130
+ const marginRequired = new anchor_1.BN((0, __1.calculateMarketMarginRatio)(targetMarket, baseSize.abs(), 'Initial', userMaxMarginRatio))
131
+ .mul(perpLiabilityValue)
132
+ .div(numericConstants_1.MARGIN_PRECISION);
133
+ return marginRequired;
134
+ }
135
+ exports.calculateMarginUSDCRequiredForTrade = calculateMarginUSDCRequiredForTrade;
136
+ /**
137
+ * Similar to calculatetMarginUSDCRequiredForTrade, but calculates how much of a given collateral is required to cover the margin requirements for a given trade. Basically does the same thing as getMarginUSDCRequiredForTrade but also accounts for asset weight of the selected collateral.
138
+ *
139
+ * Returns collateral required in the precision of the target collateral market.
140
+ */
141
+ function calculateCollateralDepositRequiredForTrade(driftClient, targetMarketIndex, baseSize, collateralIndex, userMaxMarginRatio) {
142
+ const marginRequiredUsdc = calculateMarginUSDCRequiredForTrade(driftClient, targetMarketIndex, baseSize, userMaxMarginRatio);
143
+ const collateralMarket = driftClient.getSpotMarketAccount(collateralIndex);
144
+ const collateralOracleData = driftClient.getOracleDataForSpotMarket(collateralIndex);
145
+ const scaledAssetWeight = (0, __1.calculateScaledInitialAssetWeight)(collateralMarket, collateralOracleData.price);
146
+ // Base amount required to deposit = (marginRequiredUsdc / priceOfAsset) / assetWeight .. (E.g. $100 required / $10000 price / 0.5 weight)
147
+ const baseAmountRequired = driftClient
148
+ .convertToSpotPrecision(collateralIndex, marginRequiredUsdc)
149
+ .mul(numericConstants_1.PRICE_PRECISION) // adjust for division by oracle price
150
+ .mul(numericConstants_1.SPOT_MARKET_WEIGHT_PRECISION) // adjust for division by scaled asset weight
151
+ .div(collateralOracleData.price)
152
+ .div(scaledAssetWeight)
153
+ .div(numericConstants_1.QUOTE_PRECISION); // adjust for marginRequiredUsdc value's QUOTE_PRECISION
154
+ // TODO : Round by step size?
155
+ return baseAmountRequired;
156
+ }
157
+ exports.calculateCollateralDepositRequiredForTrade = calculateCollateralDepositRequiredForTrade;
158
+ function calculateCollateralValueOfDeposit(driftClient, collateralIndex, baseSize) {
159
+ const collateralMarket = driftClient.getSpotMarketAccount(collateralIndex);
160
+ const collateralOracleData = driftClient.getOracleDataForSpotMarket(collateralIndex);
161
+ const scaledAssetWeight = (0, __1.calculateScaledInitialAssetWeight)(collateralMarket, collateralOracleData.price);
162
+ // CollateralBaseValue = oracle price * collateral base amount (and shift to QUOTE_PRECISION)
163
+ const collateralBaseValue = collateralOracleData.price
164
+ .mul(baseSize)
165
+ .mul(numericConstants_1.QUOTE_PRECISION)
166
+ .div(numericConstants_1.PRICE_PRECISION)
167
+ .div(new anchor_1.BN(10).pow(new anchor_1.BN(collateralMarket.decimals)));
168
+ const depositCollateralValue = collateralBaseValue
169
+ .mul(scaledAssetWeight)
170
+ .div(numericConstants_1.SPOT_MARKET_WEIGHT_PRECISION);
171
+ return depositCollateralValue;
172
+ }
173
+ exports.calculateCollateralValueOfDeposit = calculateCollateralValueOfDeposit;
174
+ function calculateLiquidationPrice(freeCollateral, freeCollateralDelta, oraclePrice) {
175
+ const liqPriceDelta = freeCollateral
176
+ .mul(numericConstants_1.QUOTE_PRECISION)
177
+ .div(freeCollateralDelta);
178
+ const liqPrice = oraclePrice.sub(liqPriceDelta);
179
+ if (liqPrice.lt(numericConstants_1.ZERO)) {
180
+ return new anchor_1.BN(-1);
181
+ }
182
+ return liqPrice;
183
+ }
184
+ exports.calculateLiquidationPrice = calculateLiquidationPrice;
@@ -3,27 +3,27 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getOrderParams = exports.getMarketOrderParams = exports.getTriggerLimitOrderParams = exports.getTriggerMarketOrderParams = exports.getLimitOrderParams = void 0;
4
4
  const types_1 = require("./types");
5
5
  function getLimitOrderParams(params) {
6
- return Object.assign({}, params, {
6
+ return getOrderParams(Object.assign({}, params, {
7
7
  orderType: types_1.OrderType.LIMIT,
8
- });
8
+ }));
9
9
  }
10
10
  exports.getLimitOrderParams = getLimitOrderParams;
11
11
  function getTriggerMarketOrderParams(params) {
12
- return Object.assign({}, params, {
12
+ return getOrderParams(Object.assign({}, params, {
13
13
  orderType: types_1.OrderType.TRIGGER_MARKET,
14
- });
14
+ }));
15
15
  }
16
16
  exports.getTriggerMarketOrderParams = getTriggerMarketOrderParams;
17
17
  function getTriggerLimitOrderParams(params) {
18
- return Object.assign({}, params, {
18
+ return getOrderParams(Object.assign({}, params, {
19
19
  orderType: types_1.OrderType.TRIGGER_LIMIT,
20
- });
20
+ }));
21
21
  }
22
22
  exports.getTriggerLimitOrderParams = getTriggerLimitOrderParams;
23
23
  function getMarketOrderParams(params) {
24
- return Object.assign({}, params, {
24
+ return getOrderParams(Object.assign({}, params, {
25
25
  orderType: types_1.OrderType.MARKET,
26
- });
26
+ }));
27
27
  }
28
28
  exports.getMarketOrderParams = getMarketOrderParams;
29
29
  /**
@@ -10,14 +10,13 @@ import { PollingSubscription } from './PollingSubscription';
10
10
  import { WebsocketSubscription } from './WebsocketSubscription';
11
11
  import StrictEventEmitter from 'strict-event-emitter-types';
12
12
  import { EventEmitter } from 'events';
13
- import { grpcSubscription } from './grpcSubscription';
14
13
  export declare class OrderSubscriber {
15
14
  driftClient: DriftClient;
16
15
  usersAccounts: Map<string, {
17
16
  slot: number;
18
17
  userAccount: UserAccount;
19
18
  }>;
20
- subscription: PollingSubscription | WebsocketSubscription | grpcSubscription;
19
+ subscription: PollingSubscription | WebsocketSubscription;
21
20
  commitment: Commitment;
22
21
  eventEmitter: StrictEventEmitter<EventEmitter, OrderSubscriberEvents>;
23
22
  fetchPromise?: Promise<void>;
@@ -10,10 +10,9 @@ const WebsocketSubscription_1 = require("./WebsocketSubscription");
10
10
  const events_1 = require("events");
11
11
  const index_1 = require("../index");
12
12
  const user_1 = require("../decode/user");
13
- const grpcSubscription_1 = require("./grpcSubscription");
14
13
  class OrderSubscriber {
15
14
  constructor(config) {
16
- var _a, _b, _c, _d, _e;
15
+ var _a, _b, _c;
17
16
  this.usersAccounts = new Map();
18
17
  this.driftClient = config.driftClient;
19
18
  this.commitment = config.subscriptionConfig.commitment || 'processed';
@@ -23,34 +22,20 @@ class OrderSubscriber {
23
22
  frequency: config.subscriptionConfig.frequency,
24
23
  });
25
24
  }
26
- else if (config.subscriptionConfig.type === 'grpc') {
27
- this.subscription = new grpcSubscription_1.grpcSubscription({
28
- grpcConfigs: config.subscriptionConfig.configs,
29
- orderSubscriber: this,
30
- commitment: this.commitment,
31
- skipInitialLoad: config.subscriptionConfig.skipInitialLoad,
32
- resubOpts: {
33
- resubTimeoutMs: (_a = config.subscriptionConfig) === null || _a === void 0 ? void 0 : _a.resubTimeoutMs,
34
- logResubMessages: (_b = config.subscriptionConfig) === null || _b === void 0 ? void 0 : _b.logResubMessages,
35
- },
36
- resyncIntervalMs: config.subscriptionConfig.resyncIntervalMs,
37
- decoded: config.decodeData,
38
- });
39
- }
40
25
  else {
41
26
  this.subscription = new WebsocketSubscription_1.WebsocketSubscription({
42
27
  orderSubscriber: this,
43
28
  commitment: this.commitment,
44
29
  skipInitialLoad: config.subscriptionConfig.skipInitialLoad,
45
30
  resubOpts: {
46
- resubTimeoutMs: (_c = config.subscriptionConfig) === null || _c === void 0 ? void 0 : _c.resubTimeoutMs,
47
- logResubMessages: (_d = config.subscriptionConfig) === null || _d === void 0 ? void 0 : _d.logResubMessages,
31
+ resubTimeoutMs: (_a = config.subscriptionConfig) === null || _a === void 0 ? void 0 : _a.resubTimeoutMs,
32
+ logResubMessages: (_b = config.subscriptionConfig) === null || _b === void 0 ? void 0 : _b.logResubMessages,
48
33
  },
49
34
  resyncIntervalMs: config.subscriptionConfig.resyncIntervalMs,
50
35
  decoded: config.decodeData,
51
36
  });
52
37
  }
53
- if ((_e = config.fastDecode) !== null && _e !== void 0 ? _e : true) {
38
+ if ((_c = config.fastDecode) !== null && _c !== void 0 ? _c : true) {
54
39
  this.decodeFn = (name, data) => (0, user_1.decodeUser)(data);
55
40
  }
56
41
  else {
@@ -1,21 +1,12 @@
1
1
  import { Commitment, PublicKey } from '@solana/web3.js';
2
2
  import { Order, UserAccount } from '../types';
3
3
  import { DriftClient } from '../driftClient';
4
- import { GrpcConfigs } from '../accounts/types';
5
4
  export type OrderSubscriberConfig = {
6
5
  driftClient: DriftClient;
7
6
  subscriptionConfig: {
8
7
  type: 'polling';
9
8
  frequency: number;
10
9
  commitment?: Commitment;
11
- } | {
12
- type: 'grpc';
13
- skipInitialLoad?: boolean;
14
- resubTimeoutMs?: number;
15
- logResubMessages?: boolean;
16
- resyncIntervalMs?: number;
17
- configs: GrpcConfigs;
18
- commitment?: Commitment;
19
10
  } | {
20
11
  type: 'websocket';
21
12
  skipInitialLoad?: boolean;
@@ -31,13 +31,14 @@ const anchor = __importStar(require("@coral-xyz/anchor"));
31
31
  const anchor_1 = require("@coral-xyz/anchor");
32
32
  const spl_token_1 = require("@solana/spl-token");
33
33
  const web3_js_1 = require("@solana/web3.js");
34
+ const _1 = require(".");
34
35
  const token_faucet_json_1 = __importDefault(require("./idl/token_faucet.json"));
35
36
  class TokenFaucet {
36
37
  constructor(connection, wallet, programId, mint, opts, context) {
37
38
  this.connection = connection;
38
39
  this.context = context;
39
40
  this.wallet = wallet;
40
- this.opts = opts || anchor_1.AnchorProvider.defaultOptions();
41
+ this.opts = opts || _1.DEFAULT_CONFIRMATION_OPTS;
41
42
  // @ts-ignore
42
43
  const provider = new anchor_1.AnchorProvider(context ? context.connection.toConnection() : this.connection,
43
44
  // @ts-ignore
@@ -6,17 +6,17 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.BaseTxSender = void 0;
7
7
  const types_1 = require("./types");
8
8
  const web3_js_1 = require("@solana/web3.js");
9
- const anchor_1 = require("@coral-xyz/anchor");
10
9
  const assert_1 = __importDefault(require("assert"));
11
10
  const bs58_1 = __importDefault(require("bs58"));
12
11
  const txHandler_1 = require("./txHandler");
13
12
  const node_cache_1 = __importDefault(require("node-cache"));
13
+ const config_1 = require("../config");
14
14
  const BASELINE_TX_LAND_RATE = 0.9;
15
15
  const DEFAULT_TIMEOUT = 35000;
16
16
  const DEFAULT_TX_LAND_RATE_LOOKBACK_WINDOW_MINUTES = 10;
17
17
  const NOT_CONFIRMED_ERROR_CODE = -1001;
18
18
  class BaseTxSender {
19
- constructor({ connection, wallet, opts = anchor_1.AnchorProvider.defaultOptions(), timeout = DEFAULT_TIMEOUT, additionalConnections = new Array(), confirmationStrategy = types_1.ConfirmationStrategy.Combo, additionalTxSenderCallbacks, trackTxLandRate, txHandler, txLandRateLookbackWindowMinutes = DEFAULT_TX_LAND_RATE_LOOKBACK_WINDOW_MINUTES, landRateToFeeFunc, }) {
19
+ constructor({ connection, wallet, opts = config_1.DEFAULT_CONFIRMATION_OPTS, timeout = DEFAULT_TIMEOUT, additionalConnections = new Array(), confirmationStrategy = types_1.ConfirmationStrategy.Combo, additionalTxSenderCallbacks, trackTxLandRate, txHandler, txLandRateLookbackWindowMinutes = DEFAULT_TX_LAND_RATE_LOOKBACK_WINDOW_MINUTES, landRateToFeeFunc, }) {
20
20
  this.timeoutCount = 0;
21
21
  this.txLandRate = 0;
22
22
  this.lastPriorityFeeSuggestion = 1;
@@ -2,12 +2,12 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.FastSingleTxSender = void 0;
4
4
  const types_1 = require("./types");
5
- const anchor_1 = require("@coral-xyz/anchor");
6
5
  const baseTxSender_1 = require("./baseTxSender");
6
+ const config_1 = require("../config");
7
7
  const DEFAULT_TIMEOUT = 35000;
8
8
  const DEFAULT_BLOCKHASH_REFRESH = 10000;
9
9
  class FastSingleTxSender extends baseTxSender_1.BaseTxSender {
10
- constructor({ connection, wallet, opts = { ...anchor_1.AnchorProvider.defaultOptions(), maxRetries: 0 }, timeout = DEFAULT_TIMEOUT, blockhashRefreshInterval = DEFAULT_BLOCKHASH_REFRESH, additionalConnections = new Array(), skipConfirmation = false, confirmInBackground = false, blockhashCommitment = 'finalized', confirmationStrategy = types_1.ConfirmationStrategy.Combo, trackTxLandRate, txHandler, txLandRateLookbackWindowMinutes, landRateToFeeFunc, }) {
10
+ constructor({ connection, wallet, opts = { ...config_1.DEFAULT_CONFIRMATION_OPTS, maxRetries: 0 }, timeout = DEFAULT_TIMEOUT, blockhashRefreshInterval = DEFAULT_BLOCKHASH_REFRESH, additionalConnections = new Array(), skipConfirmation = false, confirmInBackground = false, blockhashCommitment = 'finalized', confirmationStrategy = types_1.ConfirmationStrategy.Combo, trackTxLandRate, txHandler, txLandRateLookbackWindowMinutes, landRateToFeeFunc, }) {
11
11
  super({
12
12
  connection,
13
13
  wallet,
@@ -4,15 +4,15 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.ForwardOnlyTxSender = void 0;
7
- const anchor_1 = require("@coral-xyz/anchor");
8
7
  const web3_js_1 = require("@solana/web3.js");
9
8
  const bs58_1 = __importDefault(require("bs58"));
10
9
  const baseTxSender_1 = require("./baseTxSender");
11
10
  const types_1 = require("./types");
11
+ const config_1 = require("../config");
12
12
  const DEFAULT_TIMEOUT = 35000;
13
13
  const DEFAULT_RETRY = 5000;
14
14
  class ForwardOnlyTxSender extends baseTxSender_1.BaseTxSender {
15
- constructor({ connection, wallet, opts = { ...anchor_1.AnchorProvider.defaultOptions(), maxRetries: 0 }, timeout = DEFAULT_TIMEOUT, retrySleep = DEFAULT_RETRY, confirmationStrategy = types_1.ConfirmationStrategy.Combo, additionalTxSenderCallbacks = [], txHandler, trackTxLandRate, txLandRateLookbackWindowMinutes, landRateToFeeFunc, }) {
15
+ constructor({ connection, wallet, opts = { ...config_1.DEFAULT_CONFIRMATION_OPTS, maxRetries: 0 }, timeout = DEFAULT_TIMEOUT, retrySleep = DEFAULT_RETRY, confirmationStrategy = types_1.ConfirmationStrategy.Combo, additionalTxSenderCallbacks = [], txHandler, trackTxLandRate, txLandRateLookbackWindowMinutes, landRateToFeeFunc, }) {
16
16
  super({
17
17
  connection,
18
18
  wallet,
@@ -2,12 +2,12 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.RetryTxSender = void 0;
4
4
  const types_1 = require("./types");
5
- const anchor_1 = require("@coral-xyz/anchor");
6
5
  const baseTxSender_1 = require("./baseTxSender");
6
+ const config_1 = require("../config");
7
7
  const DEFAULT_TIMEOUT = 35000;
8
8
  const DEFAULT_RETRY = 2000;
9
9
  class RetryTxSender extends baseTxSender_1.BaseTxSender {
10
- constructor({ connection, wallet, opts = { ...anchor_1.AnchorProvider.defaultOptions(), maxRetries: 0 }, timeout = DEFAULT_TIMEOUT, retrySleep = DEFAULT_RETRY, additionalConnections = new Array(), confirmationStrategy = types_1.ConfirmationStrategy.Combo, additionalTxSenderCallbacks = [], txHandler, trackTxLandRate, txLandRateLookbackWindowMinutes, landRateToFeeFunc, }) {
10
+ constructor({ connection, wallet, opts = { ...config_1.DEFAULT_CONFIRMATION_OPTS, maxRetries: 0 }, timeout = DEFAULT_TIMEOUT, retrySleep = DEFAULT_RETRY, additionalConnections = new Array(), confirmationStrategy = types_1.ConfirmationStrategy.Combo, additionalTxSenderCallbacks = [], txHandler, trackTxLandRate, txLandRateLookbackWindowMinutes, landRateToFeeFunc, }) {
11
11
  super({
12
12
  connection,
13
13
  wallet,
@@ -11,6 +11,7 @@ const computeUnits_1 = require("../util/computeUnits");
11
11
  const cachedBlockhashFetcher_1 = require("./blockhashFetcher/cachedBlockhashFetcher");
12
12
  const baseBlockhashFetcher_1 = require("./blockhashFetcher/baseBlockhashFetcher");
13
13
  const utils_1 = require("./utils");
14
+ const config_1 = require("../config");
14
15
  /**
15
16
  * Explanation for SIGNATURE_BLOCK_AND_EXPIRY:
16
17
  *
@@ -26,22 +27,24 @@ const RECENT_BLOCKHASH_STALE_TIME_MS = 2000; // Reuse blockhashes within this ti
26
27
  */
27
28
  class TxHandler {
28
29
  constructor(props) {
29
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
30
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u;
30
31
  this.blockHashToLastValidBlockHeightLookup = {};
31
32
  this.returnBlockHeightsWithSignedTxCallbackData = false;
32
- this.blockhashCommitment = 'finalized';
33
+ this.blockhashCommitment = config_1.DEFAULT_CONFIRMATION_OPTS.commitment;
33
34
  this.getProps = (wallet, confirmationOpts) => [wallet !== null && wallet !== void 0 ? wallet : this.wallet, confirmationOpts !== null && confirmationOpts !== void 0 ? confirmationOpts : this.confirmationOptions];
34
35
  this.connection = props.connection;
35
36
  this.wallet = props.wallet;
36
37
  this.confirmationOptions = props.confirmationOptions;
37
- this.blockHashFetcher = ((_a = props === null || props === void 0 ? void 0 : props.config) === null || _a === void 0 ? void 0 : _a.blockhashCachingEnabled)
38
- ? new cachedBlockhashFetcher_1.CachedBlockhashFetcher(this.connection, this.blockhashCommitment, (_d = (_c = (_b = props === null || props === void 0 ? void 0 : props.config) === null || _b === void 0 ? void 0 : _b.blockhashCachingConfig) === null || _c === void 0 ? void 0 : _c.retryCount) !== null && _d !== void 0 ? _d : BLOCKHASH_FETCH_RETRY_COUNT, (_g = (_f = (_e = props === null || props === void 0 ? void 0 : props.config) === null || _e === void 0 ? void 0 : _e.blockhashCachingConfig) === null || _f === void 0 ? void 0 : _f.retrySleepTimeMs) !== null && _g !== void 0 ? _g : BLOCKHASH_FETCH_RETRY_SLEEP, (_k = (_j = (_h = props === null || props === void 0 ? void 0 : props.config) === null || _h === void 0 ? void 0 : _h.blockhashCachingConfig) === null || _j === void 0 ? void 0 : _j.staleCacheTimeMs) !== null && _k !== void 0 ? _k : RECENT_BLOCKHASH_STALE_TIME_MS)
38
+ this.blockhashCommitment =
39
+ (_e = (_d = (_b = (_a = props.confirmationOptions) === null || _a === void 0 ? void 0 : _a.preflightCommitment) !== null && _b !== void 0 ? _b : (_c = props === null || props === void 0 ? void 0 : props.connection) === null || _c === void 0 ? void 0 : _c.commitment) !== null && _d !== void 0 ? _d : this.blockhashCommitment) !== null && _e !== void 0 ? _e : 'confirmed';
40
+ this.blockHashFetcher = ((_f = props === null || props === void 0 ? void 0 : props.config) === null || _f === void 0 ? void 0 : _f.blockhashCachingEnabled)
41
+ ? new cachedBlockhashFetcher_1.CachedBlockhashFetcher(this.connection, this.blockhashCommitment, (_j = (_h = (_g = props === null || props === void 0 ? void 0 : props.config) === null || _g === void 0 ? void 0 : _g.blockhashCachingConfig) === null || _h === void 0 ? void 0 : _h.retryCount) !== null && _j !== void 0 ? _j : BLOCKHASH_FETCH_RETRY_COUNT, (_m = (_l = (_k = props === null || props === void 0 ? void 0 : props.config) === null || _k === void 0 ? void 0 : _k.blockhashCachingConfig) === null || _l === void 0 ? void 0 : _l.retrySleepTimeMs) !== null && _m !== void 0 ? _m : BLOCKHASH_FETCH_RETRY_SLEEP, (_q = (_p = (_o = props === null || props === void 0 ? void 0 : props.config) === null || _o === void 0 ? void 0 : _o.blockhashCachingConfig) === null || _p === void 0 ? void 0 : _p.staleCacheTimeMs) !== null && _q !== void 0 ? _q : RECENT_BLOCKHASH_STALE_TIME_MS)
39
42
  : new baseBlockhashFetcher_1.BaseBlockhashFetcher(this.connection, this.blockhashCommitment);
40
43
  // #Optionals
41
44
  this.returnBlockHeightsWithSignedTxCallbackData =
42
- (_m = (_l = props.opts) === null || _l === void 0 ? void 0 : _l.returnBlockHeightsWithSignedTxCallbackData) !== null && _m !== void 0 ? _m : false;
43
- this.onSignedCb = (_o = props.opts) === null || _o === void 0 ? void 0 : _o.onSignedCb;
44
- this.preSignedCb = (_p = props.opts) === null || _p === void 0 ? void 0 : _p.preSignedCb;
45
+ (_s = (_r = props.opts) === null || _r === void 0 ? void 0 : _r.returnBlockHeightsWithSignedTxCallbackData) !== null && _s !== void 0 ? _s : false;
46
+ this.onSignedCb = (_t = props.opts) === null || _t === void 0 ? void 0 : _t.onSignedCb;
47
+ this.preSignedCb = (_u = props.opts) === null || _u === void 0 ? void 0 : _u.preSignedCb;
45
48
  }
46
49
  addHashAndExpiryToLookup(hashAndExpiry) {
47
50
  if (!this.returnBlockHeightsWithSignedTxCallbackData)
@@ -1,6 +1,6 @@
1
1
  /// <reference types="node" />
2
2
  import { TxSigAndSlot } from './types';
3
- import { Commitment, ConfirmOptions, Connection, Signer, Transaction, VersionedTransaction } from '@solana/web3.js';
3
+ import { ConfirmOptions, Connection, Signer, Transaction, VersionedTransaction } from '@solana/web3.js';
4
4
  import { BaseTxSender } from './baseTxSender';
5
5
  import { TxHandler } from './txHandler';
6
6
  import { IWallet } from '../types';
@@ -19,17 +19,15 @@ export declare class WhileValidTxSender extends BaseTxSender {
19
19
  blockhash: string;
20
20
  lastValidBlockHeight: number;
21
21
  }>;
22
- blockhashCommitment: Commitment;
23
22
  useBlockHeightOffset: boolean;
24
23
  private checkAndSetUseBlockHeightOffset;
25
- constructor({ connection, wallet, opts, retrySleep, additionalConnections, additionalTxSenderCallbacks, blockhashCommitment, txHandler, trackTxLandRate, txLandRateLookbackWindowMinutes, landRateToFeeFunc, }: {
24
+ constructor({ connection, wallet, opts, retrySleep, additionalConnections, additionalTxSenderCallbacks, txHandler, trackTxLandRate, txLandRateLookbackWindowMinutes, landRateToFeeFunc, }: {
26
25
  connection: Connection;
27
26
  wallet: IWallet;
28
27
  opts?: ConfirmOptions;
29
28
  retrySleep?: number;
30
29
  additionalConnections?: any;
31
30
  additionalTxSenderCallbacks?: ((base58EncodedTx: string) => void)[];
32
- blockhashCommitment?: Commitment;
33
31
  txHandler?: TxHandler;
34
32
  trackTxLandRate?: boolean;
35
33
  txLandRateLookbackWindowMinutes?: number;