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

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 (58) hide show
  1. package/lib/addresses/pda.d.ts +4 -0
  2. package/lib/addresses/pda.js +27 -1
  3. package/lib/admin.d.ts +3 -0
  4. package/lib/admin.js +36 -10
  5. package/lib/clearingHouse.d.ts +11 -2
  6. package/lib/clearingHouse.js +140 -5
  7. package/lib/clearingHouseUser.d.ts +3 -1
  8. package/lib/clearingHouseUser.js +11 -9
  9. package/lib/config.js +1 -1
  10. package/lib/constants/banks.d.ts +2 -0
  11. package/lib/constants/banks.js +9 -0
  12. package/lib/constants/numericConstants.d.ts +2 -0
  13. package/lib/constants/numericConstants.js +4 -1
  14. package/lib/events/eventSubscriber.d.ts +4 -2
  15. package/lib/events/eventSubscriber.js +16 -9
  16. package/lib/events/fetchLogs.d.ts +10 -1
  17. package/lib/events/fetchLogs.js +27 -7
  18. package/lib/events/pollingLogProvider.d.ts +2 -1
  19. package/lib/events/pollingLogProvider.js +6 -2
  20. package/lib/events/sort.js +7 -10
  21. package/lib/events/types.d.ts +4 -2
  22. package/lib/events/types.js +2 -0
  23. package/lib/examples/makeTradeExample.js +13 -1
  24. package/lib/idl/clearing_house.json +1081 -173
  25. package/lib/index.d.ts +2 -0
  26. package/lib/index.js +2 -0
  27. package/lib/math/amm.d.ts +3 -1
  28. package/lib/math/amm.js +41 -3
  29. package/lib/math/insurance.d.ts +4 -0
  30. package/lib/math/insurance.js +27 -0
  31. package/lib/math/margin.d.ts +1 -1
  32. package/lib/math/margin.js +5 -7
  33. package/lib/math/position.js +1 -1
  34. package/lib/types.d.ts +79 -24
  35. package/lib/types.js +7 -4
  36. package/package.json +1 -1
  37. package/src/addresses/pda.ts +56 -0
  38. package/src/admin.ts +64 -18
  39. package/src/clearingHouse.ts +230 -10
  40. package/src/clearingHouseUser.ts +16 -11
  41. package/src/config.ts +1 -1
  42. package/src/constants/banks.ts +16 -0
  43. package/src/constants/numericConstants.ts +4 -0
  44. package/src/events/eventSubscriber.ts +20 -12
  45. package/src/events/fetchLogs.ts +35 -8
  46. package/src/events/pollingLogProvider.ts +10 -2
  47. package/src/events/sort.ts +10 -14
  48. package/src/events/types.ts +7 -1
  49. package/src/examples/makeTradeExample.ts +20 -1
  50. package/src/idl/clearing_house.json +1081 -173
  51. package/src/index.ts +2 -0
  52. package/src/math/amm.ts +67 -2
  53. package/src/math/insurance.ts +35 -0
  54. package/src/math/margin.ts +3 -10
  55. package/src/math/position.ts +2 -2
  56. package/src/types.ts +83 -24
  57. package/src/events/eventSubscriber.js +0 -139
  58. package/src/events/sort.js +0 -44
package/lib/index.d.ts CHANGED
@@ -29,6 +29,7 @@ export * from './factory/oracleClient';
29
29
  export * from './factory/bigNum';
30
30
  export * from './events/types';
31
31
  export * from './events/eventSubscriber';
32
+ export * from './events/fetchLogs';
32
33
  export * from './math/auction';
33
34
  export * from './math/conversion';
34
35
  export * from './math/funding';
@@ -40,6 +41,7 @@ export * from './math/trade';
40
41
  export * from './math/orders';
41
42
  export * from './math/repeg';
42
43
  export * from './math/margin';
44
+ export * from './math/insurance';
43
45
  export * from './orderParams';
44
46
  export * from './slot/SlotSubscriber';
45
47
  export * from './wallet';
package/lib/index.js CHANGED
@@ -52,6 +52,7 @@ __exportStar(require("./factory/oracleClient"), exports);
52
52
  __exportStar(require("./factory/bigNum"), exports);
53
53
  __exportStar(require("./events/types"), exports);
54
54
  __exportStar(require("./events/eventSubscriber"), exports);
55
+ __exportStar(require("./events/fetchLogs"), exports);
55
56
  __exportStar(require("./math/auction"), exports);
56
57
  __exportStar(require("./math/conversion"), exports);
57
58
  __exportStar(require("./math/funding"), exports);
@@ -63,6 +64,7 @@ __exportStar(require("./math/trade"), exports);
63
64
  __exportStar(require("./math/orders"), exports);
64
65
  __exportStar(require("./math/repeg"), exports);
65
66
  __exportStar(require("./math/margin"), exports);
67
+ __exportStar(require("./math/insurance"), exports);
66
68
  __exportStar(require("./orderParams"), exports);
67
69
  __exportStar(require("./slot/SlotSubscriber"), exports);
68
70
  __exportStar(require("./wallet"), exports);
package/lib/math/amm.d.ts CHANGED
@@ -33,9 +33,11 @@ export declare type AssetType = 'quote' | 'base';
33
33
  * @returns quoteAssetReserve and baseAssetReserve after swap. : Precision AMM_RESERVE_PRECISION
34
34
  */
35
35
  export declare function calculateAmmReservesAfterSwap(amm: Pick<AMM, 'pegMultiplier' | 'quoteAssetReserve' | 'sqrtK' | 'baseAssetReserve'>, inputAssetType: AssetType, swapAmount: BN, swapDirection: SwapDirection): [BN, BN];
36
+ export declare function calculateMarketOpenBidAsk(baseAssetReserve: BN, minBaseAssetReserve: BN, maxBaseAssetReserve: BN): [BN, BN];
37
+ export declare function calculateInventoryScale(netBaseAssetAmount: BN, baseAssetReserve: BN, minBaseAssetReserve: BN, maxBaseAssetReserve: BN): number;
36
38
  export declare function calculateEffectiveLeverage(baseSpread: number, quoteAssetReserve: BN, terminalQuoteAssetReserve: BN, pegMultiplier: BN, netBaseAssetAmount: BN, markPrice: BN, totalFeeMinusDistributions: BN): number;
37
39
  export declare function calculateMaxSpread(marginRatioInitial: number): number;
38
- export declare function calculateSpreadBN(baseSpread: number, lastOracleMarkSpreadPct: BN, lastOracleConfPct: BN, maxSpread: number, quoteAssetReserve: BN, terminalQuoteAssetReserve: BN, pegMultiplier: BN, netBaseAssetAmount: BN, markPrice: BN, totalFeeMinusDistributions: BN): [number, number];
40
+ export declare function calculateSpreadBN(baseSpread: number, lastOracleMarkSpreadPct: BN, lastOracleConfPct: BN, maxSpread: number, quoteAssetReserve: BN, terminalQuoteAssetReserve: BN, pegMultiplier: BN, netBaseAssetAmount: BN, markPrice: BN, totalFeeMinusDistributions: BN, baseAssetReserve: BN, minBaseAssetReserve: BN, maxBaseAssetReserve: BN): [number, number];
39
41
  export declare function calculateSpread(amm: AMM, direction: PositionDirection, oraclePriceData: OraclePriceData): number;
40
42
  export declare function calculateSpreadReserves(amm: AMM, direction: PositionDirection, oraclePriceData: OraclePriceData): {
41
43
  baseAssetReserve: 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.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;
3
+ exports.calculateMaxBaseAssetAmountFillable = exports.calculateQuoteAssetAmountSwapped = exports.calculateMaxBaseAssetAmountToTrade = exports.calculateTerminalPrice = exports.getSwapDirection = exports.calculateSwapOutput = exports.calculateSpreadReserves = exports.calculateSpread = exports.calculateSpreadBN = exports.calculateMaxSpread = exports.calculateEffectiveLeverage = exports.calculateInventoryScale = exports.calculateMarketOpenBidAsk = 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");
@@ -165,6 +165,36 @@ function calculateAmmReservesAfterSwap(amm, inputAssetType, swapAmount, swapDire
165
165
  return [newQuoteAssetReserve, newBaseAssetReserve];
166
166
  }
167
167
  exports.calculateAmmReservesAfterSwap = calculateAmmReservesAfterSwap;
168
+ function calculateMarketOpenBidAsk(baseAssetReserve, minBaseAssetReserve, maxBaseAssetReserve) {
169
+ // open orders
170
+ let openAsks;
171
+ if (maxBaseAssetReserve > baseAssetReserve) {
172
+ openAsks = maxBaseAssetReserve.sub(baseAssetReserve).mul(new anchor_1.BN(-1));
173
+ }
174
+ else {
175
+ openAsks = numericConstants_1.ZERO;
176
+ }
177
+ let openBids;
178
+ if (minBaseAssetReserve < baseAssetReserve) {
179
+ openBids = baseAssetReserve.sub(minBaseAssetReserve);
180
+ }
181
+ else {
182
+ openBids = numericConstants_1.ZERO;
183
+ }
184
+ return [openBids, openAsks];
185
+ }
186
+ exports.calculateMarketOpenBidAsk = calculateMarketOpenBidAsk;
187
+ function calculateInventoryScale(netBaseAssetAmount, baseAssetReserve, minBaseAssetReserve, maxBaseAssetReserve) {
188
+ // inventory skew
189
+ const [openBids, openAsks] = calculateMarketOpenBidAsk(baseAssetReserve, minBaseAssetReserve, maxBaseAssetReserve);
190
+ const totalLiquidity = anchor_1.BN.max(openBids.abs().add(openAsks.abs()), new anchor_1.BN(1));
191
+ const inventoryScale = anchor_1.BN.min(netBaseAssetAmount.abs(), totalLiquidity)
192
+ .mul(numericConstants_1.BID_ASK_SPREAD_PRECISION.mul(new anchor_1.BN(5)))
193
+ .div(totalLiquidity)
194
+ .toNumber() / numericConstants_1.BID_ASK_SPREAD_PRECISION.toNumber();
195
+ return inventoryScale;
196
+ }
197
+ exports.calculateInventoryScale = calculateInventoryScale;
168
198
  function calculateEffectiveLeverage(baseSpread, quoteAssetReserve, terminalQuoteAssetReserve, pegMultiplier, netBaseAssetAmount, markPrice, totalFeeMinusDistributions) {
169
199
  // inventory skew
170
200
  const netBaseAssetValue = quoteAssetReserve
@@ -187,7 +217,7 @@ function calculateMaxSpread(marginRatioInitial) {
187
217
  return maxTargetSpread;
188
218
  }
189
219
  exports.calculateMaxSpread = calculateMaxSpread;
190
- function calculateSpreadBN(baseSpread, lastOracleMarkSpreadPct, lastOracleConfPct, maxSpread, quoteAssetReserve, terminalQuoteAssetReserve, pegMultiplier, netBaseAssetAmount, markPrice, totalFeeMinusDistributions) {
220
+ function calculateSpreadBN(baseSpread, lastOracleMarkSpreadPct, lastOracleConfPct, maxSpread, quoteAssetReserve, terminalQuoteAssetReserve, pegMultiplier, netBaseAssetAmount, markPrice, totalFeeMinusDistributions, baseAssetReserve, minBaseAssetReserve, maxBaseAssetReserve) {
191
221
  let longSpread = baseSpread / 2;
192
222
  let shortSpread = baseSpread / 2;
193
223
  if (lastOracleMarkSpreadPct.gt(numericConstants_1.ZERO)) {
@@ -198,6 +228,14 @@ function calculateSpreadBN(baseSpread, lastOracleMarkSpreadPct, lastOracleConfPc
198
228
  }
199
229
  const maxTargetSpread = maxSpread;
200
230
  const MAX_INVENTORY_SKEW = 5;
231
+ const inventoryScale = calculateInventoryScale(netBaseAssetAmount, baseAssetReserve, minBaseAssetReserve, maxBaseAssetReserve);
232
+ const inventorySpreadScale = Math.min(MAX_INVENTORY_SKEW, 1 + inventoryScale);
233
+ if (netBaseAssetAmount.gt(numericConstants_1.ZERO)) {
234
+ longSpread *= inventorySpreadScale;
235
+ }
236
+ else if (netBaseAssetAmount.lt(numericConstants_1.ZERO)) {
237
+ shortSpread *= inventorySpreadScale;
238
+ }
201
239
  const effectiveLeverage = calculateEffectiveLeverage(baseSpread, quoteAssetReserve, terminalQuoteAssetReserve, pegMultiplier, netBaseAssetAmount, markPrice, totalFeeMinusDistributions);
202
240
  if (totalFeeMinusDistributions.gt(numericConstants_1.ZERO)) {
203
241
  const spreadScale = Math.min(MAX_INVENTORY_SKEW, 1 + effectiveLeverage);
@@ -240,7 +278,7 @@ function calculateSpread(amm, direction, oraclePriceData) {
240
278
  const confIntervalPct = confInterval
241
279
  .mul(numericConstants_1.BID_ASK_SPREAD_PRECISION)
242
280
  .div(markPrice);
243
- const [longSpread, shortSpread] = calculateSpreadBN(amm.baseSpread, targetMarkSpreadPct, confIntervalPct, amm.maxSpread, amm.quoteAssetReserve, amm.terminalQuoteAssetReserve, amm.pegMultiplier, amm.netBaseAssetAmount, markPrice, amm.totalFeeMinusDistributions);
281
+ const [longSpread, shortSpread] = calculateSpreadBN(amm.baseSpread, targetMarkSpreadPct, confIntervalPct, amm.maxSpread, amm.quoteAssetReserve, amm.terminalQuoteAssetReserve, amm.pegMultiplier, amm.netBaseAssetAmount, markPrice, amm.totalFeeMinusDistributions, amm.baseAssetReserve, amm.minBaseAssetReserve, amm.maxBaseAssetReserve);
244
282
  let spread;
245
283
  if ((0, types_1.isVariant)(direction, 'long')) {
246
284
  spread = longSpread;
@@ -0,0 +1,4 @@
1
+ /// <reference types="bn.js" />
2
+ import { BN } from '../index';
3
+ export declare function stakeAmountToShares(amount: BN, totalIfShares: BN, insuranceFundVaultBalance: BN): BN;
4
+ export declare function unstakeSharesToAmount(nShares: BN, totalIfShares: BN, insuranceFundVaultBalance: BN): BN;
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.unstakeSharesToAmount = exports.stakeAmountToShares = void 0;
4
+ const numericConstants_1 = require("../constants/numericConstants");
5
+ const index_1 = require("../index");
6
+ function stakeAmountToShares(amount, totalIfShares, insuranceFundVaultBalance) {
7
+ let nShares;
8
+ if (insuranceFundVaultBalance.gt(numericConstants_1.ZERO)) {
9
+ nShares = amount.mul(totalIfShares).div(insuranceFundVaultBalance);
10
+ }
11
+ else {
12
+ nShares = amount;
13
+ }
14
+ return nShares;
15
+ }
16
+ exports.stakeAmountToShares = stakeAmountToShares;
17
+ function unstakeSharesToAmount(nShares, totalIfShares, insuranceFundVaultBalance) {
18
+ let amount;
19
+ if (totalIfShares.gt(numericConstants_1.ZERO)) {
20
+ amount = index_1.BN.max(numericConstants_1.ZERO, nShares.mul(insuranceFundVaultBalance).div(totalIfShares).sub(numericConstants_1.ONE));
21
+ }
22
+ else {
23
+ amount = numericConstants_1.ZERO;
24
+ }
25
+ return amount;
26
+ }
27
+ exports.unstakeSharesToAmount = unstakeSharesToAmount;
@@ -7,5 +7,5 @@ imfFactor: BN, liabilityWeight: BN, precision: BN): BN;
7
7
  export declare function calculateSizeDiscountAssetWeight(size: BN, // AMM_RESERVE_PRECISION
8
8
  imfFactor: BN, assetWeight: BN): BN;
9
9
  export declare function calculateOraclePriceForPerpMargin(marketPosition: UserPosition, market: MarketAccount, oraclePriceData: OraclePriceData): BN;
10
- export declare function calculateMarginBaseAssetValue(market: MarketAccount, marketPosition: UserPosition, oraclePriceData: OraclePriceData): BN;
10
+ export declare function calculateBaseAssetValueWithOracle(market: MarketAccount, marketPosition: UserPosition, oraclePriceData: OraclePriceData): BN;
11
11
  export declare function calculateWorstCaseBaseAssetAmount(marketPosition: UserPosition): BN;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.calculateWorstCaseBaseAssetAmount = exports.calculateMarginBaseAssetValue = exports.calculateOraclePriceForPerpMargin = exports.calculateSizeDiscountAssetWeight = exports.calculateSizePremiumLiabilityWeight = void 0;
3
+ 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("@project-serum/anchor");
@@ -50,15 +50,13 @@ function calculateOraclePriceForPerpMargin(marketPosition, market, oraclePriceDa
50
50
  return marginPrice;
51
51
  }
52
52
  exports.calculateOraclePriceForPerpMargin = calculateOraclePriceForPerpMargin;
53
- function calculateMarginBaseAssetValue(market, marketPosition, oraclePriceData) {
54
- const marginPrice = calculateOraclePriceForPerpMargin(marketPosition, market, oraclePriceData);
55
- const baseAssetValue = marketPosition.baseAssetAmount
53
+ function calculateBaseAssetValueWithOracle(market, marketPosition, oraclePriceData) {
54
+ return marketPosition.baseAssetAmount
56
55
  .abs()
57
- .mul(marginPrice)
56
+ .mul(oraclePriceData.price)
58
57
  .div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO.mul(numericConstants_1.MARK_PRICE_PRECISION));
59
- return baseAssetValue;
60
58
  }
61
- exports.calculateMarginBaseAssetValue = calculateMarginBaseAssetValue;
59
+ exports.calculateBaseAssetValueWithOracle = calculateBaseAssetValueWithOracle;
62
60
  function calculateWorstCaseBaseAssetAmount(marketPosition) {
63
61
  const allBids = marketPosition.baseAssetAmount.add(marketPosition.openBids);
64
62
  const allAsks = marketPosition.baseAssetAmount.add(marketPosition.openAsks);
@@ -61,7 +61,7 @@ function calculatePositionPNL(market, marketPosition, withFunding = false, oracl
61
61
  if (marketPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
62
62
  return marketPosition.quoteAssetAmount;
63
63
  }
64
- const baseAssetValue = (0, margin_1.calculateMarginBaseAssetValue)(market, marketPosition, oraclePriceData);
64
+ const baseAssetValue = (0, margin_1.calculateBaseAssetValueWithOracle)(market, marketPosition, oraclePriceData);
65
65
  const baseAssetValueSign = marketPosition.baseAssetAmount.isNeg()
66
66
  ? new __1.BN(-1)
67
67
  : new __1.BN(1);
package/lib/types.d.ts CHANGED
@@ -104,9 +104,6 @@ export declare class OrderActionExplanation {
104
104
  static readonly NONE: {
105
105
  none: {};
106
106
  };
107
- static readonly BREACHED_MARGIN_REQUIREMENT: {
108
- breachedMarginRequirement: {};
109
- };
110
107
  static readonly ORACLE_PRICE_BREACHED_LIMIT_PRICE: {
111
108
  oraclePriceBreachedLimitPrice: {};
112
109
  };
@@ -178,15 +175,41 @@ export declare type CurveRecord = {
178
175
  oraclePrice: BN;
179
176
  tradeId: BN;
180
177
  };
178
+ export declare type LPRecord = {
179
+ ts: BN;
180
+ user: PublicKey;
181
+ action: LPAction;
182
+ nShares: BN;
183
+ marketIndex: BN;
184
+ deltaBaseAssetAmount: BN;
185
+ deltaQuoteAssetAmount: BN;
186
+ pnl: BN;
187
+ };
188
+ export declare class LPAction {
189
+ static readonly ADD_LIQUIDITY: {
190
+ addLiquidity: {};
191
+ };
192
+ static readonly REMOVE_LIQUIDITY: {
193
+ removeLiquidity: {};
194
+ };
195
+ static readonly SETTLE_LIQUIDITY: {
196
+ settleLiquidity: {};
197
+ };
198
+ }
181
199
  export declare type FundingRateRecord = {
182
200
  ts: BN;
183
201
  recordId: BN;
184
202
  marketIndex: BN;
185
203
  fundingRate: BN;
204
+ fundingRateLong: BN;
205
+ fundingRateShort: BN;
186
206
  cumulativeFundingRateLong: BN;
187
207
  cumulativeFundingRateShort: BN;
188
208
  oraclePriceTwap: BN;
189
209
  markPriceTwap: BN;
210
+ periodRevenue: BN;
211
+ netBaseAssetAmount: BN;
212
+ netUnsettledLpBaseAssetAmount: BN;
190
213
  };
191
214
  export declare type FundingPaymentRecord = {
192
215
  ts: BN;
@@ -241,6 +264,7 @@ export declare type LiquidatePerpRecord = {
241
264
  oraclePrice: BN;
242
265
  baseAssetAmount: BN;
243
266
  quoteAssetAmount: BN;
267
+ lpShares: BN;
244
268
  userPnl: BN;
245
269
  liquidatorPnl: BN;
246
270
  canceledOrdersFee: BN;
@@ -294,27 +318,40 @@ export declare type SettlePnlRecord = {
294
318
  };
295
319
  export declare type OrderRecord = {
296
320
  ts: BN;
297
- taker: PublicKey;
298
- maker: PublicKey;
299
- takerOrder: Order;
300
- makerOrder: Order;
301
- takerPnl: BN;
302
- makerPnl: BN;
321
+ user: PublicKey;
322
+ order: Order;
323
+ };
324
+ export declare type OrderActionRecord = {
325
+ ts: BN;
303
326
  action: OrderAction;
304
327
  actionExplanation: OrderActionExplanation;
305
- filler: PublicKey;
306
- fillRecordId: BN;
307
328
  marketIndex: BN;
308
- baseAssetAmountFilled: BN;
309
- quoteAssetAmountFilled: BN;
310
- makerRebate: BN;
311
- takerFee: BN;
312
- fillerReward: BN;
313
- quoteAssetAmountSurplus: BN;
329
+ filler: PublicKey | null;
330
+ fillerReward: BN | null;
331
+ fillRecordId: BN | null;
332
+ referrer: PublicKey | null;
333
+ baseAssetAmountFilled: BN | null;
334
+ quoteAssetAmountFilled: BN | null;
335
+ takerPnl: BN | null;
336
+ makerPnl: BN | null;
337
+ takerFee: BN | null;
338
+ makerRebate: BN | null;
339
+ referrerReward: BN | null;
340
+ refereeDiscount: BN | null;
341
+ quoteAssetAmountSurplus: BN | null;
342
+ taker: PublicKey | null;
343
+ takerOrderId: BN | null;
344
+ takerOrderBaseAssetAmount: BN | null;
345
+ takerOrderBaseAssetAmountFilled: BN | null;
346
+ takerOrderQuoteAssetAmountFilled: BN | null;
347
+ takerOrderFee: BN | null;
348
+ maker: PublicKey | null;
349
+ makerOrderId: BN | null;
350
+ makerOrderBaseAssetAmount: BN | null;
351
+ makerOrderBaseAssetAmountFilled: BN | null;
352
+ makerOrderQuoteAssetAmountFilled: BN | null;
353
+ makerOrderFee: BN | null;
314
354
  oraclePrice: BN;
315
- referrer: PublicKey;
316
- referrerReward: BN;
317
- refereeDiscount: BN;
318
355
  };
319
356
  export declare type StateAccount = {
320
357
  admin: PublicKey;
@@ -322,8 +359,6 @@ export declare type StateAccount = {
322
359
  exchangePaused: boolean;
323
360
  adminControlsPrices: boolean;
324
361
  insuranceVault: PublicKey;
325
- insuranceVaultAuthority: PublicKey;
326
- insuranceVaultNonce: number;
327
362
  marginRatioInitial: BN;
328
363
  marginRatioMaintenance: BN;
329
364
  marginRatioPartial: BN;
@@ -345,6 +380,8 @@ export declare type StateAccount = {
345
380
  numberOfMarkets: BN;
346
381
  numberOfBanks: BN;
347
382
  minOrderQuoteAssetAmount: BN;
383
+ signer: PublicKey;
384
+ signerNonce: number;
348
385
  maxAuctionDuration: number;
349
386
  minAuctionDuration: number;
350
387
  };
@@ -372,8 +409,14 @@ export declare type BankAccount = {
372
409
  pubkey: PublicKey;
373
410
  mint: PublicKey;
374
411
  vault: PublicKey;
375
- vaultAuthority: PublicKey;
376
- vaultAuthorityNonce: number;
412
+ insuranceFundVault: PublicKey;
413
+ insuranceWithdrawEscrowPeriod: BN;
414
+ revenuePool: PoolBalance;
415
+ totalIfShares: BN;
416
+ userIfShares: BN;
417
+ userIfFactor: BN;
418
+ totalIfFactor: BN;
419
+ liquidationIfFactor: BN;
377
420
  decimals: number;
378
421
  optimalUtilization: BN;
379
422
  optimalBorrowRate: BN;
@@ -430,6 +473,7 @@ export declare type AMM = {
430
473
  cumulativeFeePerLp: BN;
431
474
  cumulativeNetBaseAssetAmountPerLp: BN;
432
475
  userLpShares: BN;
476
+ netUnsettledLpBaseAssetAmount: BN;
433
477
  minimumQuoteAssetTradeSize: BN;
434
478
  baseAssetAmountStepSize: BN;
435
479
  maxBaseAssetAmountRatio: number;
@@ -453,6 +497,7 @@ export declare type AMM = {
453
497
  maxSpread: number;
454
498
  marketPosition: UserPosition;
455
499
  marketPositionPerLp: UserPosition;
500
+ ammJitIntensity: number;
456
501
  maxBaseAssetReserve: BN;
457
502
  minBaseAssetReserve: BN;
458
503
  };
@@ -489,6 +534,7 @@ export declare type UserStatsAccount = {
489
534
  isReferrer: boolean;
490
535
  totalReferrerReward: BN;
491
536
  authority: PublicKey;
537
+ quoteAssetInsuranceFundStake: BN;
492
538
  };
493
539
  export declare type UserAccount = {
494
540
  authority: PublicKey;
@@ -665,3 +711,12 @@ export declare type OrderFillerRewardStructure = {
665
711
  timeBasedRewardLowerBound: BN;
666
712
  };
667
713
  export declare type MarginCategory = 'Initial' | 'Maintenance';
714
+ export declare type InsuranceFundStake = {
715
+ bankIndex: BN;
716
+ authority: PublicKey;
717
+ ifShares: BN;
718
+ ifBase: BN;
719
+ lastWithdrawRequestShares: BN;
720
+ lastWithdrawRequestValue: BN;
721
+ lastWithdrawRequestTs: BN;
722
+ };
package/lib/types.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DefaultOrderParams = exports.LiquidationType = exports.TradeSide = exports.isOneOfVariant = exports.isVariant = exports.OrderTriggerCondition = exports.OrderActionExplanation = exports.OrderAction = exports.OrderDiscountTier = exports.OrderStatus = exports.OrderType = exports.OracleSource = exports.DepositDirection = exports.PositionDirection = exports.BankBalanceType = exports.SwapDirection = void 0;
3
+ exports.DefaultOrderParams = exports.LiquidationType = exports.LPAction = exports.TradeSide = exports.isOneOfVariant = exports.isVariant = exports.OrderTriggerCondition = exports.OrderActionExplanation = exports.OrderAction = exports.OrderDiscountTier = exports.OrderStatus = exports.OrderType = exports.OracleSource = exports.DepositDirection = exports.PositionDirection = exports.BankBalanceType = exports.SwapDirection = void 0;
4
4
  const _1 = require(".");
5
5
  // # Utility Types / Enums / Constants
6
6
  class SwapDirection {
@@ -61,9 +61,6 @@ class OrderActionExplanation {
61
61
  }
62
62
  exports.OrderActionExplanation = OrderActionExplanation;
63
63
  OrderActionExplanation.NONE = { none: {} };
64
- OrderActionExplanation.BREACHED_MARGIN_REQUIREMENT = {
65
- breachedMarginRequirement: {},
66
- };
67
64
  OrderActionExplanation.ORACLE_PRICE_BREACHED_LIMIT_PRICE = {
68
65
  oraclePriceBreachedLimitPrice: {},
69
66
  };
@@ -97,6 +94,12 @@ var TradeSide;
97
94
  TradeSide[TradeSide["Buy"] = 1] = "Buy";
98
95
  TradeSide[TradeSide["Sell"] = 2] = "Sell";
99
96
  })(TradeSide = exports.TradeSide || (exports.TradeSide = {}));
97
+ class LPAction {
98
+ }
99
+ exports.LPAction = LPAction;
100
+ LPAction.ADD_LIQUIDITY = { addLiquidity: {} };
101
+ LPAction.REMOVE_LIQUIDITY = { removeLiquidity: {} };
102
+ LPAction.SETTLE_LIQUIDITY = { settleLiquidity: {} };
100
103
  class LiquidationType {
101
104
  }
102
105
  exports.LiquidationType = LiquidationType;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@drift-labs/sdk",
3
- "version": "0.2.0-master.22",
3
+ "version": "0.2.0-master.25",
4
4
  "main": "lib/index.js",
5
5
  "types": "lib/index.d.ts",
6
6
  "author": "crispheaney",
@@ -129,3 +129,59 @@ export async function getBankVaultAuthorityPublicKey(
129
129
  )
130
130
  )[0];
131
131
  }
132
+
133
+ export async function getInsuranceFundVaultPublicKey(
134
+ programId: PublicKey,
135
+ bankIndex: BN
136
+ ): Promise<PublicKey> {
137
+ return (
138
+ await anchor.web3.PublicKey.findProgramAddress(
139
+ [
140
+ Buffer.from(anchor.utils.bytes.utf8.encode('insurance_fund_vault')),
141
+ bankIndex.toArrayLike(Buffer, 'le', 8),
142
+ ],
143
+ programId
144
+ )
145
+ )[0];
146
+ }
147
+
148
+ export async function getInsuranceFundVaultAuthorityPublicKey(
149
+ programId: PublicKey,
150
+ bankIndex: BN
151
+ ): Promise<PublicKey> {
152
+ return (
153
+ await anchor.web3.PublicKey.findProgramAddress(
154
+ [
155
+ Buffer.from(
156
+ anchor.utils.bytes.utf8.encode('insurance_fund_vault_authority')
157
+ ),
158
+ bankIndex.toArrayLike(Buffer, 'le', 8),
159
+ ],
160
+ programId
161
+ )
162
+ )[0];
163
+ }
164
+
165
+ export function getInsuranceFundStakeAccountPublicKey(
166
+ programId: PublicKey,
167
+ authority: PublicKey,
168
+ bankIndex: BN
169
+ ): PublicKey {
170
+ return anchor.web3.PublicKey.findProgramAddressSync(
171
+ [
172
+ Buffer.from(anchor.utils.bytes.utf8.encode('insurance_fund_stake')),
173
+ authority.toBuffer(),
174
+ bankIndex.toArrayLike(Buffer, 'le', 8),
175
+ ],
176
+ programId
177
+ )[0];
178
+ }
179
+
180
+ export function getClearingHouseSignerPublicKey(
181
+ programId: PublicKey
182
+ ): PublicKey {
183
+ return anchor.web3.PublicKey.findProgramAddressSync(
184
+ [Buffer.from(anchor.utils.bytes.utf8.encode('clearing_house_signer'))],
185
+ programId
186
+ )[0];
187
+ }
package/src/admin.ts CHANGED
@@ -13,10 +13,10 @@ import { BN } from '@project-serum/anchor';
13
13
  import * as anchor from '@project-serum/anchor';
14
14
  import {
15
15
  getClearingHouseStateAccountPublicKeyAndNonce,
16
- getBankVaultAuthorityPublicKey,
17
16
  getBankPublicKey,
18
17
  getBankVaultPublicKey,
19
18
  getMarketPublicKey,
19
+ getInsuranceFundVaultPublicKey,
20
20
  } from './addresses/pda';
21
21
  import { TOKEN_PROGRAM_ID } from '@solana/spl-token';
22
22
  import { ClearingHouse } from './clearingHouse';
@@ -36,20 +36,16 @@ export class Admin extends ClearingHouse {
36
36
  throw new Error('Clearing house already initialized');
37
37
  }
38
38
 
39
+ const [clearingHouseStatePublicKey] =
40
+ await getClearingHouseStateAccountPublicKeyAndNonce(
41
+ this.program.programId
42
+ );
43
+
39
44
  const [insuranceVaultPublicKey] = await PublicKey.findProgramAddress(
40
45
  [Buffer.from(anchor.utils.bytes.utf8.encode('insurance_vault'))],
41
46
  this.program.programId
42
47
  );
43
48
 
44
- const [insuranceVaultAuthority] = await PublicKey.findProgramAddress(
45
- [insuranceVaultPublicKey.toBuffer()],
46
- this.program.programId
47
- );
48
-
49
- const [clearingHouseStatePublicKey] =
50
- await getClearingHouseStateAccountPublicKeyAndNonce(
51
- this.program.programId
52
- );
53
49
  const initializeTx = await this.program.transaction.initialize(
54
50
  adminControlsPrices,
55
51
  {
@@ -57,9 +53,9 @@ export class Admin extends ClearingHouse {
57
53
  admin: this.wallet.publicKey,
58
54
  state: clearingHouseStatePublicKey,
59
55
  quoteAssetMint: usdcMint,
60
- insuranceVault: insuranceVaultPublicKey,
61
- insuranceVaultAuthority: insuranceVaultAuthority,
62
56
  rent: SYSVAR_RENT_PUBKEY,
57
+ insuranceVault: insuranceVaultPublicKey,
58
+ clearingHouseSigner: this.getSignerPublicKey(),
63
59
  systemProgram: anchor.web3.SystemProgram.programId,
64
60
  tokenProgram: TOKEN_PROGRAM_ID,
65
61
  },
@@ -97,7 +93,7 @@ export class Admin extends ClearingHouse {
97
93
  bankIndex
98
94
  );
99
95
 
100
- const bankVaultAuthority = await getBankVaultAuthorityPublicKey(
96
+ const insuranceFundVault = await getInsuranceFundVaultPublicKey(
101
97
  this.program.programId,
102
98
  bankIndex
103
99
  );
@@ -119,7 +115,8 @@ export class Admin extends ClearingHouse {
119
115
  state: await this.getStatePublicKey(),
120
116
  bank,
121
117
  bankVault,
122
- bankVaultAuthority,
118
+ insuranceFundVault,
119
+ clearingHouseSigner: this.getSignerPublicKey(),
123
120
  bankMint: mint,
124
121
  oracle,
125
122
  rent: SYSVAR_RENT_PUBKEY,
@@ -340,7 +337,7 @@ export class Admin extends ClearingHouse {
340
337
  state: await this.getStatePublicKey(),
341
338
  bank: bank.pubkey,
342
339
  insuranceVault: state.insuranceVault,
343
- insuranceVaultAuthority: state.insuranceVaultAuthority,
340
+ clearingHouseSigner: this.getSignerPublicKey(),
344
341
  recipient: recipient,
345
342
  tokenProgram: TOKEN_PROGRAM_ID,
346
343
  },
@@ -364,7 +361,7 @@ export class Admin extends ClearingHouse {
364
361
  market: marketPublicKey,
365
362
  bank: bank.pubkey,
366
363
  bankVault: bank.vault,
367
- bankVaultAuthority: bank.vaultAuthority,
364
+ clearingHouseSigner: this.getSignerPublicKey(),
368
365
  recipient: recipient,
369
366
  tokenProgram: TOKEN_PROGRAM_ID,
370
367
  },
@@ -384,10 +381,9 @@ export class Admin extends ClearingHouse {
384
381
  state: await this.getStatePublicKey(),
385
382
  market: await getMarketPublicKey(this.program.programId, marketIndex),
386
383
  insuranceVault: state.insuranceVault,
387
- insuranceVaultAuthority: state.insuranceVaultAuthority,
384
+ clearingHouseSigner: this.getSignerPublicKey(),
388
385
  bank: bank.pubkey,
389
386
  bankVault: bank.vault,
390
- bankVaultAuthority: bank.vaultAuthority,
391
387
  tokenProgram: TOKEN_PROGRAM_ID,
392
388
  },
393
389
  });
@@ -452,6 +448,19 @@ export class Admin extends ClearingHouse {
452
448
  });
453
449
  }
454
450
 
451
+ public async updateAmmJitIntensity(
452
+ marketIndex: BN,
453
+ ammJitIntensity: number
454
+ ): Promise<TransactionSignature> {
455
+ return await this.program.rpc.updateAmmJitIntensity(ammJitIntensity, {
456
+ accounts: {
457
+ admin: this.wallet.publicKey,
458
+ state: await this.getStatePublicKey(),
459
+ market: await getMarketPublicKey(this.program.programId, marketIndex),
460
+ },
461
+ });
462
+ }
463
+
455
464
  public async updateMarketMaxSpread(
456
465
  marketIndex: BN,
457
466
  maxSpread: number
@@ -591,6 +600,43 @@ export class Admin extends ClearingHouse {
591
600
  );
592
601
  }
593
602
 
603
+ public async updateBankIfFactor(
604
+ bankIndex: BN,
605
+ userIfFactor: BN,
606
+ totalIfFactor: BN,
607
+ liquidationIfFactor: BN
608
+ ): Promise<TransactionSignature> {
609
+ return await this.program.rpc.updateBankIfFactor(
610
+ bankIndex,
611
+ userIfFactor,
612
+ totalIfFactor,
613
+ liquidationIfFactor,
614
+ {
615
+ accounts: {
616
+ admin: this.wallet.publicKey,
617
+ state: await this.getStatePublicKey(),
618
+ bank: await getBankPublicKey(this.program.programId, bankIndex),
619
+ },
620
+ }
621
+ );
622
+ }
623
+
624
+ public async updateBankInsuranceWithdrawEscrowPeriod(
625
+ bankIndex: BN,
626
+ insuranceWithdrawEscrowPeriod: BN
627
+ ): Promise<TransactionSignature> {
628
+ return await this.program.rpc.updateBankInsuranceWithdrawEscrowPeriod(
629
+ insuranceWithdrawEscrowPeriod,
630
+ {
631
+ accounts: {
632
+ admin: this.wallet.publicKey,
633
+ state: await this.getStatePublicKey(),
634
+ bank: await getBankPublicKey(this.program.programId, bankIndex),
635
+ },
636
+ }
637
+ );
638
+ }
639
+
594
640
  public async updateLpCooldownTime(
595
641
  marketIndex: BN,
596
642
  cooldownTime: BN