@drift-labs/sdk 2.145.0 → 2.146.0-alpha.13

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 (99) hide show
  1. package/.env +4 -0
  2. package/VERSION +1 -1
  3. package/lib/browser/accounts/grpcMultiUserAccountSubscriber.js +8 -1
  4. package/lib/browser/accounts/webSocketProgramAccountSubscriberV2.d.ts +99 -7
  5. package/lib/browser/accounts/webSocketProgramAccountSubscriberV2.js +435 -144
  6. package/lib/browser/adminClient.d.ts +5 -1
  7. package/lib/browser/adminClient.js +57 -23
  8. package/lib/browser/constants/numericConstants.d.ts +2 -0
  9. package/lib/browser/constants/numericConstants.js +5 -1
  10. package/lib/browser/constants/perpMarkets.js +0 -2
  11. package/lib/browser/decode/user.js +4 -0
  12. package/lib/browser/driftClient.d.ts +25 -10
  13. package/lib/browser/driftClient.js +238 -41
  14. package/lib/browser/driftClientConfig.d.ts +7 -2
  15. package/lib/browser/idl/drift.json +245 -22
  16. package/lib/browser/index.d.ts +4 -0
  17. package/lib/browser/index.js +9 -1
  18. package/lib/browser/marginCalculation.d.ts +86 -0
  19. package/lib/browser/marginCalculation.js +209 -0
  20. package/lib/browser/math/margin.d.ts +1 -1
  21. package/lib/browser/math/margin.js +8 -1
  22. package/lib/browser/math/position.d.ts +1 -0
  23. package/lib/browser/math/position.js +10 -2
  24. package/lib/browser/math/spotPosition.d.ts +1 -1
  25. package/lib/browser/math/spotPosition.js +3 -2
  26. package/lib/browser/math/superStake.d.ts +3 -2
  27. package/lib/browser/types.d.ts +13 -0
  28. package/lib/browser/types.js +12 -1
  29. package/lib/browser/user.d.ts +59 -11
  30. package/lib/browser/user.js +348 -43
  31. package/lib/node/accounts/grpcMultiUserAccountSubscriber.d.ts.map +1 -1
  32. package/lib/node/accounts/grpcMultiUserAccountSubscriber.js +8 -1
  33. package/lib/node/accounts/webSocketProgramAccountSubscriberV2.d.ts +99 -7
  34. package/lib/node/accounts/webSocketProgramAccountSubscriberV2.d.ts.map +1 -1
  35. package/lib/node/accounts/webSocketProgramAccountSubscriberV2.js +435 -144
  36. package/lib/node/adminClient.d.ts +5 -1
  37. package/lib/node/adminClient.d.ts.map +1 -1
  38. package/lib/node/adminClient.js +57 -23
  39. package/lib/node/constants/numericConstants.d.ts +2 -0
  40. package/lib/node/constants/numericConstants.d.ts.map +1 -1
  41. package/lib/node/constants/numericConstants.js +5 -1
  42. package/lib/node/constants/perpMarkets.d.ts.map +1 -1
  43. package/lib/node/constants/perpMarkets.js +0 -2
  44. package/lib/node/decode/user.d.ts.map +1 -1
  45. package/lib/node/decode/user.js +4 -0
  46. package/lib/node/driftClient.d.ts +25 -10
  47. package/lib/node/driftClient.d.ts.map +1 -1
  48. package/lib/node/driftClient.js +238 -41
  49. package/lib/node/driftClientConfig.d.ts +7 -2
  50. package/lib/node/driftClientConfig.d.ts.map +1 -1
  51. package/lib/node/idl/drift.json +245 -22
  52. package/lib/node/index.d.ts +4 -0
  53. package/lib/node/index.d.ts.map +1 -1
  54. package/lib/node/index.js +9 -1
  55. package/lib/node/marginCalculation.d.ts +87 -0
  56. package/lib/node/marginCalculation.d.ts.map +1 -0
  57. package/lib/node/marginCalculation.js +209 -0
  58. package/lib/node/math/margin.d.ts +1 -1
  59. package/lib/node/math/margin.d.ts.map +1 -1
  60. package/lib/node/math/margin.js +8 -1
  61. package/lib/node/math/position.d.ts +1 -0
  62. package/lib/node/math/position.d.ts.map +1 -1
  63. package/lib/node/math/position.js +10 -2
  64. package/lib/node/math/spotPosition.d.ts +1 -1
  65. package/lib/node/math/spotPosition.d.ts.map +1 -1
  66. package/lib/node/math/spotPosition.js +3 -2
  67. package/lib/node/math/superStake.d.ts +3 -2
  68. package/lib/node/math/superStake.d.ts.map +1 -1
  69. package/lib/node/types.d.ts +13 -0
  70. package/lib/node/types.d.ts.map +1 -1
  71. package/lib/node/types.js +12 -1
  72. package/lib/node/user.d.ts +59 -11
  73. package/lib/node/user.d.ts.map +1 -1
  74. package/lib/node/user.js +348 -43
  75. package/package.json +1 -1
  76. package/scripts/deposit-isolated-positions.ts +110 -0
  77. package/scripts/single-grpc-client-test.ts +71 -21
  78. package/scripts/withdraw-isolated-positions.ts +174 -0
  79. package/src/accounts/grpcMultiUserAccountSubscriber.ts +8 -1
  80. package/src/accounts/webSocketProgramAccountSubscriberV2.ts +566 -167
  81. package/src/adminClient.ts +74 -25
  82. package/src/constants/numericConstants.ts +5 -0
  83. package/src/constants/perpMarkets.ts +0 -3
  84. package/src/decode/user.ts +7 -1
  85. package/src/driftClient.ts +465 -52
  86. package/src/driftClientConfig.ts +15 -8
  87. package/src/idl/drift.json +246 -23
  88. package/src/index.ts +4 -0
  89. package/src/margin/README.md +143 -0
  90. package/src/marginCalculation.ts +306 -0
  91. package/src/math/margin.ts +13 -1
  92. package/src/math/position.ts +12 -2
  93. package/src/math/spotPosition.ts +6 -2
  94. package/src/types.ts +16 -0
  95. package/src/user.ts +623 -81
  96. package/tests/amm/test.ts +1 -1
  97. package/tests/dlob/helpers.ts +6 -3
  98. package/tests/user/getMarginCalculation.ts +405 -0
  99. package/tests/user/test.ts +0 -7
@@ -0,0 +1,306 @@
1
+ import { BN } from '@coral-xyz/anchor';
2
+ import { MARGIN_PRECISION } from './constants/numericConstants';
3
+ import { MarketType } from './types';
4
+
5
+ export type MarginCategory = 'Initial' | 'Maintenance' | 'Fill';
6
+
7
+ export type MarginCalculationMode =
8
+ | { type: 'Standard' }
9
+ | { type: 'Liquidation' };
10
+
11
+ export class MarketIdentifier {
12
+ marketType: MarketType;
13
+ marketIndex: number;
14
+
15
+ private constructor(marketType: MarketType, marketIndex: number) {
16
+ this.marketType = marketType;
17
+ this.marketIndex = marketIndex;
18
+ }
19
+
20
+ static spot(marketIndex: number): MarketIdentifier {
21
+ return new MarketIdentifier(MarketType.SPOT, marketIndex);
22
+ }
23
+
24
+ static perp(marketIndex: number): MarketIdentifier {
25
+ return new MarketIdentifier(MarketType.PERP, marketIndex);
26
+ }
27
+
28
+ equals(other: MarketIdentifier | undefined): boolean {
29
+ return (
30
+ !!other &&
31
+ this.marketType === other.marketType &&
32
+ this.marketIndex === other.marketIndex
33
+ );
34
+ }
35
+ }
36
+
37
+ export class MarginContext {
38
+ marginType: MarginCategory;
39
+ mode: MarginCalculationMode;
40
+ strict: boolean;
41
+ ignoreInvalidDepositOracles: boolean;
42
+ marginBuffer: BN; // scaled by MARGIN_PRECISION
43
+ marginRatioOverride?: number;
44
+
45
+ private constructor(marginType: MarginCategory) {
46
+ this.marginType = marginType;
47
+ this.mode = { type: 'Standard' };
48
+ this.strict = false;
49
+ this.ignoreInvalidDepositOracles = false;
50
+ this.marginBuffer = new BN(0);
51
+ }
52
+
53
+ static standard(marginType: MarginCategory): MarginContext {
54
+ return new MarginContext(marginType);
55
+ }
56
+
57
+ static liquidation(marginBuffer: BN): MarginContext {
58
+ const ctx = new MarginContext('Maintenance');
59
+ ctx.mode = { type: 'Liquidation' };
60
+ ctx.marginBuffer = marginBuffer ?? new BN(0);
61
+ return ctx;
62
+ }
63
+
64
+ strictMode(strict: boolean): this {
65
+ this.strict = strict;
66
+ return this;
67
+ }
68
+
69
+ ignoreInvalidDeposits(ignore: boolean): this {
70
+ this.ignoreInvalidDepositOracles = ignore;
71
+ return this;
72
+ }
73
+
74
+ setMarginBuffer(buffer?: BN): this {
75
+ this.marginBuffer = buffer ?? new BN(0);
76
+ return this;
77
+ }
78
+
79
+ setMarginRatioOverride(ratio: number): this {
80
+ this.marginRatioOverride = ratio;
81
+ return this;
82
+ }
83
+ }
84
+
85
+ export class IsolatedMarginCalculation {
86
+ marginRequirement: BN;
87
+ totalCollateral: BN; // deposit + pnl
88
+ totalCollateralBuffer: BN;
89
+ marginRequirementPlusBuffer: BN;
90
+
91
+ constructor() {
92
+ this.marginRequirement = new BN(0);
93
+ this.totalCollateral = new BN(0);
94
+ this.totalCollateralBuffer = new BN(0);
95
+ this.marginRequirementPlusBuffer = new BN(0);
96
+ }
97
+
98
+ getTotalCollateralPlusBuffer(): BN {
99
+ return this.totalCollateral.add(this.totalCollateralBuffer);
100
+ }
101
+
102
+ meetsMarginRequirement(): boolean {
103
+ return this.totalCollateral.gte(this.marginRequirement);
104
+ }
105
+
106
+ meetsMarginRequirementWithBuffer(): boolean {
107
+ return this.getTotalCollateralPlusBuffer().gte(
108
+ this.marginRequirementPlusBuffer
109
+ );
110
+ }
111
+
112
+ marginShortage(): BN {
113
+ const shortage = this.marginRequirementPlusBuffer.sub(
114
+ this.getTotalCollateralPlusBuffer()
115
+ );
116
+ return shortage.isNeg() ? new BN(0) : shortage;
117
+ }
118
+ }
119
+
120
+ export class MarginCalculation {
121
+ context: MarginContext;
122
+ totalCollateral: BN;
123
+ totalCollateralBuffer: BN;
124
+ marginRequirement: BN;
125
+ marginRequirementPlusBuffer: BN;
126
+ isolatedMarginCalculations: Map<number, IsolatedMarginCalculation>;
127
+ numSpotLiabilities: number;
128
+ numPerpLiabilities: number;
129
+ allDepositOraclesValid: boolean;
130
+ allLiabilityOraclesValid: boolean;
131
+ withPerpIsolatedLiability: boolean;
132
+ withSpotIsolatedLiability: boolean;
133
+ totalSpotLiabilityValue: BN;
134
+ totalPerpLiabilityValue: BN;
135
+ trackedMarketMarginRequirement: BN;
136
+ fuelDeposits: number;
137
+ fuelBorrows: number;
138
+ fuelPositions: number;
139
+
140
+ constructor(context: MarginContext) {
141
+ this.context = context;
142
+ this.totalCollateral = new BN(0);
143
+ this.totalCollateralBuffer = new BN(0);
144
+ this.marginRequirement = new BN(0);
145
+ this.marginRequirementPlusBuffer = new BN(0);
146
+ this.isolatedMarginCalculations = new Map();
147
+ this.numSpotLiabilities = 0;
148
+ this.numPerpLiabilities = 0;
149
+ this.allDepositOraclesValid = true;
150
+ this.allLiabilityOraclesValid = true;
151
+ this.withPerpIsolatedLiability = false;
152
+ this.withSpotIsolatedLiability = false;
153
+ this.totalSpotLiabilityValue = new BN(0);
154
+ this.totalPerpLiabilityValue = new BN(0);
155
+ this.trackedMarketMarginRequirement = new BN(0);
156
+ this.fuelDeposits = 0;
157
+ this.fuelBorrows = 0;
158
+ this.fuelPositions = 0;
159
+ }
160
+
161
+ addCrossMarginTotalCollateral(delta: BN): void {
162
+ this.totalCollateral = this.totalCollateral.add(delta);
163
+ if (this.context.marginBuffer.gt(new BN(0)) && delta.isNeg()) {
164
+ this.totalCollateralBuffer = this.totalCollateralBuffer.add(
165
+ delta.mul(this.context.marginBuffer).div(MARGIN_PRECISION)
166
+ );
167
+ }
168
+ }
169
+
170
+ addCrossMarginRequirement(marginRequirement: BN, liabilityValue: BN): void {
171
+ this.marginRequirement = this.marginRequirement.add(marginRequirement);
172
+ if (this.context.marginBuffer.gt(new BN(0))) {
173
+ this.marginRequirementPlusBuffer = this.marginRequirementPlusBuffer.add(
174
+ marginRequirement.add(
175
+ liabilityValue.mul(this.context.marginBuffer).div(MARGIN_PRECISION)
176
+ )
177
+ );
178
+ }
179
+ }
180
+
181
+ addIsolatedMarginCalculation(
182
+ marketIndex: number,
183
+ depositValue: BN,
184
+ pnl: BN,
185
+ liabilityValue: BN,
186
+ marginRequirement: BN
187
+ ): void {
188
+ const totalCollateral = depositValue.add(pnl);
189
+ const totalCollateralBuffer =
190
+ this.context.marginBuffer.gt(new BN(0)) && pnl.isNeg()
191
+ ? pnl.mul(this.context.marginBuffer).div(MARGIN_PRECISION)
192
+ : new BN(0);
193
+
194
+ const marginRequirementPlusBuffer = this.context.marginBuffer.gt(new BN(0))
195
+ ? marginRequirement.add(
196
+ liabilityValue.mul(this.context.marginBuffer).div(MARGIN_PRECISION)
197
+ )
198
+ : new BN(0);
199
+
200
+ const iso = new IsolatedMarginCalculation();
201
+ iso.marginRequirement = marginRequirement;
202
+ iso.totalCollateral = totalCollateral;
203
+ iso.totalCollateralBuffer = totalCollateralBuffer;
204
+ iso.marginRequirementPlusBuffer = marginRequirementPlusBuffer;
205
+ this.isolatedMarginCalculations.set(marketIndex, iso);
206
+ }
207
+
208
+ addSpotLiability(): void {
209
+ this.numSpotLiabilities += 1;
210
+ }
211
+
212
+ addPerpLiability(): void {
213
+ this.numPerpLiabilities += 1;
214
+ }
215
+
216
+ addSpotLiabilityValue(spotLiabilityValue: BN): void {
217
+ this.totalSpotLiabilityValue =
218
+ this.totalSpotLiabilityValue.add(spotLiabilityValue);
219
+ }
220
+
221
+ addPerpLiabilityValue(perpLiabilityValue: BN): void {
222
+ this.totalPerpLiabilityValue =
223
+ this.totalPerpLiabilityValue.add(perpLiabilityValue);
224
+ }
225
+
226
+ updateAllDepositOraclesValid(valid: boolean): void {
227
+ this.allDepositOraclesValid = this.allDepositOraclesValid && valid;
228
+ }
229
+
230
+ updateAllLiabilityOraclesValid(valid: boolean): void {
231
+ this.allLiabilityOraclesValid = this.allLiabilityOraclesValid && valid;
232
+ }
233
+
234
+ updateWithSpotIsolatedLiability(isolated: boolean): void {
235
+ this.withSpotIsolatedLiability = this.withSpotIsolatedLiability || isolated;
236
+ }
237
+
238
+ updateWithPerpIsolatedLiability(isolated: boolean): void {
239
+ this.withPerpIsolatedLiability = this.withPerpIsolatedLiability || isolated;
240
+ }
241
+
242
+ validateNumSpotLiabilities(): void {
243
+ if (this.numSpotLiabilities > 0 && this.marginRequirement.eq(new BN(0))) {
244
+ throw new Error(
245
+ 'InvalidMarginRatio: num_spot_liabilities>0 but margin_requirement=0'
246
+ );
247
+ }
248
+ }
249
+
250
+ getNumOfLiabilities(): number {
251
+ return this.numSpotLiabilities + this.numPerpLiabilities;
252
+ }
253
+
254
+ getCrossTotalCollateralPlusBuffer(): BN {
255
+ return this.totalCollateral.add(this.totalCollateralBuffer);
256
+ }
257
+
258
+ meetsCrossMarginRequirement(): boolean {
259
+ return this.totalCollateral.gte(this.marginRequirement);
260
+ }
261
+
262
+ meetsCrossMarginRequirementWithBuffer(): boolean {
263
+ return this.getCrossTotalCollateralPlusBuffer().gte(
264
+ this.marginRequirementPlusBuffer
265
+ );
266
+ }
267
+
268
+ meetsMarginRequirement(): boolean {
269
+ if (!this.meetsCrossMarginRequirement()) return false;
270
+ for (const [, iso] of this.isolatedMarginCalculations) {
271
+ if (!iso.meetsMarginRequirement()) return false;
272
+ }
273
+ return true;
274
+ }
275
+
276
+ meetsMarginRequirementWithBuffer(): boolean {
277
+ if (!this.meetsCrossMarginRequirementWithBuffer()) return false;
278
+ for (const [, iso] of this.isolatedMarginCalculations) {
279
+ if (!iso.meetsMarginRequirementWithBuffer()) return false;
280
+ }
281
+ return true;
282
+ }
283
+
284
+ getCrossFreeCollateral(): BN {
285
+ const free = this.totalCollateral.sub(this.marginRequirement);
286
+ return free.isNeg() ? new BN(0) : free;
287
+ }
288
+
289
+ getIsolatedFreeCollateral(marketIndex: number): BN {
290
+ const iso = this.isolatedMarginCalculations.get(marketIndex);
291
+ if (!iso)
292
+ throw new Error('InvalidMarginCalculation: missing isolated calc');
293
+ const free = iso.totalCollateral.sub(iso.marginRequirement);
294
+ return free.isNeg() ? new BN(0) : free;
295
+ }
296
+
297
+ getIsolatedMarginCalculation(
298
+ marketIndex: number
299
+ ): IsolatedMarginCalculation | undefined {
300
+ return this.isolatedMarginCalculations.get(marketIndex);
301
+ }
302
+
303
+ hasIsolatedMarginCalculation(marketIndex: number): boolean {
304
+ return this.isolatedMarginCalculations.has(marketIndex);
305
+ }
306
+ }
@@ -165,8 +165,20 @@ export function calculateWorstCaseBaseAssetAmount(
165
165
  export function calculateWorstCasePerpLiabilityValue(
166
166
  perpPosition: PerpPosition,
167
167
  perpMarket: PerpMarketAccount,
168
- oraclePrice: BN
168
+ oraclePrice: BN,
169
+ includeOpenOrders: boolean = true
169
170
  ): { worstCaseBaseAssetAmount: BN; worstCaseLiabilityValue: BN } {
171
+ // return early if no open orders required
172
+ if (!includeOpenOrders) {
173
+ return {
174
+ worstCaseBaseAssetAmount: perpPosition.baseAssetAmount,
175
+ worstCaseLiabilityValue: calculatePerpLiabilityValue(
176
+ perpPosition.baseAssetAmount,
177
+ oraclePrice,
178
+ isVariant(perpMarket.contractType, 'prediction')
179
+ ),
180
+ };
181
+ }
170
182
  const allBids = perpPosition.baseAssetAmount.add(perpPosition.openBids);
171
183
  const allAsks = perpPosition.baseAssetAmount.add(perpPosition.openAsks);
172
184
 
@@ -14,6 +14,7 @@ import {
14
14
  PositionDirection,
15
15
  PerpPosition,
16
16
  SpotMarketAccount,
17
+ PositionFlag,
17
18
  } from '../types';
18
19
  import {
19
20
  calculateUpdatedAMM,
@@ -127,7 +128,6 @@ export function calculatePositionPNL(
127
128
 
128
129
  if (withFunding) {
129
130
  const fundingRatePnL = calculateUnsettledFundingPnl(market, perpPosition);
130
-
131
131
  pnl = pnl.add(fundingRatePnL);
132
132
  }
133
133
 
@@ -244,7 +244,17 @@ export function positionIsAvailable(position: PerpPosition): boolean {
244
244
  position.baseAssetAmount.eq(ZERO) &&
245
245
  position.openOrders === 0 &&
246
246
  position.quoteAssetAmount.eq(ZERO) &&
247
- position.lpShares.eq(ZERO)
247
+ position.lpShares.eq(ZERO) &&
248
+ position.isolatedPositionScaledBalance.eq(ZERO) &&
249
+ !positionIsBeingLiquidated(position)
250
+ );
251
+ }
252
+
253
+ export function positionIsBeingLiquidated(position: PerpPosition): boolean {
254
+ return (
255
+ (position.positionFlag &
256
+ (PositionFlag.BeingLiquidated | PositionFlag.Bankruptcy)) >
257
+ 0
248
258
  );
249
259
  }
250
260
 
@@ -33,7 +33,8 @@ export function getWorstCaseTokenAmounts(
33
33
  spotMarketAccount: SpotMarketAccount,
34
34
  strictOraclePrice: StrictOraclePrice,
35
35
  marginCategory: MarginCategory,
36
- customMarginRatio?: number
36
+ customMarginRatio?: number,
37
+ includeOpenOrders: boolean = true
37
38
  ): OrderFillSimulation {
38
39
  const tokenAmount = getSignedTokenAmount(
39
40
  getTokenAmount(
@@ -50,7 +51,10 @@ export function getWorstCaseTokenAmounts(
50
51
  strictOraclePrice
51
52
  );
52
53
 
53
- if (spotPosition.openBids.eq(ZERO) && spotPosition.openAsks.eq(ZERO)) {
54
+ if (
55
+ (spotPosition.openBids.eq(ZERO) && spotPosition.openAsks.eq(ZERO)) ||
56
+ !includeOpenOrders
57
+ ) {
54
58
  const { weight, weightedTokenValue } = calculateWeightedTokenValue(
55
59
  tokenAmount,
56
60
  tokenValue,
package/src/types.ts CHANGED
@@ -584,6 +584,10 @@ export type SpotBankruptcyRecord = {
584
584
  ifPayment: BN;
585
585
  };
586
586
 
587
+ export class LiquidationBitFlag {
588
+ static readonly IsolatedPosition = 1;
589
+ }
590
+
587
591
  export type SettlePnlRecord = {
588
592
  ts: BN;
589
593
  user: PublicKey;
@@ -1136,6 +1140,8 @@ export type PerpPosition = {
1136
1140
  lastBaseAssetAmountPerLp: BN;
1137
1141
  lastQuoteAssetAmountPerLp: BN;
1138
1142
  perLpBase: number;
1143
+ positionFlag: number;
1144
+ isolatedPositionScaledBalance: BN;
1139
1145
  };
1140
1146
 
1141
1147
  export type UserStatsAccount = {
@@ -1288,6 +1294,12 @@ export class OrderParamsBitFlag {
1288
1294
  static readonly UpdateHighLeverageMode = 2;
1289
1295
  }
1290
1296
 
1297
+ export class PositionFlag {
1298
+ static readonly IsolatedPosition = 1;
1299
+ static readonly BeingLiquidated = 2;
1300
+ static readonly Bankruptcy = 3;
1301
+ }
1302
+
1291
1303
  export type NecessaryOrderParams = {
1292
1304
  orderType: OrderType;
1293
1305
  marketIndex: number;
@@ -1299,6 +1311,10 @@ export type OptionalOrderParams = {
1299
1311
  [Property in keyof OrderParams]?: OrderParams[Property];
1300
1312
  } & NecessaryOrderParams;
1301
1313
 
1314
+ export type PerpOrderIsolatedExtras = {
1315
+ isolatedPositionDepositAmount?: BN;
1316
+ };
1317
+
1302
1318
  export type ModifyOrderParams = {
1303
1319
  [Property in keyof OrderParams]?: OrderParams[Property] | null;
1304
1320
  } & { policy?: ModifyOrderPolicy };