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

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 (149) hide show
  1. package/lib/accounts/bulkUserStatsSubscription.d.ts +7 -0
  2. package/lib/accounts/bulkUserStatsSubscription.js +21 -0
  3. package/lib/accounts/bulkUserSubscription.js +0 -1
  4. package/lib/accounts/fetch.d.ts +2 -1
  5. package/lib/accounts/fetch.js +9 -1
  6. package/lib/accounts/pollingUserStatsAccountSubscriber.d.ts +27 -0
  7. package/lib/accounts/pollingUserStatsAccountSubscriber.js +113 -0
  8. package/lib/accounts/types.d.ts +14 -1
  9. package/lib/accounts/webSocketUserStatsAccountSubsriber.d.ts +20 -0
  10. package/lib/accounts/webSocketUserStatsAccountSubsriber.js +47 -0
  11. package/lib/addresses/pda.d.ts +1 -0
  12. package/lib/addresses/pda.js +8 -1
  13. package/lib/admin.d.ts +9 -5
  14. package/lib/admin.js +52 -11
  15. package/lib/clearingHouse.d.ts +52 -23
  16. package/lib/clearingHouse.js +736 -200
  17. package/lib/clearingHouseConfig.d.ts +1 -0
  18. package/lib/clearingHouseUser.d.ts +24 -16
  19. package/lib/clearingHouseUser.js +223 -101
  20. package/lib/clearingHouseUserStats.d.ts +18 -0
  21. package/lib/clearingHouseUserStats.js +49 -0
  22. package/lib/clearingHouseUserStatsConfig.d.ts +14 -0
  23. package/lib/clearingHouseUserStatsConfig.js +2 -0
  24. package/lib/config.js +1 -1
  25. package/lib/constants/banks.d.ts +2 -2
  26. package/lib/constants/banks.js +12 -4
  27. package/lib/constants/numericConstants.d.ts +5 -0
  28. package/lib/constants/numericConstants.js +8 -3
  29. package/lib/events/eventList.js +3 -0
  30. package/lib/events/types.d.ts +3 -1
  31. package/lib/events/types.js +2 -0
  32. package/lib/factory/bigNum.d.ts +1 -0
  33. package/lib/factory/bigNum.js +34 -10
  34. package/lib/idl/clearing_house.json +1603 -377
  35. package/lib/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  36. package/lib/index.d.ts +9 -3
  37. package/lib/index.js +13 -3
  38. package/lib/math/amm.d.ts +1 -0
  39. package/lib/math/amm.js +22 -38
  40. package/lib/math/auction.js +4 -1
  41. package/lib/math/bankBalance.d.ts +7 -1
  42. package/lib/math/bankBalance.js +77 -2
  43. package/lib/math/margin.d.ts +11 -0
  44. package/lib/math/margin.js +72 -0
  45. package/lib/math/market.d.ts +4 -1
  46. package/lib/math/market.js +35 -1
  47. package/lib/math/oracles.d.ts +3 -0
  48. package/lib/math/oracles.js +25 -5
  49. package/lib/math/orders.d.ts +6 -2
  50. package/lib/math/orders.js +62 -12
  51. package/lib/math/position.d.ts +8 -0
  52. package/lib/math/position.js +45 -12
  53. package/lib/math/trade.d.ts +1 -1
  54. package/lib/math/trade.js +7 -10
  55. package/lib/orderParams.d.ts +14 -5
  56. package/lib/orderParams.js +8 -96
  57. package/lib/slot/SlotSubscriber.d.ts +7 -0
  58. package/lib/slot/SlotSubscriber.js +3 -0
  59. package/lib/{mockUSDCFaucet.d.ts → tokenFaucet.d.ts} +8 -5
  60. package/lib/{mockUSDCFaucet.js → tokenFaucet.js} +63 -51
  61. package/lib/tx/retryTxSender.js +9 -2
  62. package/lib/tx/utils.js +1 -1
  63. package/lib/types.d.ts +236 -26
  64. package/lib/types.js +64 -1
  65. package/lib/util/computeUnits.js +1 -1
  66. package/lib/util/getTokenAddress.d.ts +2 -0
  67. package/lib/util/getTokenAddress.js +9 -0
  68. package/package.json +3 -3
  69. package/src/accounts/bulkUserStatsSubscription.ts +33 -0
  70. package/src/accounts/bulkUserSubscription.ts +0 -1
  71. package/src/accounts/fetch.ts +27 -2
  72. package/src/accounts/pollingUserStatsAccountSubscriber.ts +172 -0
  73. package/src/accounts/types.ts +18 -0
  74. package/src/accounts/webSocketUserStatsAccountSubsriber.ts +80 -0
  75. package/src/addresses/marketAddresses.js +26 -0
  76. package/src/addresses/pda.ts +13 -0
  77. package/src/admin.ts +82 -15
  78. package/src/assert/assert.js +9 -0
  79. package/src/clearingHouse.ts +1232 -323
  80. package/src/clearingHouseConfig.ts +1 -0
  81. package/src/clearingHouseUser.ts +343 -155
  82. package/src/clearingHouseUserStats.ts +75 -0
  83. package/src/clearingHouseUserStatsConfig.ts +18 -0
  84. package/src/config.ts +1 -1
  85. package/src/constants/banks.js +42 -0
  86. package/src/constants/banks.ts +14 -4
  87. package/src/constants/markets.js +42 -0
  88. package/src/constants/numericConstants.js +41 -0
  89. package/src/constants/numericConstants.ts +14 -2
  90. package/src/events/eventList.js +77 -0
  91. package/src/events/eventList.ts +3 -0
  92. package/src/events/eventSubscriber.js +139 -0
  93. package/src/events/sort.js +44 -0
  94. package/src/events/txEventCache.js +71 -0
  95. package/src/events/types.ts +6 -0
  96. package/src/examples/makeTradeExample.js +80 -0
  97. package/src/factory/bigNum.js +390 -0
  98. package/src/factory/bigNum.ts +42 -13
  99. package/src/factory/oracleClient.js +20 -0
  100. package/src/idl/clearing_house.json +1603 -377
  101. package/src/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  102. package/src/index.ts +9 -3
  103. package/src/math/amm.ts +54 -55
  104. package/src/math/auction.js +42 -0
  105. package/src/math/auction.ts +5 -1
  106. package/src/math/bankBalance.ts +148 -2
  107. package/src/math/conversion.js +11 -0
  108. package/src/math/funding.js +248 -0
  109. package/src/math/margin.ts +124 -0
  110. package/src/math/market.ts +66 -1
  111. package/src/math/oracles.js +26 -0
  112. package/src/math/oracles.ts +42 -5
  113. package/src/math/orders.ts +129 -13
  114. package/src/math/position.ts +64 -9
  115. package/src/math/repeg.js +128 -0
  116. package/src/math/state.js +15 -0
  117. package/src/math/trade.js +253 -0
  118. package/src/math/trade.ts +23 -25
  119. package/src/math/utils.js +0 -1
  120. package/src/oracles/oracleClientCache.js +19 -0
  121. package/src/oracles/pythClient.js +46 -0
  122. package/src/oracles/quoteAssetOracleClient.js +32 -0
  123. package/src/oracles/switchboardClient.js +69 -0
  124. package/src/oracles/types.js +2 -0
  125. package/src/orderParams.js +20 -0
  126. package/src/orderParams.ts +20 -141
  127. package/src/slot/SlotSubscriber.js +39 -0
  128. package/src/slot/SlotSubscriber.ts +11 -1
  129. package/src/token/index.js +38 -0
  130. package/src/tokenFaucet.js +189 -0
  131. package/src/{mockUSDCFaucet.ts → tokenFaucet.ts} +82 -70
  132. package/src/tx/retryTxSender.ts +11 -3
  133. package/src/tx/types.js +2 -0
  134. package/src/tx/utils.js +17 -0
  135. package/src/tx/utils.ts +1 -1
  136. package/src/types.ts +239 -27
  137. package/src/userName.js +20 -0
  138. package/src/util/computeUnits.js +21 -11
  139. package/src/util/computeUnits.ts +1 -1
  140. package/src/util/getTokenAddress.js +9 -0
  141. package/src/util/getTokenAddress.ts +18 -0
  142. package/src/util/promiseTimeout.js +14 -0
  143. package/src/util/tps.js +27 -0
  144. package/src/wallet.js +35 -0
  145. package/tests/bn/test.ts +10 -0
  146. package/lib/orders.d.ts +0 -8
  147. package/lib/orders.js +0 -142
  148. package/src/orders.ts +0 -251
  149. package/src/util/computeUnits.js.map +0 -1
@@ -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: {};
@@ -92,6 +100,26 @@ export declare class OrderAction {
92
100
  trigger: {};
93
101
  };
94
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
+ };
122
+ }
95
123
  export declare class OrderTriggerCondition {
96
124
  static readonly ABOVE: {
97
125
  above: {};
@@ -108,6 +136,14 @@ export declare enum TradeSide {
108
136
  Sell = 2
109
137
  }
110
138
  export declare type CandleResolution = '1' | '5' | '15' | '60' | '240' | 'D' | 'W' | 'M';
139
+ export declare type NewUserRecord = {
140
+ ts: BN;
141
+ userAuthority: PublicKey;
142
+ user: PublicKey;
143
+ userId: number;
144
+ name: number[];
145
+ referrer: PublicKey;
146
+ };
111
147
  export declare type DepositRecord = {
112
148
  ts: BN;
113
149
  userAuthority: PublicKey;
@@ -118,6 +154,8 @@ export declare type DepositRecord = {
118
154
  };
119
155
  bankIndex: BN;
120
156
  amount: BN;
157
+ oraclePrice: BN;
158
+ referrer: PublicKey;
121
159
  from?: PublicKey;
122
160
  to?: PublicKey;
123
161
  };
@@ -164,20 +202,95 @@ export declare type FundingPaymentRecord = {
164
202
  };
165
203
  export declare type LiquidationRecord = {
166
204
  ts: BN;
167
- recordId: BN;
168
- userAuthority: PublicKey;
169
205
  user: PublicKey;
170
- partial: boolean;
171
- baseAssetValue: BN;
172
- baseAssetValueClosed: BN;
173
- liquidationFee: BN;
174
- feeToLiquidator: BN;
175
- feeToInsuranceFund: BN;
176
206
  liquidator: PublicKey;
207
+ liquidationType: LiquidationType;
208
+ marginRequirement: BN;
177
209
  totalCollateral: BN;
178
- collateral: BN;
179
- unrealizedPnl: BN;
180
- marginRatio: BN;
210
+ liquidationId: number;
211
+ liquidatePerp: LiquidatePerpRecord;
212
+ liquidateBorrow: LiquidateBorrowRecord;
213
+ liquidateBorrowForPerpPnl: LiquidateBorrowForPerpPnlRecord;
214
+ liquidatePerpPnlForDeposit: LiquidatePerpPnlForDepositRecord;
215
+ perpBankruptcy: PerpBankruptcyRecord;
216
+ borrowBankruptcy: BorrowBankruptcyRecord;
217
+ };
218
+ export declare class LiquidationType {
219
+ static readonly LIQUIDATE_PERP: {
220
+ liquidatePerp: {};
221
+ };
222
+ static readonly LIQUIDATE_BORROW: {
223
+ liquidateBorrow: {};
224
+ };
225
+ static readonly LIQUIDATE_BORROW_FOR_PERP_PNL: {
226
+ liquidateBorrowForPerpPnl: {};
227
+ };
228
+ static readonly LIQUIDATE_PERP_PNL_FOR_DEPOSIT: {
229
+ liquidatePerpPnlForDeposit: {};
230
+ };
231
+ static readonly PERP_BANKRUPTCY: {
232
+ perpBankruptcy: {};
233
+ };
234
+ static readonly BORROW_BANKRUPTCY: {
235
+ borrowBankruptcy: {};
236
+ };
237
+ }
238
+ export declare type LiquidatePerpRecord = {
239
+ marketIndex: BN;
240
+ orderIds: BN[];
241
+ oraclePrice: BN;
242
+ baseAssetAmount: BN;
243
+ quoteAssetAmount: BN;
244
+ userPnl: BN;
245
+ liquidatorPnl: BN;
246
+ canceledOrdersFee: BN;
247
+ userOrderId: BN;
248
+ liquidatorOrderId: BN;
249
+ fillRecordId: BN;
250
+ };
251
+ export declare type LiquidateBorrowRecord = {
252
+ assetBankIndex: BN;
253
+ assetPrice: BN;
254
+ assetTransfer: BN;
255
+ liabilityBankIndex: BN;
256
+ liabilityPrice: BN;
257
+ liabilityTransfer: BN;
258
+ };
259
+ export declare type LiquidateBorrowForPerpPnlRecord = {
260
+ marketIndex: BN;
261
+ marketOraclePrice: BN;
262
+ pnlTransfer: BN;
263
+ liabilityBankIndex: BN;
264
+ liabilityPrice: BN;
265
+ liabilityTransfer: BN;
266
+ };
267
+ export declare type LiquidatePerpPnlForDepositRecord = {
268
+ marketIndex: BN;
269
+ marketOraclePrice: BN;
270
+ pnlTransfer: BN;
271
+ assetBankIndex: BN;
272
+ assetPrice: BN;
273
+ assetTransfer: BN;
274
+ };
275
+ export declare type PerpBankruptcyRecord = {
276
+ marketIndex: BN;
277
+ pnl: BN;
278
+ cumulativeFundingRateDelta: BN;
279
+ };
280
+ export declare type BorrowBankruptcyRecord = {
281
+ bankIndex: BN;
282
+ borrowAmount: BN;
283
+ cumulativeDepositInterestDelta: BN;
284
+ };
285
+ export declare type SettlePnlRecord = {
286
+ ts: BN;
287
+ user: PublicKey;
288
+ marketIndex: BN;
289
+ pnl: BN;
290
+ baseAssetAmount: BN;
291
+ quoteAssetAmountAfter: BN;
292
+ quoteEntryamount: BN;
293
+ settlePrice: BN;
181
294
  };
182
295
  export declare type OrderRecord = {
183
296
  ts: BN;
@@ -185,7 +298,10 @@ export declare type OrderRecord = {
185
298
  maker: PublicKey;
186
299
  takerOrder: Order;
187
300
  makerOrder: Order;
301
+ takerPnl: BN;
302
+ makerPnl: BN;
188
303
  action: OrderAction;
304
+ actionExplanation: OrderActionExplanation;
189
305
  filler: PublicKey;
190
306
  fillRecordId: BN;
191
307
  marketIndex: BN;
@@ -196,6 +312,9 @@ export declare type OrderRecord = {
196
312
  fillerReward: BN;
197
313
  quoteAssetAmountSurplus: BN;
198
314
  oraclePrice: BN;
315
+ referrer: PublicKey;
316
+ referrerReward: BN;
317
+ refereeDiscount: BN;
199
318
  };
200
319
  export declare type StateAccount = {
201
320
  admin: PublicKey;
@@ -226,6 +345,8 @@ export declare type StateAccount = {
226
345
  numberOfMarkets: BN;
227
346
  numberOfBanks: BN;
228
347
  minOrderQuoteAssetAmount: BN;
348
+ maxAuctionDuration: number;
349
+ minAuctionDuration: number;
229
350
  };
230
351
  export declare type MarketAccount = {
231
352
  initialized: boolean;
@@ -238,9 +359,13 @@ export declare type MarketAccount = {
238
359
  openInterest: BN;
239
360
  marginRatioInitial: number;
240
361
  marginRatioMaintenance: number;
241
- marginRatioPartial: number;
242
362
  nextFillRecordId: BN;
243
363
  pnlPool: PoolBalance;
364
+ liquidationFee: BN;
365
+ imfFactor: BN;
366
+ unrealizedImfFactor: BN;
367
+ unrealizedInitialAssetWeight: number;
368
+ unrealizedMaintenanceAssetWeight: number;
244
369
  };
245
370
  export declare type BankAccount = {
246
371
  bankIndex: BN;
@@ -257,12 +382,19 @@ export declare type BankAccount = {
257
382
  cumulativeBorrowInterest: BN;
258
383
  depositBalance: BN;
259
384
  borrowBalance: BN;
260
- lastUpdated: BN;
385
+ lastInterestTs: BN;
386
+ lastTwapTs: BN;
261
387
  oracle: PublicKey;
262
388
  initialAssetWeight: BN;
263
389
  maintenanceAssetWeight: BN;
264
390
  initialLiabilityWeight: BN;
265
391
  maintenanceLiabilityWeight: BN;
392
+ liquidationFee: BN;
393
+ imfFactor: BN;
394
+ withdrawGuardThreshold: BN;
395
+ depositTokenTwap: BN;
396
+ borrowTokenTwap: BN;
397
+ utilizationTwap: BN;
266
398
  };
267
399
  export declare type PoolBalance = {
268
400
  balance: BN;
@@ -274,9 +406,13 @@ export declare type AMM = {
274
406
  lastFundingRate: BN;
275
407
  lastFundingRateTs: BN;
276
408
  lastMarkPriceTwap: BN;
409
+ lastMarkPriceTwap5min: BN;
277
410
  lastMarkPriceTwapTs: BN;
278
411
  lastOraclePriceTwap: BN;
412
+ lastOraclePriceTwap5min: BN;
279
413
  lastOraclePriceTwapTs: BN;
414
+ lastOracleMarkSpreadPct: BN;
415
+ lastOracleConfPct: BN;
280
416
  oracle: PublicKey;
281
417
  oracleSource: OracleSource;
282
418
  fundingPeriod: BN;
@@ -284,13 +420,20 @@ export declare type AMM = {
284
420
  pegMultiplier: BN;
285
421
  cumulativeFundingRateLong: BN;
286
422
  cumulativeFundingRateShort: BN;
423
+ cumulativeFundingRateLp: BN;
287
424
  cumulativeRepegRebateLong: BN;
288
425
  cumulativeRepegRebateShort: BN;
289
426
  totalFeeMinusDistributions: BN;
290
427
  totalFeeWithdrawn: BN;
291
428
  totalFee: BN;
429
+ cumulativeFundingPaymentPerLp: BN;
430
+ cumulativeFeePerLp: BN;
431
+ cumulativeNetBaseAssetAmountPerLp: BN;
432
+ userLpShares: BN;
292
433
  minimumQuoteAssetTradeSize: BN;
293
434
  baseAssetAmountStepSize: BN;
435
+ maxBaseAssetAmountRatio: number;
436
+ maxSlippageRatio: number;
294
437
  lastOraclePrice: BN;
295
438
  baseSpread: number;
296
439
  curveUpdateIntensity: number;
@@ -308,6 +451,10 @@ export declare type AMM = {
308
451
  longSpread: BN;
309
452
  shortSpread: BN;
310
453
  maxSpread: number;
454
+ marketPosition: UserPosition;
455
+ marketPositionPerLp: UserPosition;
456
+ maxBaseAssetReserve: BN;
457
+ minBaseAssetReserve: BN;
311
458
  };
312
459
  export declare type UserPosition = {
313
460
  baseAssetAmount: BN;
@@ -316,26 +463,44 @@ export declare type UserPosition = {
316
463
  quoteAssetAmount: BN;
317
464
  quoteEntryAmount: BN;
318
465
  openOrders: BN;
319
- unsettledPnl: BN;
320
466
  openBids: BN;
321
467
  openAsks: BN;
468
+ realizedPnl: BN;
469
+ lpShares: BN;
470
+ lastFeePerLp: BN;
471
+ lastNetBaseAssetAmountPerLp: BN;
472
+ lastNetQuoteAssetAmountPerLp: BN;
322
473
  };
323
- export declare type UserAccount = {
324
- authority: PublicKey;
325
- name: number[];
326
- userId: number;
327
- bankBalances: UserBankBalance[];
328
- collateral: BN;
329
- cumulativeDeposits: BN;
474
+ export declare type UserStatsAccount = {
475
+ numberOfUsers: number;
476
+ makerVolume30D: BN;
477
+ takerVolume30D: BN;
478
+ fillerVolume30D: BN;
479
+ lastMakerVolume30DTs: BN;
480
+ lastTakerVolume30DTs: BN;
481
+ lastFillerVolume30DTs: BN;
330
482
  fees: {
331
483
  totalFeePaid: BN;
332
484
  totalFeeRebate: BN;
333
485
  totalTokenDiscount: BN;
334
- totalReferralReward: BN;
335
486
  totalRefereeDiscount: BN;
336
487
  };
488
+ referrer: PublicKey;
489
+ isReferrer: boolean;
490
+ totalReferrerReward: BN;
491
+ authority: PublicKey;
492
+ };
493
+ export declare type UserAccount = {
494
+ authority: PublicKey;
495
+ name: number[];
496
+ userId: number;
497
+ bankBalances: UserBankBalance[];
337
498
  positions: UserPosition[];
338
499
  orders: Order[];
500
+ beingLiquidated: boolean;
501
+ bankrupt: boolean;
502
+ nextLiquidationId: number;
503
+ nextOrderId: BN;
339
504
  };
340
505
  export declare type UserBankBalance = {
341
506
  bankIndex: BN;
@@ -361,9 +526,7 @@ export declare type Order = {
361
526
  triggerPrice: BN;
362
527
  triggerCondition: OrderTriggerCondition;
363
528
  triggered: boolean;
364
- discountTier: OrderDiscountTier;
365
529
  existingPositionDirection: PositionDirection;
366
- referrer: PublicKey;
367
530
  postOnly: boolean;
368
531
  immediateOrCancel: boolean;
369
532
  oraclePriceOffset: BN;
@@ -375,7 +538,6 @@ export declare type OrderParams = {
375
538
  orderType: OrderType;
376
539
  userOrderId: number;
377
540
  direction: PositionDirection;
378
- quoteAssetAmount: BN;
379
541
  baseAssetAmount: BN;
380
542
  price: BN;
381
543
  marketIndex: BN;
@@ -393,10 +555,57 @@ export declare type OrderParams = {
393
555
  referrer: boolean;
394
556
  };
395
557
  };
558
+ export declare type NecessaryOrderParams = {
559
+ orderType: OrderType;
560
+ marketIndex: BN;
561
+ baseAssetAmount: BN;
562
+ direction: PositionDirection;
563
+ };
564
+ export declare type OptionalOrderParams = {
565
+ [Property in keyof OrderParams]?: OrderParams[Property];
566
+ } & NecessaryOrderParams;
567
+ export declare const DefaultOrderParams: {
568
+ orderType: {
569
+ market: {};
570
+ };
571
+ userOrderId: number;
572
+ direction: {
573
+ long: {};
574
+ };
575
+ baseAssetAmount: BN;
576
+ price: BN;
577
+ marketIndex: BN;
578
+ reduceOnly: boolean;
579
+ postOnly: boolean;
580
+ immediateOrCancel: boolean;
581
+ triggerPrice: BN;
582
+ triggerCondition: {
583
+ above: {};
584
+ };
585
+ positionLimit: BN;
586
+ oraclePriceOffset: BN;
587
+ padding0: BN;
588
+ padding1: BN;
589
+ optionalAccounts: {
590
+ discountToken: boolean;
591
+ referrer: boolean;
592
+ };
593
+ };
396
594
  export declare type MakerInfo = {
397
595
  maker: PublicKey;
596
+ makerStats: PublicKey;
597
+ order: Order;
598
+ };
599
+ export declare type TakerInfo = {
600
+ taker: PublicKey;
601
+ takerStats: PublicKey;
602
+ takerUserAccount: UserAccount;
398
603
  order: Order;
399
604
  };
605
+ export declare type ReferrerInfo = {
606
+ referrer: PublicKey;
607
+ referrerStats: PublicKey;
608
+ };
400
609
  export interface IWallet {
401
610
  signTransaction(tx: Transaction): Promise<Transaction>;
402
611
  signAllTransactions(txs: Transaction[]): Promise<Transaction[]>;
@@ -436,6 +645,7 @@ export declare type FeeStructure = {
436
645
  makerRebateNumerator: BN;
437
646
  makerRebateDenominator: BN;
438
647
  fillerRewardStructure: OrderFillerRewardStructure;
648
+ cancelOrderFee: BN;
439
649
  };
440
650
  export declare type OracleGuardRails = {
441
651
  priceDivergence: {
@@ -454,4 +664,4 @@ export declare type OrderFillerRewardStructure = {
454
664
  rewardDenominator: BN;
455
665
  timeBasedRewardLowerBound: BN;
456
666
  };
457
- export declare type MarginCategory = 'Initial' | 'Partial' | 'Maintenance';
667
+ 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;
@@ -51,6 +57,25 @@ OrderAction.CANCEL = { cancel: {} };
51
57
  OrderAction.EXPIRE = { expire: {} };
52
58
  OrderAction.FILL = { fill: {} };
53
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
+ };
54
79
  class OrderTriggerCondition {
55
80
  }
56
81
  exports.OrderTriggerCondition = OrderTriggerCondition;
@@ -72,3 +97,41 @@ var TradeSide;
72
97
  TradeSide[TradeSide["Buy"] = 1] = "Buy";
73
98
  TradeSide[TradeSide["Sell"] = 2] = "Sell";
74
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
+ LiquidationType.PERP_BANKRUPTCY = {
112
+ perpBankruptcy: {},
113
+ };
114
+ LiquidationType.BORROW_BANKRUPTCY = {
115
+ borrowBankruptcy: {},
116
+ };
117
+ exports.DefaultOrderParams = {
118
+ orderType: OrderType.MARKET,
119
+ userOrderId: 0,
120
+ direction: PositionDirection.LONG,
121
+ baseAssetAmount: _1.ZERO,
122
+ price: _1.ZERO,
123
+ marketIndex: _1.ZERO,
124
+ reduceOnly: false,
125
+ postOnly: false,
126
+ immediateOrCancel: false,
127
+ triggerPrice: _1.ZERO,
128
+ triggerCondition: OrderTriggerCondition.ABOVE,
129
+ positionLimit: _1.ZERO,
130
+ oraclePriceOffset: _1.ZERO,
131
+ padding0: _1.ZERO,
132
+ padding1: _1.ZERO,
133
+ optionalAccounts: {
134
+ discountToken: false,
135
+ referrer: false,
136
+ },
137
+ };