@drift-labs/sdk 0.2.0-master.1 → 0.2.0-master.12

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 (142) hide show
  1. package/lib/accounts/types.d.ts +1 -0
  2. package/lib/admin.d.ts +8 -5
  3. package/lib/admin.js +43 -11
  4. package/lib/clearingHouse.d.ts +35 -20
  5. package/lib/clearingHouse.js +497 -154
  6. package/lib/clearingHouseUser.d.ts +12 -17
  7. package/lib/clearingHouseUser.js +97 -88
  8. package/lib/config.js +1 -1
  9. package/lib/constants/banks.d.ts +2 -2
  10. package/lib/constants/banks.js +12 -4
  11. package/lib/constants/numericConstants.d.ts +4 -0
  12. package/lib/constants/numericConstants.js +5 -1
  13. package/lib/events/eventList.js +3 -0
  14. package/lib/events/types.d.ts +2 -1
  15. package/lib/factory/bigNum.d.ts +9 -2
  16. package/lib/factory/bigNum.js +50 -16
  17. package/lib/idl/clearing_house.json +858 -177
  18. package/lib/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  19. package/lib/index.d.ts +4 -2
  20. package/lib/index.js +8 -2
  21. package/lib/math/amm.d.ts +6 -1
  22. package/lib/math/amm.js +124 -41
  23. package/lib/math/auction.js +4 -1
  24. package/lib/math/bankBalance.d.ts +3 -1
  25. package/lib/math/bankBalance.js +54 -1
  26. package/lib/math/margin.d.ts +11 -0
  27. package/lib/math/margin.js +72 -0
  28. package/lib/math/market.d.ts +4 -1
  29. package/lib/math/market.js +35 -1
  30. package/lib/math/orders.d.ts +2 -2
  31. package/lib/math/orders.js +18 -11
  32. package/lib/math/position.d.ts +8 -0
  33. package/lib/math/position.js +44 -12
  34. package/lib/math/repeg.js +1 -1
  35. package/lib/math/trade.d.ts +1 -1
  36. package/lib/math/trade.js +7 -10
  37. package/lib/orderParams.d.ts +14 -5
  38. package/lib/orderParams.js +8 -96
  39. package/lib/orders.d.ts +2 -4
  40. package/lib/orders.js +7 -161
  41. package/lib/slot/SlotSubscriber.d.ts +7 -0
  42. package/lib/slot/SlotSubscriber.js +3 -0
  43. package/lib/{mockUSDCFaucet.d.ts → tokenFaucet.d.ts} +8 -5
  44. package/lib/{mockUSDCFaucet.js → tokenFaucet.js} +63 -51
  45. package/lib/tx/retryTxSender.js +9 -2
  46. package/lib/tx/utils.js +1 -1
  47. package/lib/types.d.ts +159 -15
  48. package/lib/types.js +59 -1
  49. package/lib/util/computeUnits.js +1 -1
  50. package/lib/util/getTokenAddress.d.ts +2 -0
  51. package/lib/util/getTokenAddress.js +9 -0
  52. package/package.json +3 -3
  53. package/src/accounts/bulkAccountLoader.js +197 -0
  54. package/src/accounts/bulkUserSubscription.js +33 -0
  55. package/src/accounts/pollingClearingHouseAccountSubscriber.js +311 -0
  56. package/src/accounts/pollingOracleSubscriber.js +93 -0
  57. package/src/accounts/pollingTokenAccountSubscriber.js +90 -0
  58. package/src/accounts/pollingUserAccountSubscriber.js +132 -0
  59. package/src/accounts/types.js +10 -0
  60. package/src/accounts/utils.js +7 -0
  61. package/src/accounts/webSocketAccountSubscriber.js +93 -0
  62. package/src/accounts/webSocketClearingHouseAccountSubscriber.js +233 -0
  63. package/src/accounts/webSocketUserAccountSubscriber.js +62 -0
  64. package/src/addresses/marketAddresses.js +26 -0
  65. package/src/admin.ts +66 -14
  66. package/src/assert/assert.js +9 -0
  67. package/src/clearingHouse.ts +836 -254
  68. package/src/clearingHouseConfig.js +2 -0
  69. package/src/clearingHouseUser.ts +219 -121
  70. package/src/clearingHouseUserConfig.js +2 -0
  71. package/src/config.ts +1 -1
  72. package/src/constants/banks.js +42 -0
  73. package/src/constants/banks.ts +14 -4
  74. package/src/constants/markets.js +42 -0
  75. package/src/constants/numericConstants.js +41 -0
  76. package/src/constants/numericConstants.ts +5 -0
  77. package/src/events/eventList.js +77 -0
  78. package/src/events/eventList.ts +3 -0
  79. package/src/events/eventSubscriber.js +139 -0
  80. package/src/events/fetchLogs.js +50 -0
  81. package/src/events/pollingLogProvider.js +64 -0
  82. package/src/events/sort.js +44 -0
  83. package/src/events/txEventCache.js +71 -0
  84. package/src/events/types.js +20 -0
  85. package/src/events/types.ts +2 -0
  86. package/src/events/webSocketLogProvider.js +41 -0
  87. package/src/examples/makeTradeExample.js +80 -0
  88. package/src/factory/bigNum.js +390 -0
  89. package/src/factory/bigNum.ts +65 -18
  90. package/src/factory/oracleClient.js +20 -0
  91. package/src/idl/clearing_house.json +858 -177
  92. package/src/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  93. package/src/index.js +69 -0
  94. package/src/index.ts +4 -2
  95. package/src/math/amm.js +369 -0
  96. package/src/math/amm.ts +207 -52
  97. package/src/math/auction.js +42 -0
  98. package/src/math/auction.ts +5 -1
  99. package/src/math/bankBalance.ts +98 -1
  100. package/src/math/conversion.js +11 -0
  101. package/src/math/funding.js +248 -0
  102. package/src/math/margin.ts +124 -0
  103. package/src/math/market.ts +66 -1
  104. package/src/math/oracles.js +26 -0
  105. package/src/math/orders.ts +17 -13
  106. package/src/math/position.ts +63 -9
  107. package/src/math/repeg.js +128 -0
  108. package/src/math/repeg.ts +2 -1
  109. package/src/math/state.js +15 -0
  110. package/src/math/trade.js +253 -0
  111. package/src/math/trade.ts +23 -25
  112. package/src/math/utils.js +0 -1
  113. package/src/mockUSDCFaucet.js +280 -0
  114. package/src/oracles/oracleClientCache.js +19 -0
  115. package/src/oracles/pythClient.js +46 -0
  116. package/src/oracles/quoteAssetOracleClient.js +32 -0
  117. package/src/oracles/switchboardClient.js +69 -0
  118. package/src/oracles/types.js +2 -0
  119. package/src/orderParams.js +20 -0
  120. package/src/orderParams.ts +20 -141
  121. package/src/orders.ts +10 -287
  122. package/src/slot/SlotSubscriber.js +39 -0
  123. package/src/slot/SlotSubscriber.ts +11 -1
  124. package/src/token/index.js +38 -0
  125. package/src/tokenFaucet.js +189 -0
  126. package/src/{mockUSDCFaucet.ts → tokenFaucet.ts} +82 -70
  127. package/src/tx/retryTxSender.ts +11 -3
  128. package/src/tx/types.js +2 -0
  129. package/src/tx/utils.js +17 -0
  130. package/src/tx/utils.ts +1 -1
  131. package/src/types.js +125 -0
  132. package/src/types.ts +155 -17
  133. package/src/userName.js +20 -0
  134. package/src/util/computeUnits.js +21 -11
  135. package/src/util/computeUnits.ts +1 -1
  136. package/src/util/getTokenAddress.js +9 -0
  137. package/src/util/getTokenAddress.ts +18 -0
  138. package/src/util/promiseTimeout.js +14 -0
  139. package/src/util/tps.js +27 -0
  140. package/src/wallet.js +35 -0
  141. package/tests/bn/test.ts +2 -0
  142. package/src/util/computeUnits.js.map +0 -1
@@ -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/tx/utils.js CHANGED
@@ -3,7 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.wrapInTx = void 0;
4
4
  const web3_js_1 = require("@solana/web3.js");
5
5
  const COMPUTE_UNITS_DEFAULT = 200000;
6
- function wrapInTx(instruction, computeUnits = 500000 // TODO, requires less code change
6
+ function wrapInTx(instruction, computeUnits = 600000 // TODO, requires less code change
7
7
  ) {
8
8
  const tx = new web3_js_1.Transaction();
9
9
  if (computeUnits != COMPUTE_UNITS_DEFAULT) {
package/lib/types.d.ts CHANGED
@@ -25,6 +25,14 @@ export declare class PositionDirection {
25
25
  short: {};
26
26
  };
27
27
  }
28
+ export declare class DepositDirection {
29
+ static readonly DEPOSIT: {
30
+ deposit: {};
31
+ };
32
+ static readonly WITHDRAW: {
33
+ withdraw: {};
34
+ };
35
+ }
28
36
  export declare class OracleSource {
29
37
  static readonly PYTH: {
30
38
  pyth: {};
@@ -88,6 +96,29 @@ export declare class OrderAction {
88
96
  static readonly FILL: {
89
97
  fill: {};
90
98
  };
99
+ static readonly TRIGGER: {
100
+ trigger: {};
101
+ };
102
+ }
103
+ export declare class OrderActionExplanation {
104
+ static readonly NONE: {
105
+ none: {};
106
+ };
107
+ static readonly BREACHED_MARGIN_REQUIREMENT: {
108
+ breachedMarginRequirement: {};
109
+ };
110
+ static readonly ORACLE_PRICE_BREACHED_LIMIT_PRICE: {
111
+ oraclePriceBreachedLimitPrice: {};
112
+ };
113
+ static readonly MARKET_ORDER_FILLED_TO_LIMIT_PRICE: {
114
+ marketOrderFilledToLimitPrice: {};
115
+ };
116
+ static readonly CANCELED_FOR_LIQUIDATION: {
117
+ canceledForLiquidation: {};
118
+ };
119
+ static readonly MARKET_ORDER_AUCTION_EXPIRED: {
120
+ marketOrderAuctionExpired: {};
121
+ };
91
122
  }
92
123
  export declare class OrderTriggerCondition {
93
124
  static readonly ABOVE: {
@@ -115,6 +146,7 @@ export declare type DepositRecord = {
115
146
  };
116
147
  bankIndex: BN;
117
148
  amount: BN;
149
+ oraclePrice: BN;
118
150
  from?: PublicKey;
119
151
  to?: PublicKey;
120
152
  };
@@ -161,20 +193,76 @@ export declare type FundingPaymentRecord = {
161
193
  };
162
194
  export declare type LiquidationRecord = {
163
195
  ts: BN;
164
- recordId: BN;
165
- userAuthority: PublicKey;
166
196
  user: PublicKey;
167
- partial: boolean;
168
- baseAssetValue: BN;
169
- baseAssetValueClosed: BN;
170
- liquidationFee: BN;
171
- feeToLiquidator: BN;
172
- feeToInsuranceFund: BN;
173
197
  liquidator: PublicKey;
198
+ liquidationType: LiquidationType;
199
+ marginRequirement: BN;
174
200
  totalCollateral: BN;
175
- collateral: BN;
176
- unrealizedPnl: BN;
177
- 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;
178
266
  };
179
267
  export declare type OrderRecord = {
180
268
  ts: BN;
@@ -182,7 +270,10 @@ export declare type OrderRecord = {
182
270
  maker: PublicKey;
183
271
  takerOrder: Order;
184
272
  makerOrder: Order;
273
+ takerPnl: BN;
274
+ makerPnl: BN;
185
275
  action: OrderAction;
276
+ actionExplanation: OrderActionExplanation;
186
277
  filler: PublicKey;
187
278
  fillRecordId: BN;
188
279
  marketIndex: BN;
@@ -235,9 +326,13 @@ export declare type MarketAccount = {
235
326
  openInterest: BN;
236
327
  marginRatioInitial: number;
237
328
  marginRatioMaintenance: number;
238
- marginRatioPartial: number;
239
329
  nextFillRecordId: BN;
240
330
  pnlPool: PoolBalance;
331
+ liquidationFee: BN;
332
+ imfFactor: BN;
333
+ unsettledImfFactor: BN;
334
+ unsettledInitialAssetWeight: number;
335
+ unsettledMaintenanceAssetWeight: number;
241
336
  };
242
337
  export declare type BankAccount = {
243
338
  bankIndex: BN;
@@ -260,6 +355,8 @@ export declare type BankAccount = {
260
355
  maintenanceAssetWeight: BN;
261
356
  initialLiabilityWeight: BN;
262
357
  maintenanceLiabilityWeight: BN;
358
+ liquidationFee: BN;
359
+ imfFactor: BN;
263
360
  };
264
361
  export declare type PoolBalance = {
265
362
  balance: BN;
@@ -274,6 +371,8 @@ export declare type AMM = {
274
371
  lastMarkPriceTwapTs: BN;
275
372
  lastOraclePriceTwap: BN;
276
373
  lastOraclePriceTwapTs: BN;
374
+ lastOracleMarkSpreadPct: BN;
375
+ lastOracleConfPct: BN;
277
376
  oracle: PublicKey;
278
377
  oracleSource: OracleSource;
279
378
  fundingPeriod: BN;
@@ -288,6 +387,8 @@ export declare type AMM = {
288
387
  totalFee: BN;
289
388
  minimumQuoteAssetTradeSize: BN;
290
389
  baseAssetAmountStepSize: BN;
390
+ maxBaseAssetAmountRatio: number;
391
+ maxSlippageRatio: number;
291
392
  lastOraclePrice: BN;
292
393
  baseSpread: number;
293
394
  curveUpdateIntensity: number;
@@ -304,6 +405,7 @@ export declare type AMM = {
304
405
  lastAskPriceTwap: BN;
305
406
  longSpread: BN;
306
407
  shortSpread: BN;
408
+ maxSpread: number;
307
409
  };
308
410
  export declare type UserPosition = {
309
411
  baseAssetAmount: BN;
@@ -312,7 +414,6 @@ export declare type UserPosition = {
312
414
  quoteAssetAmount: BN;
313
415
  quoteEntryAmount: BN;
314
416
  openOrders: BN;
315
- unsettledPnl: BN;
316
417
  openBids: BN;
317
418
  openAsks: BN;
318
419
  };
@@ -332,6 +433,8 @@ export declare type UserAccount = {
332
433
  };
333
434
  positions: UserPosition[];
334
435
  orders: Order[];
436
+ beingLiquidated: boolean;
437
+ nextLiquidationId: number;
335
438
  };
336
439
  export declare type UserBankBalance = {
337
440
  bankIndex: BN;
@@ -356,6 +459,7 @@ export declare type Order = {
356
459
  reduceOnly: boolean;
357
460
  triggerPrice: BN;
358
461
  triggerCondition: OrderTriggerCondition;
462
+ triggered: boolean;
359
463
  discountTier: OrderDiscountTier;
360
464
  existingPositionDirection: PositionDirection;
361
465
  referrer: PublicKey;
@@ -370,7 +474,6 @@ export declare type OrderParams = {
370
474
  orderType: OrderType;
371
475
  userOrderId: number;
372
476
  direction: PositionDirection;
373
- quoteAssetAmount: BN;
374
477
  baseAssetAmount: BN;
375
478
  price: BN;
376
479
  marketIndex: BN;
@@ -388,10 +491,50 @@ export declare type OrderParams = {
388
491
  referrer: boolean;
389
492
  };
390
493
  };
494
+ export declare type NecessaryOrderParams = {
495
+ orderType: OrderType;
496
+ marketIndex: BN;
497
+ baseAssetAmount: BN;
498
+ direction: PositionDirection;
499
+ };
500
+ export declare type OptionalOrderParams = {
501
+ [Property in keyof OrderParams]?: OrderParams[Property];
502
+ } & NecessaryOrderParams;
503
+ export declare const DefaultOrderParams: {
504
+ orderType: {
505
+ market: {};
506
+ };
507
+ userOrderId: number;
508
+ direction: {
509
+ long: {};
510
+ };
511
+ baseAssetAmount: BN;
512
+ price: BN;
513
+ marketIndex: BN;
514
+ reduceOnly: boolean;
515
+ postOnly: boolean;
516
+ immediateOrCancel: boolean;
517
+ triggerPrice: BN;
518
+ triggerCondition: {
519
+ above: {};
520
+ };
521
+ positionLimit: BN;
522
+ oraclePriceOffset: BN;
523
+ padding0: BN;
524
+ padding1: BN;
525
+ optionalAccounts: {
526
+ discountToken: boolean;
527
+ referrer: boolean;
528
+ };
529
+ };
391
530
  export declare type MakerInfo = {
392
531
  maker: PublicKey;
393
532
  order: Order;
394
533
  };
534
+ export declare type TakerInfo = {
535
+ taker: PublicKey;
536
+ order: Order;
537
+ };
395
538
  export interface IWallet {
396
539
  signTransaction(tx: Transaction): Promise<Transaction>;
397
540
  signAllTransactions(txs: Transaction[]): Promise<Transaction[]>;
@@ -431,6 +574,7 @@ export declare type FeeStructure = {
431
574
  makerRebateNumerator: BN;
432
575
  makerRebateDenominator: BN;
433
576
  fillerRewardStructure: OrderFillerRewardStructure;
577
+ cancelOrderFee: BN;
434
578
  };
435
579
  export declare type OracleGuardRails = {
436
580
  priceDivergence: {
@@ -449,4 +593,4 @@ export declare type OrderFillerRewardStructure = {
449
593
  rewardDenominator: BN;
450
594
  timeBasedRewardLowerBound: BN;
451
595
  };
452
- export declare type MarginCategory = 'Initial' | 'Partial' | 'Maintenance';
596
+ export declare type MarginCategory = 'Initial' | 'Maintenance';
package/lib/types.js CHANGED
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TradeSide = exports.isOneOfVariant = exports.isVariant = exports.OrderTriggerCondition = exports.OrderAction = exports.OrderDiscountTier = exports.OrderStatus = exports.OrderType = exports.OracleSource = 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
+ const _1 = require(".");
4
5
  // # Utility Types / Enums / Constants
5
6
  class SwapDirection {
6
7
  }
@@ -17,6 +18,11 @@ class PositionDirection {
17
18
  exports.PositionDirection = PositionDirection;
18
19
  PositionDirection.LONG = { long: {} };
19
20
  PositionDirection.SHORT = { short: {} };
21
+ class DepositDirection {
22
+ }
23
+ exports.DepositDirection = DepositDirection;
24
+ DepositDirection.DEPOSIT = { deposit: {} };
25
+ DepositDirection.WITHDRAW = { withdraw: {} };
20
26
  class OracleSource {
21
27
  }
22
28
  exports.OracleSource = OracleSource;
@@ -50,6 +56,26 @@ OrderAction.PLACE = { place: {} };
50
56
  OrderAction.CANCEL = { cancel: {} };
51
57
  OrderAction.EXPIRE = { expire: {} };
52
58
  OrderAction.FILL = { fill: {} };
59
+ OrderAction.TRIGGER = { trigger: {} };
60
+ class OrderActionExplanation {
61
+ }
62
+ exports.OrderActionExplanation = OrderActionExplanation;
63
+ OrderActionExplanation.NONE = { none: {} };
64
+ OrderActionExplanation.BREACHED_MARGIN_REQUIREMENT = {
65
+ breachedMarginRequirement: {},
66
+ };
67
+ OrderActionExplanation.ORACLE_PRICE_BREACHED_LIMIT_PRICE = {
68
+ oraclePriceBreachedLimitPrice: {},
69
+ };
70
+ OrderActionExplanation.MARKET_ORDER_FILLED_TO_LIMIT_PRICE = {
71
+ marketOrderFilledToLimitPrice: {},
72
+ };
73
+ OrderActionExplanation.CANCELED_FOR_LIQUIDATION = {
74
+ canceledForLiquidation: {},
75
+ };
76
+ OrderActionExplanation.MARKET_ORDER_AUCTION_EXPIRED = {
77
+ marketOrderAuctionExpired: {},
78
+ };
53
79
  class OrderTriggerCondition {
54
80
  }
55
81
  exports.OrderTriggerCondition = OrderTriggerCondition;
@@ -71,3 +97,35 @@ var TradeSide;
71
97
  TradeSide[TradeSide["Buy"] = 1] = "Buy";
72
98
  TradeSide[TradeSide["Sell"] = 2] = "Sell";
73
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
+ };
111
+ exports.DefaultOrderParams = {
112
+ orderType: OrderType.MARKET,
113
+ userOrderId: 0,
114
+ direction: PositionDirection.LONG,
115
+ baseAssetAmount: _1.ZERO,
116
+ price: _1.ZERO,
117
+ marketIndex: _1.ZERO,
118
+ reduceOnly: false,
119
+ postOnly: false,
120
+ immediateOrCancel: false,
121
+ triggerPrice: _1.ZERO,
122
+ triggerCondition: OrderTriggerCondition.ABOVE,
123
+ positionLimit: _1.ZERO,
124
+ oraclePriceOffset: _1.ZERO,
125
+ padding0: _1.ZERO,
126
+ padding1: _1.ZERO,
127
+ optionalAccounts: {
128
+ discountToken: false,
129
+ referrer: false,
130
+ },
131
+ };
@@ -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.1",
3
+ "version": "0.2.0-master.12",
4
4
  "main": "lib/index.js",
5
5
  "types": "lib/index.d.ts",
6
6
  "author": "crispheaney",
@@ -30,7 +30,7 @@
30
30
  },
31
31
  "dependencies": {
32
32
  "@project-serum/anchor": "0.24.2",
33
- "@pythnetwork/client": "2.5.1",
33
+ "@pythnetwork/client": "2.5.3",
34
34
  "@solana/spl-token": "^0.1.6",
35
35
  "@solana/web3.js": "1.41.0",
36
36
  "@switchboard-xyz/switchboard-v2": "^0.0.67",
@@ -39,10 +39,10 @@
39
39
  },
40
40
  "devDependencies": {
41
41
  "@types/chai": "^4.3.1",
42
+ "@types/jest": "^28.1.3",
42
43
  "@types/mocha": "^9.1.1",
43
44
  "@typescript-eslint/eslint-plugin": "^4.28.0",
44
45
  "@typescript-eslint/parser": "^4.28.0",
45
- "@types/jest": "^28.1.3",
46
46
  "chai": "^4.3.6",
47
47
  "eslint": "^7.29.0",
48
48
  "eslint-config-prettier": "^8.3.0",