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

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 (152) 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 +727 -197
  17. package/lib/clearingHouseConfig.d.ts +1 -0
  18. package/lib/clearingHouseUser.d.ts +17 -17
  19. package/lib/clearingHouseUser.js +186 -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 +1609 -388
  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 +5 -2
  50. package/lib/math/orders.js +53 -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 +233 -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 +1224 -319
  80. package/src/clearingHouseConfig.ts +1 -0
  81. package/src/clearingHouseUser.ts +311 -148
  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/fetchLogs.js +50 -0
  94. package/src/events/pollingLogProvider.js +64 -0
  95. package/src/events/sort.js +44 -0
  96. package/src/events/txEventCache.js +71 -0
  97. package/src/events/types.ts +6 -0
  98. package/src/events/webSocketLogProvider.js +41 -0
  99. package/src/examples/makeTradeExample.js +80 -0
  100. package/src/factory/bigNum.js +390 -0
  101. package/src/factory/bigNum.ts +42 -13
  102. package/src/factory/oracleClient.js +20 -0
  103. package/src/idl/clearing_house.json +1609 -388
  104. package/src/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  105. package/src/index.ts +9 -3
  106. package/src/math/amm.ts +54 -55
  107. package/src/math/auction.js +42 -0
  108. package/src/math/auction.ts +5 -1
  109. package/src/math/bankBalance.ts +148 -2
  110. package/src/math/conversion.js +11 -0
  111. package/src/math/funding.js +248 -0
  112. package/src/math/margin.ts +124 -0
  113. package/src/math/market.ts +66 -1
  114. package/src/math/oracles.js +26 -0
  115. package/src/math/oracles.ts +42 -5
  116. package/src/math/orders.ts +112 -13
  117. package/src/math/position.ts +64 -9
  118. package/src/math/repeg.js +128 -0
  119. package/src/math/state.js +15 -0
  120. package/src/math/trade.js +253 -0
  121. package/src/math/trade.ts +23 -25
  122. package/src/math/utils.js +0 -1
  123. package/src/oracles/oracleClientCache.js +19 -0
  124. package/src/oracles/pythClient.js +46 -0
  125. package/src/oracles/quoteAssetOracleClient.js +32 -0
  126. package/src/oracles/switchboardClient.js +69 -0
  127. package/src/oracles/types.js +2 -0
  128. package/src/orderParams.js +20 -0
  129. package/src/orderParams.ts +20 -141
  130. package/src/slot/SlotSubscriber.js +39 -0
  131. package/src/slot/SlotSubscriber.ts +11 -1
  132. package/src/token/index.js +38 -0
  133. package/src/tokenFaucet.js +189 -0
  134. package/src/{mockUSDCFaucet.ts → tokenFaucet.ts} +82 -70
  135. package/src/tx/retryTxSender.ts +11 -3
  136. package/src/tx/types.js +2 -0
  137. package/src/tx/utils.js +17 -0
  138. package/src/tx/utils.ts +1 -1
  139. package/src/types.ts +236 -27
  140. package/src/userName.js +20 -0
  141. package/src/util/computeUnits.js +21 -11
  142. package/src/util/computeUnits.ts +1 -1
  143. package/src/util/getTokenAddress.js +9 -0
  144. package/src/util/getTokenAddress.ts +18 -0
  145. package/src/util/promiseTimeout.js +14 -0
  146. package/src/util/tps.js +27 -0
  147. package/src/wallet.js +35 -0
  148. package/tests/bn/test.ts +10 -0
  149. package/lib/orders.d.ts +0 -8
  150. package/lib/orders.js +0 -142
  151. package/src/orders.ts +0 -251
  152. 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;
@@ -238,9 +357,13 @@ export declare type MarketAccount = {
238
357
  openInterest: BN;
239
358
  marginRatioInitial: number;
240
359
  marginRatioMaintenance: number;
241
- marginRatioPartial: number;
242
360
  nextFillRecordId: BN;
243
361
  pnlPool: PoolBalance;
362
+ liquidationFee: BN;
363
+ imfFactor: BN;
364
+ unrealizedImfFactor: BN;
365
+ unrealizedInitialAssetWeight: number;
366
+ unrealizedMaintenanceAssetWeight: number;
244
367
  };
245
368
  export declare type BankAccount = {
246
369
  bankIndex: BN;
@@ -257,12 +380,19 @@ export declare type BankAccount = {
257
380
  cumulativeBorrowInterest: BN;
258
381
  depositBalance: BN;
259
382
  borrowBalance: BN;
260
- lastUpdated: BN;
383
+ lastInterestTs: BN;
384
+ lastTwapTs: BN;
261
385
  oracle: PublicKey;
262
386
  initialAssetWeight: BN;
263
387
  maintenanceAssetWeight: BN;
264
388
  initialLiabilityWeight: BN;
265
389
  maintenanceLiabilityWeight: BN;
390
+ liquidationFee: BN;
391
+ imfFactor: BN;
392
+ withdrawGuardThreshold: BN;
393
+ depositTokenTwap: BN;
394
+ borrowTokenTwap: BN;
395
+ utilizationTwap: BN;
266
396
  };
267
397
  export declare type PoolBalance = {
268
398
  balance: BN;
@@ -274,9 +404,13 @@ export declare type AMM = {
274
404
  lastFundingRate: BN;
275
405
  lastFundingRateTs: BN;
276
406
  lastMarkPriceTwap: BN;
407
+ lastMarkPriceTwap5min: BN;
277
408
  lastMarkPriceTwapTs: BN;
278
409
  lastOraclePriceTwap: BN;
410
+ lastOraclePriceTwap5min: BN;
279
411
  lastOraclePriceTwapTs: BN;
412
+ lastOracleMarkSpreadPct: BN;
413
+ lastOracleConfPct: BN;
280
414
  oracle: PublicKey;
281
415
  oracleSource: OracleSource;
282
416
  fundingPeriod: BN;
@@ -284,13 +418,20 @@ export declare type AMM = {
284
418
  pegMultiplier: BN;
285
419
  cumulativeFundingRateLong: BN;
286
420
  cumulativeFundingRateShort: BN;
421
+ cumulativeFundingRateLp: BN;
287
422
  cumulativeRepegRebateLong: BN;
288
423
  cumulativeRepegRebateShort: BN;
289
424
  totalFeeMinusDistributions: BN;
290
425
  totalFeeWithdrawn: BN;
291
426
  totalFee: BN;
427
+ cumulativeFundingPaymentPerLp: BN;
428
+ cumulativeFeePerLp: BN;
429
+ cumulativeNetBaseAssetAmountPerLp: BN;
430
+ userLpShares: BN;
292
431
  minimumQuoteAssetTradeSize: BN;
293
432
  baseAssetAmountStepSize: BN;
433
+ maxBaseAssetAmountRatio: number;
434
+ maxSlippageRatio: number;
294
435
  lastOraclePrice: BN;
295
436
  baseSpread: number;
296
437
  curveUpdateIntensity: number;
@@ -308,6 +449,10 @@ export declare type AMM = {
308
449
  longSpread: BN;
309
450
  shortSpread: BN;
310
451
  maxSpread: number;
452
+ marketPosition: UserPosition;
453
+ marketPositionPerLp: UserPosition;
454
+ maxBaseAssetReserve: BN;
455
+ minBaseAssetReserve: BN;
311
456
  };
312
457
  export declare type UserPosition = {
313
458
  baseAssetAmount: BN;
@@ -316,26 +461,44 @@ export declare type UserPosition = {
316
461
  quoteAssetAmount: BN;
317
462
  quoteEntryAmount: BN;
318
463
  openOrders: BN;
319
- unsettledPnl: BN;
320
464
  openBids: BN;
321
465
  openAsks: BN;
466
+ realizedPnl: BN;
467
+ lpShares: BN;
468
+ lastFeePerLp: BN;
469
+ lastNetBaseAssetAmountPerLp: BN;
470
+ lastNetQuoteAssetAmountPerLp: BN;
322
471
  };
323
- export declare type UserAccount = {
324
- authority: PublicKey;
325
- name: number[];
326
- userId: number;
327
- bankBalances: UserBankBalance[];
328
- collateral: BN;
329
- cumulativeDeposits: BN;
472
+ export declare type UserStatsAccount = {
473
+ numberOfUsers: number;
474
+ makerVolume30D: BN;
475
+ takerVolume30D: BN;
476
+ fillerVolume30D: BN;
477
+ lastMakerVolume30DTs: BN;
478
+ lastTakerVolume30DTs: BN;
479
+ lastFillerVolume30DTs: BN;
330
480
  fees: {
331
481
  totalFeePaid: BN;
332
482
  totalFeeRebate: BN;
333
483
  totalTokenDiscount: BN;
334
- totalReferralReward: BN;
335
484
  totalRefereeDiscount: BN;
336
485
  };
486
+ referrer: PublicKey;
487
+ isReferrer: boolean;
488
+ totalReferrerReward: BN;
489
+ authority: PublicKey;
490
+ };
491
+ export declare type UserAccount = {
492
+ authority: PublicKey;
493
+ name: number[];
494
+ userId: number;
495
+ bankBalances: UserBankBalance[];
337
496
  positions: UserPosition[];
338
497
  orders: Order[];
498
+ beingLiquidated: boolean;
499
+ bankrupt: boolean;
500
+ nextLiquidationId: number;
501
+ nextOrderId: BN;
339
502
  };
340
503
  export declare type UserBankBalance = {
341
504
  bankIndex: BN;
@@ -361,9 +524,7 @@ export declare type Order = {
361
524
  triggerPrice: BN;
362
525
  triggerCondition: OrderTriggerCondition;
363
526
  triggered: boolean;
364
- discountTier: OrderDiscountTier;
365
527
  existingPositionDirection: PositionDirection;
366
- referrer: PublicKey;
367
528
  postOnly: boolean;
368
529
  immediateOrCancel: boolean;
369
530
  oraclePriceOffset: BN;
@@ -375,7 +536,6 @@ export declare type OrderParams = {
375
536
  orderType: OrderType;
376
537
  userOrderId: number;
377
538
  direction: PositionDirection;
378
- quoteAssetAmount: BN;
379
539
  baseAssetAmount: BN;
380
540
  price: BN;
381
541
  marketIndex: BN;
@@ -393,10 +553,56 @@ export declare type OrderParams = {
393
553
  referrer: boolean;
394
554
  };
395
555
  };
556
+ export declare type NecessaryOrderParams = {
557
+ orderType: OrderType;
558
+ marketIndex: BN;
559
+ baseAssetAmount: BN;
560
+ direction: PositionDirection;
561
+ };
562
+ export declare type OptionalOrderParams = {
563
+ [Property in keyof OrderParams]?: OrderParams[Property];
564
+ } & NecessaryOrderParams;
565
+ export declare const DefaultOrderParams: {
566
+ orderType: {
567
+ market: {};
568
+ };
569
+ userOrderId: number;
570
+ direction: {
571
+ long: {};
572
+ };
573
+ baseAssetAmount: BN;
574
+ price: BN;
575
+ marketIndex: BN;
576
+ reduceOnly: boolean;
577
+ postOnly: boolean;
578
+ immediateOrCancel: boolean;
579
+ triggerPrice: BN;
580
+ triggerCondition: {
581
+ above: {};
582
+ };
583
+ positionLimit: BN;
584
+ oraclePriceOffset: BN;
585
+ padding0: BN;
586
+ padding1: BN;
587
+ optionalAccounts: {
588
+ discountToken: boolean;
589
+ referrer: boolean;
590
+ };
591
+ };
396
592
  export declare type MakerInfo = {
397
593
  maker: PublicKey;
594
+ makerStats: PublicKey;
595
+ order: Order;
596
+ };
597
+ export declare type TakerInfo = {
598
+ taker: PublicKey;
599
+ takerStats: PublicKey;
398
600
  order: Order;
399
601
  };
602
+ export declare type ReferrerInfo = {
603
+ referrer: PublicKey;
604
+ referrerStats: PublicKey;
605
+ };
400
606
  export interface IWallet {
401
607
  signTransaction(tx: Transaction): Promise<Transaction>;
402
608
  signAllTransactions(txs: Transaction[]): Promise<Transaction[]>;
@@ -436,6 +642,7 @@ export declare type FeeStructure = {
436
642
  makerRebateNumerator: BN;
437
643
  makerRebateDenominator: BN;
438
644
  fillerRewardStructure: OrderFillerRewardStructure;
645
+ cancelOrderFee: BN;
439
646
  };
440
647
  export declare type OracleGuardRails = {
441
648
  priceDivergence: {
@@ -454,4 +661,4 @@ export declare type OrderFillerRewardStructure = {
454
661
  rewardDenominator: BN;
455
662
  timeBasedRewardLowerBound: BN;
456
663
  };
457
- export declare type MarginCategory = 'Initial' | 'Partial' | 'Maintenance';
664
+ 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
+ };