@drift-labs/sdk 0.2.0-master.10 → 0.2.0-master.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 (82) hide show
  1. package/lib/admin.d.ts +3 -3
  2. package/lib/admin.js +6 -6
  3. package/lib/clearingHouse.d.ts +22 -6
  4. package/lib/clearingHouse.js +357 -74
  5. package/lib/clearingHouseUser.d.ts +12 -17
  6. package/lib/clearingHouseUser.js +97 -88
  7. package/lib/config.js +1 -1
  8. package/lib/constants/banks.d.ts +2 -2
  9. package/lib/constants/banks.js +5 -4
  10. package/lib/constants/numericConstants.d.ts +3 -0
  11. package/lib/constants/numericConstants.js +4 -1
  12. package/lib/events/eventList.js +3 -0
  13. package/lib/events/types.d.ts +2 -1
  14. package/lib/factory/bigNum.d.ts +1 -0
  15. package/lib/factory/bigNum.js +37 -11
  16. package/lib/idl/clearing_house.json +611 -146
  17. package/lib/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  18. package/lib/index.d.ts +2 -1
  19. package/lib/index.js +2 -1
  20. package/lib/math/amm.js +2 -2
  21. package/lib/math/bankBalance.d.ts +3 -1
  22. package/lib/math/bankBalance.js +54 -1
  23. package/lib/math/margin.d.ts +11 -0
  24. package/lib/math/margin.js +72 -0
  25. package/lib/math/market.d.ts +4 -1
  26. package/lib/math/market.js +35 -1
  27. package/lib/math/position.d.ts +8 -0
  28. package/lib/math/position.js +42 -12
  29. package/lib/orders.d.ts +1 -2
  30. package/lib/orders.js +2 -77
  31. package/lib/{mockUSDCFaucet.d.ts → tokenFaucet.d.ts} +8 -5
  32. package/lib/{mockUSDCFaucet.js → tokenFaucet.js} +63 -51
  33. package/lib/tx/retryTxSender.js +9 -2
  34. package/lib/types.d.ts +86 -16
  35. package/lib/types.js +18 -1
  36. package/lib/util/computeUnits.js +1 -1
  37. package/lib/util/getTokenAddress.d.ts +2 -0
  38. package/lib/util/getTokenAddress.js +9 -0
  39. package/package.json +1 -1
  40. package/src/admin.ts +7 -7
  41. package/src/clearingHouse.ts +636 -94
  42. package/src/clearingHouseConfig.js +2 -0
  43. package/src/clearingHouseUser.ts +219 -121
  44. package/src/clearingHouseUserConfig.js +2 -0
  45. package/src/config.ts +1 -1
  46. package/src/constants/banks.js +42 -0
  47. package/src/constants/banks.ts +7 -4
  48. package/src/constants/markets.js +42 -0
  49. package/src/constants/numericConstants.js +41 -0
  50. package/src/constants/numericConstants.ts +4 -0
  51. package/src/events/eventList.ts +3 -0
  52. package/src/events/types.ts +2 -0
  53. package/src/factory/bigNum.js +37 -11
  54. package/src/factory/bigNum.ts +43 -13
  55. package/src/idl/clearing_house.json +611 -146
  56. package/src/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  57. package/src/index.js +1 -1
  58. package/src/index.ts +2 -1
  59. package/src/math/amm.ts +8 -5
  60. package/src/math/bankBalance.ts +98 -1
  61. package/src/math/margin.ts +124 -0
  62. package/src/math/market.ts +66 -1
  63. package/src/math/position.ts +59 -9
  64. package/src/mockUSDCFaucet.js +276 -167
  65. package/src/orders.ts +4 -157
  66. package/src/tokenFaucet.js +189 -0
  67. package/src/{mockUSDCFaucet.ts → tokenFaucet.ts} +82 -70
  68. package/src/tx/retryTxSender.ts +11 -3
  69. package/src/types.js +12 -1
  70. package/src/types.ts +88 -16
  71. package/src/{accounts/fetch.js → util/computeUnits.js} +11 -13
  72. package/src/util/computeUnits.ts +1 -1
  73. package/src/util/getTokenAddress.js +9 -0
  74. package/src/util/getTokenAddress.ts +18 -0
  75. package/tests/bn/test.ts +2 -0
  76. package/src/addresses/pda.js +0 -104
  77. package/src/math/bankBalance.js +0 -75
  78. package/src/math/market.js +0 -57
  79. package/src/math/orders.js +0 -110
  80. package/src/math/position.js +0 -140
  81. package/src/orders.js +0 -134
  82. package/src/tx/retryTxSender.js +0 -188
@@ -5,22 +5,25 @@ import { AccountInfo } from '@solana/spl-token';
5
5
  import { ConfirmOptions, Connection, PublicKey, TransactionInstruction, TransactionSignature } from '@solana/web3.js';
6
6
  import { BN } from '.';
7
7
  import { IWallet } from './types';
8
- export declare class MockUSDCFaucet {
8
+ export declare class TokenFaucet {
9
9
  connection: Connection;
10
10
  wallet: IWallet;
11
11
  program: Program;
12
12
  provider: AnchorProvider;
13
+ mint: PublicKey;
13
14
  opts?: ConfirmOptions;
14
- constructor(connection: Connection, wallet: IWallet, programId: PublicKey, opts?: ConfirmOptions);
15
- getMockUSDCFaucetStatePublicKeyAndNonce(): Promise<[
15
+ constructor(connection: Connection, wallet: IWallet, programId: PublicKey, mint: PublicKey, opts?: ConfirmOptions);
16
+ getFaucetConfigPublicKeyAndNonce(): Promise<[
16
17
  PublicKey,
17
18
  number
18
19
  ]>;
19
- mockUSDCFaucetStatePublicKey?: PublicKey;
20
- getMockUSDCFaucetStatePublicKey(): Promise<PublicKey>;
20
+ getMintAuthority(): Promise<PublicKey>;
21
+ getFaucetConfigPublicKey(): Promise<PublicKey>;
21
22
  initialize(): Promise<TransactionSignature>;
22
23
  fetchState(): Promise<any>;
24
+ private mintToUserIx;
23
25
  mintToUser(userTokenAccount: PublicKey, amount: BN): Promise<TransactionSignature>;
26
+ transferMintAuthority(): Promise<TransactionSignature>;
24
27
  createAssociatedTokenAccountAndMintTo(userPublicKey: PublicKey, amount: BN): Promise<[PublicKey, TransactionSignature]>;
25
28
  createAssociatedTokenAccountAndMintToInstructions(userPublicKey: PublicKey, amount: BN): Promise<[PublicKey, TransactionInstruction, TransactionInstruction]>;
26
29
  getAssosciatedMockUSDMintAddress(props: {
@@ -26,77 +26,97 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
26
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
27
27
  };
28
28
  Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.MockUSDCFaucet = void 0;
29
+ exports.TokenFaucet = void 0;
30
30
  const anchor = __importStar(require("@project-serum/anchor"));
31
31
  const anchor_1 = require("@project-serum/anchor");
32
32
  const spl_token_1 = require("@solana/spl-token");
33
33
  const web3_js_1 = require("@solana/web3.js");
34
- const mock_usdc_faucet_json_1 = __importDefault(require("./idl/mock_usdc_faucet.json"));
35
- class MockUSDCFaucet {
36
- constructor(connection, wallet, programId, opts) {
34
+ const token_faucet_json_1 = __importDefault(require("./idl/token_faucet.json"));
35
+ class TokenFaucet {
36
+ constructor(connection, wallet, programId, mint, opts) {
37
37
  this.connection = connection;
38
38
  this.wallet = wallet;
39
39
  this.opts = opts || anchor_1.AnchorProvider.defaultOptions();
40
40
  const provider = new anchor_1.AnchorProvider(connection, wallet, this.opts);
41
41
  this.provider = provider;
42
- this.program = new anchor_1.Program(mock_usdc_faucet_json_1.default, programId, provider);
42
+ this.program = new anchor_1.Program(token_faucet_json_1.default, programId, provider);
43
+ this.mint = mint;
43
44
  }
44
- async getMockUSDCFaucetStatePublicKeyAndNonce() {
45
- return anchor.web3.PublicKey.findProgramAddress([Buffer.from(anchor.utils.bytes.utf8.encode('mock_usdc_faucet'))], this.program.programId);
45
+ async getFaucetConfigPublicKeyAndNonce() {
46
+ return anchor.web3.PublicKey.findProgramAddress([
47
+ Buffer.from(anchor.utils.bytes.utf8.encode('faucet_config')),
48
+ this.mint.toBuffer(),
49
+ ], this.program.programId);
46
50
  }
47
- async getMockUSDCFaucetStatePublicKey() {
48
- if (this.mockUSDCFaucetStatePublicKey) {
49
- return this.mockUSDCFaucetStatePublicKey;
50
- }
51
- this.mockUSDCFaucetStatePublicKey = (await this.getMockUSDCFaucetStatePublicKeyAndNonce())[0];
52
- return this.mockUSDCFaucetStatePublicKey;
51
+ async getMintAuthority() {
52
+ return (await anchor.web3.PublicKey.findProgramAddress([
53
+ Buffer.from(anchor.utils.bytes.utf8.encode('mint_authority')),
54
+ this.mint.toBuffer(),
55
+ ], this.program.programId))[0];
56
+ }
57
+ async getFaucetConfigPublicKey() {
58
+ return (await this.getFaucetConfigPublicKeyAndNonce())[0];
53
59
  }
54
60
  async initialize() {
55
- const stateAccountRPCResponse = await this.connection.getParsedAccountInfo(await this.getMockUSDCFaucetStatePublicKey());
56
- if (stateAccountRPCResponse.value !== null) {
57
- throw new Error('Faucet already initialized');
58
- }
59
- const fakeUSDCMint = anchor.web3.Keypair.generate();
60
- const createUSDCMintAccountIx = web3_js_1.SystemProgram.createAccount({
61
- fromPubkey: this.wallet.publicKey,
62
- newAccountPubkey: fakeUSDCMint.publicKey,
63
- lamports: await spl_token_1.Token.getMinBalanceRentForExemptMint(this.connection),
64
- space: spl_token_1.MintLayout.span,
65
- programId: spl_token_1.TOKEN_PROGRAM_ID,
66
- });
67
- const [mintAuthority, _mintAuthorityNonce] = await web3_js_1.PublicKey.findProgramAddress([fakeUSDCMint.publicKey.toBuffer()], this.program.programId);
68
- const initUSDCMintIx = spl_token_1.Token.createInitMintInstruction(spl_token_1.TOKEN_PROGRAM_ID, fakeUSDCMint.publicKey, 6, mintAuthority, null);
69
- const [mockUSDCFaucetStatePublicKey, mockUSDCFaucetStateNonce] = await this.getMockUSDCFaucetStatePublicKeyAndNonce();
70
- return await this.program.rpc.initialize(mockUSDCFaucetStateNonce, {
61
+ const [faucetConfigPublicKey] = await this.getFaucetConfigPublicKeyAndNonce();
62
+ return await this.program.rpc.initialize({
71
63
  accounts: {
72
- mockUsdcFaucetState: mockUSDCFaucetStatePublicKey,
64
+ faucetConfig: faucetConfigPublicKey,
73
65
  admin: this.wallet.publicKey,
74
- mintAccount: fakeUSDCMint.publicKey,
66
+ mintAccount: this.mint,
75
67
  rent: web3_js_1.SYSVAR_RENT_PUBKEY,
76
68
  systemProgram: anchor.web3.SystemProgram.programId,
69
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
77
70
  },
78
- instructions: [createUSDCMintAccountIx, initUSDCMintIx],
79
- signers: [fakeUSDCMint],
80
71
  });
81
72
  }
82
73
  async fetchState() {
83
- return await this.program.account.mockUsdcFaucetState.fetch(await this.getMockUSDCFaucetStatePublicKey());
74
+ return await this.program.account.faucetConfig.fetch(await this.getFaucetConfigPublicKey());
84
75
  }
85
- async mintToUser(userTokenAccount, amount) {
86
- const state = await this.fetchState();
87
- return await this.program.rpc.mintToUser(amount, {
76
+ async mintToUserIx(userTokenAccount, amount) {
77
+ return this.program.instruction.mintToUser(amount, {
88
78
  accounts: {
89
- mockUsdcFaucetState: await this.getMockUSDCFaucetStatePublicKey(),
90
- mintAccount: state.mint,
79
+ faucetConfig: await this.getFaucetConfigPublicKey(),
80
+ mintAccount: this.mint,
91
81
  userTokenAccount,
92
- mintAuthority: state.mintAuthority,
82
+ mintAuthority: await this.getMintAuthority(),
83
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
84
+ },
85
+ });
86
+ }
87
+ async mintToUser(userTokenAccount, amount) {
88
+ const mintIx = await this.mintToUserIx(userTokenAccount, amount);
89
+ const tx = new web3_js_1.Transaction().add(mintIx);
90
+ const txSig = await this.program.provider.sendAndConfirm(tx, [], this.opts);
91
+ return txSig;
92
+ }
93
+ async transferMintAuthority() {
94
+ return await this.program.rpc.transferMintAuthority({
95
+ accounts: {
96
+ faucetConfig: await this.getFaucetConfigPublicKey(),
97
+ mintAccount: this.mint,
98
+ mintAuthority: await this.getMintAuthority(),
93
99
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
100
+ admin: this.wallet.publicKey,
94
101
  },
95
102
  });
96
103
  }
97
104
  async createAssociatedTokenAccountAndMintTo(userPublicKey, amount) {
105
+ const tx = new web3_js_1.Transaction();
98
106
  const [associatedTokenPublicKey, createAssociatedAccountIx, mintToTx] = await this.createAssociatedTokenAccountAndMintToInstructions(userPublicKey, amount);
99
- const tx = new web3_js_1.Transaction().add(createAssociatedAccountIx).add(mintToTx);
107
+ let associatedTokenAccountExists = false;
108
+ try {
109
+ const assosciatedTokenAccount = await this.connection.getAccountInfo(associatedTokenPublicKey);
110
+ associatedTokenAccountExists = !!assosciatedTokenAccount;
111
+ }
112
+ catch (e) {
113
+ // token account doesn't exist
114
+ associatedTokenAccountExists = false;
115
+ }
116
+ const skipAccountCreation = associatedTokenAccountExists;
117
+ if (!skipAccountCreation)
118
+ tx.add(createAssociatedAccountIx);
119
+ tx.add(mintToTx);
100
120
  const txSig = await this.program.provider.sendAndConfirm(tx, [], this.opts);
101
121
  return [associatedTokenPublicKey, txSig];
102
122
  }
@@ -104,15 +124,7 @@ class MockUSDCFaucet {
104
124
  const state = await this.fetchState();
105
125
  const associateTokenPublicKey = await this.getAssosciatedMockUSDMintAddress({ userPubKey: userPublicKey });
106
126
  const createAssociatedAccountIx = spl_token_1.Token.createAssociatedTokenAccountInstruction(spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID, spl_token_1.TOKEN_PROGRAM_ID, state.mint, associateTokenPublicKey, userPublicKey, this.wallet.publicKey);
107
- const mintToIx = await this.program.instruction.mintToUser(amount, {
108
- accounts: {
109
- mockUsdcFaucetState: await this.getMockUSDCFaucetStatePublicKey(),
110
- mintAccount: state.mint,
111
- userTokenAccount: associateTokenPublicKey,
112
- mintAuthority: state.mintAuthority,
113
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
114
- },
115
- });
127
+ const mintToIx = await this.mintToUserIx(associateTokenPublicKey, amount);
116
128
  return [associateTokenPublicKey, createAssociatedAccountIx, mintToIx];
117
129
  }
118
130
  async getAssosciatedMockUSDMintAddress(props) {
@@ -143,4 +155,4 @@ class MockUSDCFaucet {
143
155
  }
144
156
  }
145
157
  }
146
- exports.MockUSDCFaucet = MockUSDCFaucet;
158
+ exports.TokenFaucet = TokenFaucet;
@@ -25,8 +25,15 @@ class RetryTxSender {
25
25
  await this.prepareTx(tx, additionalSigners, opts);
26
26
  const rawTransaction = tx.serialize();
27
27
  const startTime = this.getTimestamp();
28
- const txid = await this.provider.connection.sendRawTransaction(rawTransaction, opts);
29
- this.sendToAdditionalConnections(rawTransaction, opts);
28
+ let txid;
29
+ try {
30
+ txid = await this.provider.connection.sendRawTransaction(rawTransaction, opts);
31
+ this.sendToAdditionalConnections(rawTransaction, opts);
32
+ }
33
+ catch (e) {
34
+ console.error(e);
35
+ throw e;
36
+ }
30
37
  let done = false;
31
38
  const resolveReference = {
32
39
  resolve: undefined,
package/lib/types.d.ts CHANGED
@@ -113,6 +113,12 @@ export declare class OrderActionExplanation {
113
113
  static readonly MARKET_ORDER_FILLED_TO_LIMIT_PRICE: {
114
114
  marketOrderFilledToLimitPrice: {};
115
115
  };
116
+ static readonly CANCELED_FOR_LIQUIDATION: {
117
+ canceledForLiquidation: {};
118
+ };
119
+ static readonly MARKET_ORDER_AUCTION_EXPIRED: {
120
+ marketOrderAuctionExpired: {};
121
+ };
116
122
  }
117
123
  export declare class OrderTriggerCondition {
118
124
  static readonly ABOVE: {
@@ -187,20 +193,76 @@ export declare type FundingPaymentRecord = {
187
193
  };
188
194
  export declare type LiquidationRecord = {
189
195
  ts: BN;
190
- recordId: BN;
191
- userAuthority: PublicKey;
192
196
  user: PublicKey;
193
- partial: boolean;
194
- baseAssetValue: BN;
195
- baseAssetValueClosed: BN;
196
- liquidationFee: BN;
197
- feeToLiquidator: BN;
198
- feeToInsuranceFund: BN;
199
197
  liquidator: PublicKey;
198
+ liquidationType: LiquidationType;
199
+ marginRequirement: BN;
200
200
  totalCollateral: BN;
201
- collateral: BN;
202
- unrealizedPnl: BN;
203
- marginRatio: BN;
201
+ liquidationId: number;
202
+ liquidatePerp: LiquidatePerpRecord;
203
+ liquidateBorrow: LiquidateBorrowRecord;
204
+ liquidateBorrowForPerpPnl: LiquidateBorrowForPerpPnlRecord;
205
+ liquidatePerpPnlForDeposit: LiquidatePerpPnlForDepositRecord;
206
+ };
207
+ export declare class LiquidationType {
208
+ static readonly LIQUIDATE_PERP: {
209
+ liquidatePerp: {};
210
+ };
211
+ static readonly LIQUIDATE_BORROW: {
212
+ liquidateBorrow: {};
213
+ };
214
+ static readonly LIQUIDATE_BORROW_FOR_PERP_PNL: {
215
+ liquidateBorrowForPerpPnl: {};
216
+ };
217
+ static readonly LIQUIDATE_PERP_PNL_FOR_DEPOSIT: {
218
+ liquidatePerpPnlForDeposit: {};
219
+ };
220
+ }
221
+ export declare type LiquidatePerpRecord = {
222
+ marketIndex: BN;
223
+ orderIds: BN[];
224
+ oraclePrice: BN;
225
+ baseAssetAmount: BN;
226
+ quoteAssetAmount: BN;
227
+ userPnl: BN;
228
+ liquidatorPnl: BN;
229
+ canceledOrdersFee: BN;
230
+ userOrderId: BN;
231
+ liquidatorOrderId: BN;
232
+ fillRecordId: BN;
233
+ };
234
+ export declare type LiquidateBorrowRecord = {
235
+ assetBankIndex: BN;
236
+ assetPrice: BN;
237
+ assetTransfer: BN;
238
+ liabilityBankIndex: BN;
239
+ liabilityPrice: BN;
240
+ liabilityTransfer: BN;
241
+ };
242
+ export declare type LiquidateBorrowForPerpPnlRecord = {
243
+ marketIndex: BN;
244
+ marketOraclePrice: BN;
245
+ pnlTransfer: BN;
246
+ liabilityBankIndex: BN;
247
+ liabilityPrice: BN;
248
+ liabilityTransfer: BN;
249
+ };
250
+ export declare type LiquidatePerpPnlForDepositRecord = {
251
+ marketIndex: BN;
252
+ marketOraclePrice: BN;
253
+ pnlTransfer: BN;
254
+ assetBankIndex: BN;
255
+ assetPrice: BN;
256
+ assetTransfer: BN;
257
+ };
258
+ export declare type SettlePnlRecord = {
259
+ ts: BN;
260
+ marketIndex: BN;
261
+ pnl: BN;
262
+ baseAssetAmount: BN;
263
+ quoteAssetAmountAfter: BN;
264
+ quoteEntryamount: BN;
265
+ oraclePrice: BN;
204
266
  };
205
267
  export declare type OrderRecord = {
206
268
  ts: BN;
@@ -208,8 +270,8 @@ export declare type OrderRecord = {
208
270
  maker: PublicKey;
209
271
  takerOrder: Order;
210
272
  makerOrder: Order;
211
- takerUnsettledPnl: BN;
212
- makerUnsettledPnl: BN;
273
+ takerPnl: BN;
274
+ makerPnl: BN;
213
275
  action: OrderAction;
214
276
  actionExplanation: OrderActionExplanation;
215
277
  filler: PublicKey;
@@ -264,9 +326,13 @@ export declare type MarketAccount = {
264
326
  openInterest: BN;
265
327
  marginRatioInitial: number;
266
328
  marginRatioMaintenance: number;
267
- marginRatioPartial: number;
268
329
  nextFillRecordId: BN;
269
330
  pnlPool: PoolBalance;
331
+ liquidationFee: BN;
332
+ imfFactor: BN;
333
+ unsettledImfFactor: BN;
334
+ unsettledInitialAssetWeight: number;
335
+ unsettledMaintenanceAssetWeight: number;
270
336
  };
271
337
  export declare type BankAccount = {
272
338
  bankIndex: BN;
@@ -289,6 +355,8 @@ export declare type BankAccount = {
289
355
  maintenanceAssetWeight: BN;
290
356
  initialLiabilityWeight: BN;
291
357
  maintenanceLiabilityWeight: BN;
358
+ liquidationFee: BN;
359
+ imfFactor: BN;
292
360
  };
293
361
  export declare type PoolBalance = {
294
362
  balance: BN;
@@ -346,7 +414,6 @@ export declare type UserPosition = {
346
414
  quoteAssetAmount: BN;
347
415
  quoteEntryAmount: BN;
348
416
  openOrders: BN;
349
- unsettledPnl: BN;
350
417
  openBids: BN;
351
418
  openAsks: BN;
352
419
  };
@@ -366,6 +433,8 @@ export declare type UserAccount = {
366
433
  };
367
434
  positions: UserPosition[];
368
435
  orders: Order[];
436
+ beingLiquidated: boolean;
437
+ nextLiquidationId: number;
369
438
  };
370
439
  export declare type UserBankBalance = {
371
440
  bankIndex: BN;
@@ -505,6 +574,7 @@ export declare type FeeStructure = {
505
574
  makerRebateNumerator: BN;
506
575
  makerRebateDenominator: BN;
507
576
  fillerRewardStructure: OrderFillerRewardStructure;
577
+ cancelOrderFee: BN;
508
578
  };
509
579
  export declare type OracleGuardRails = {
510
580
  priceDivergence: {
@@ -523,4 +593,4 @@ export declare type OrderFillerRewardStructure = {
523
593
  rewardDenominator: BN;
524
594
  timeBasedRewardLowerBound: BN;
525
595
  };
526
- export declare type MarginCategory = 'Initial' | 'Partial' | 'Maintenance';
596
+ export declare type MarginCategory = 'Initial' | 'Maintenance';
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.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.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 {
@@ -70,6 +70,12 @@ OrderActionExplanation.ORACLE_PRICE_BREACHED_LIMIT_PRICE = {
70
70
  OrderActionExplanation.MARKET_ORDER_FILLED_TO_LIMIT_PRICE = {
71
71
  marketOrderFilledToLimitPrice: {},
72
72
  };
73
+ OrderActionExplanation.CANCELED_FOR_LIQUIDATION = {
74
+ canceledForLiquidation: {},
75
+ };
76
+ OrderActionExplanation.MARKET_ORDER_AUCTION_EXPIRED = {
77
+ marketOrderAuctionExpired: {},
78
+ };
73
79
  class OrderTriggerCondition {
74
80
  }
75
81
  exports.OrderTriggerCondition = OrderTriggerCondition;
@@ -91,6 +97,17 @@ var TradeSide;
91
97
  TradeSide[TradeSide["Buy"] = 1] = "Buy";
92
98
  TradeSide[TradeSide["Sell"] = 2] = "Sell";
93
99
  })(TradeSide = exports.TradeSide || (exports.TradeSide = {}));
100
+ class LiquidationType {
101
+ }
102
+ exports.LiquidationType = LiquidationType;
103
+ LiquidationType.LIQUIDATE_PERP = { liquidatePerp: {} };
104
+ LiquidationType.LIQUIDATE_BORROW = { liquidateBorrow: {} };
105
+ LiquidationType.LIQUIDATE_BORROW_FOR_PERP_PNL = {
106
+ liquidateBorrowForPerpPnl: {},
107
+ };
108
+ LiquidationType.LIQUIDATE_PERP_PNL_FOR_DEPOSIT = {
109
+ liquidatePerpPnlForDeposit: {},
110
+ };
94
111
  exports.DefaultOrderParams = {
95
112
  orderType: OrderType.MARKET,
96
113
  userOrderId: 0,
@@ -4,7 +4,7 @@ exports.findComputeUnitConsumption = void 0;
4
4
  async function findComputeUnitConsumption(programId, connection, txSignature, commitment = 'confirmed') {
5
5
  const tx = await connection.getTransaction(txSignature, { commitment });
6
6
  const computeUnits = [];
7
- const regex = new RegExp(`Program ${programId.toString()} consumed ([0-9]{0,6}) of 200000 compute units`);
7
+ const regex = new RegExp(`Program ${programId.toString()} consumed ([0-9]{0,6}) of ([0-9]{0,7}) compute units`);
8
8
  tx.meta.logMessages.forEach((logMessage) => {
9
9
  const match = logMessage.match(regex);
10
10
  if (match && match[1]) {
@@ -0,0 +1,2 @@
1
+ import { PublicKey } from '@solana/web3.js';
2
+ export declare const getTokenAddress: (mintAddress: string, userPubKey: string) => Promise<PublicKey>;
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getTokenAddress = void 0;
4
+ const spl_token_1 = require("@solana/spl-token");
5
+ const web3_js_1 = require("@solana/web3.js");
6
+ const getTokenAddress = (mintAddress, userPubKey) => {
7
+ return spl_token_1.Token.getAssociatedTokenAddress(spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID, spl_token_1.TOKEN_PROGRAM_ID, new web3_js_1.PublicKey(mintAddress), new web3_js_1.PublicKey(userPubKey));
8
+ };
9
+ exports.getTokenAddress = getTokenAddress;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@drift-labs/sdk",
3
- "version": "0.2.0-master.10",
3
+ "version": "0.2.0-master.13",
4
4
  "main": "lib/index.js",
5
5
  "types": "lib/index.d.ts",
6
6
  "author": "crispheaney",
package/src/admin.ts CHANGED
@@ -20,7 +20,7 @@ import {
20
20
  } from './addresses/pda';
21
21
  import { TOKEN_PROGRAM_ID } from '@solana/spl-token';
22
22
  import { ClearingHouse } from './clearingHouse';
23
- import { PEG_PRECISION } from './constants/numericConstants';
23
+ import { PEG_PRECISION, ZERO } from './constants/numericConstants';
24
24
  import { calculateTargetPriceTrade } from './math/trade';
25
25
  import { calculateAmmReservesAfterSwap, getSwapDirection } from './math/amm';
26
26
 
@@ -86,7 +86,8 @@ export class Admin extends ClearingHouse {
86
86
  maintenanceAssetWeight: BN,
87
87
  initialLiabilityWeight: BN,
88
88
  maintenanceLiabilityWeight: BN,
89
- imfFactor = new BN(0)
89
+ imfFactor = new BN(0),
90
+ liquidationFee = ZERO
90
91
  ): Promise<TransactionSignature> {
91
92
  const bankIndex = this.getStateAccount().numberOfBanks;
92
93
  const bank = await getBankPublicKey(this.program.programId, bankIndex);
@@ -111,6 +112,7 @@ export class Admin extends ClearingHouse {
111
112
  initialLiabilityWeight,
112
113
  maintenanceLiabilityWeight,
113
114
  imfFactor,
115
+ liquidationFee,
114
116
  {
115
117
  accounts: {
116
118
  admin: this.wallet.publicKey,
@@ -146,8 +148,8 @@ export class Admin extends ClearingHouse {
146
148
  pegMultiplier: BN = PEG_PRECISION,
147
149
  oracleSource: OracleSource = OracleSource.PYTH,
148
150
  marginRatioInitial = 2000,
149
- marginRatioPartial = 625,
150
- marginRatioMaintenance = 500
151
+ marginRatioMaintenance = 500,
152
+ liquidationFee = ZERO
151
153
  ): Promise<TransactionSignature> {
152
154
  const marketPublicKey = await getMarketPublicKey(
153
155
  this.program.programId,
@@ -161,8 +163,8 @@ export class Admin extends ClearingHouse {
161
163
  pegMultiplier,
162
164
  oracleSource,
163
165
  marginRatioInitial,
164
- marginRatioPartial,
165
166
  marginRatioMaintenance,
167
+ liquidationFee,
166
168
  {
167
169
  accounts: {
168
170
  state: await this.getStatePublicKey(),
@@ -422,12 +424,10 @@ export class Admin extends ClearingHouse {
422
424
  public async updateMarginRatio(
423
425
  marketIndex: BN,
424
426
  marginRatioInitial: number,
425
- marginRatioPartial: number,
426
427
  marginRatioMaintenance: number
427
428
  ): Promise<TransactionSignature> {
428
429
  return await this.program.rpc.updateMarginRatio(
429
430
  marginRatioInitial,
430
- marginRatioPartial,
431
431
  marginRatioMaintenance,
432
432
  {
433
433
  accounts: {