@drift-labs/sdk 0.1.18-master.2 → 0.1.18-orders.0

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 (109) hide show
  1. package/lib/accounts/defaultClearingHouseAccountSubscriber.d.ts +7 -4
  2. package/lib/accounts/defaultClearingHouseAccountSubscriber.js +27 -2
  3. package/lib/accounts/defaultHistoryAccountSubscriber.d.ts +28 -0
  4. package/lib/accounts/defaultHistoryAccountSubscriber.js +110 -0
  5. package/lib/accounts/defaultUserAccountSubscriber.d.ts +3 -2
  6. package/lib/accounts/defaultUserAccountSubscriber.js +14 -3
  7. package/lib/accounts/types.d.ts +32 -6
  8. package/lib/accounts/webSocketAccountSubscriber.d.ts +0 -1
  9. package/lib/addresses.d.ts +4 -1
  10. package/lib/addresses.js +28 -1
  11. package/lib/admin.d.ts +10 -5
  12. package/lib/admin.js +53 -30
  13. package/lib/assert/assert.d.ts +0 -1
  14. package/lib/clearingHouse.d.ts +22 -3
  15. package/lib/clearingHouse.js +246 -15
  16. package/lib/clearingHouseUser.d.ts +10 -17
  17. package/lib/clearingHouseUser.js +111 -97
  18. package/lib/config.d.ts +0 -1
  19. package/lib/config.js +1 -1
  20. package/lib/constants/markets.d.ts +0 -1
  21. package/lib/constants/numericConstants.d.ts +0 -1
  22. package/lib/examples/makeTradeExample.d.ts +0 -1
  23. package/lib/examples/makeTradeExample.js +6 -6
  24. package/lib/idl/clearing_house.json +895 -132
  25. package/lib/index.d.ts +3 -1
  26. package/lib/index.js +3 -0
  27. package/lib/math/amm.d.ts +1 -1
  28. package/lib/math/amm.js +38 -15
  29. package/lib/math/conversion.d.ts +0 -1
  30. package/lib/math/conversion.js +1 -1
  31. package/lib/math/funding.d.ts +0 -1
  32. package/lib/math/funding.js +2 -2
  33. package/lib/math/insuranceFund.d.ts +0 -1
  34. package/lib/math/market.d.ts +2 -2
  35. package/lib/math/market.js +12 -2
  36. package/lib/math/orders.d.ts +3 -0
  37. package/lib/math/orders.js +30 -0
  38. package/lib/math/position.d.ts +4 -2
  39. package/lib/math/position.js +19 -5
  40. package/lib/math/trade.d.ts +0 -1
  41. package/lib/math/trade.js +16 -16
  42. package/lib/math/utils.d.ts +0 -1
  43. package/lib/mockUSDCFaucet.d.ts +0 -1
  44. package/lib/orderParams.d.ts +7 -0
  45. package/lib/orderParams.js +88 -0
  46. package/lib/orders.d.ts +5 -0
  47. package/lib/orders.js +136 -0
  48. package/lib/pythClient.d.ts +0 -1
  49. package/lib/pythClient.js +1 -1
  50. package/lib/tx/defaultTxSender.d.ts +0 -1
  51. package/lib/tx/types.d.ts +0 -1
  52. package/lib/tx/utils.d.ts +0 -1
  53. package/lib/types.d.ts +140 -7
  54. package/lib/types.js +36 -1
  55. package/lib/util/computeUnits.d.ts +0 -1
  56. package/lib/util/tps.d.ts +0 -1
  57. package/lib/wallet.d.ts +0 -1
  58. package/package.json +1 -1
  59. package/src/accounts/defaultClearingHouseAccountSubscriber.ts +52 -5
  60. package/src/accounts/defaultHistoryAccountSubscriber.ts +176 -0
  61. package/src/accounts/defaultUserAccountSubscriber.ts +31 -4
  62. package/src/accounts/types.ts +42 -5
  63. package/src/addresses.ts +35 -0
  64. package/src/admin.ts +86 -33
  65. package/src/clearingHouse.ts +340 -7
  66. package/src/clearingHouseUser.ts +154 -102
  67. package/src/config.ts +1 -1
  68. package/src/idl/clearing_house.json +895 -132
  69. package/src/index.ts +3 -0
  70. package/src/math/amm.ts +47 -14
  71. package/src/math/funding.ts +4 -3
  72. package/src/math/market.ts +28 -2
  73. package/src/math/orders.ts +39 -0
  74. package/src/math/position.ts +23 -3
  75. package/src/orderParams.ts +128 -0
  76. package/src/orders.ts +230 -0
  77. package/src/types.ts +124 -6
  78. package/tsconfig.json +0 -1
  79. package/lib/accounts/defaultClearingHouseAccountSubscriber.d.ts.map +0 -1
  80. package/lib/accounts/defaultUserAccountSubscriber.d.ts.map +0 -1
  81. package/lib/accounts/types.d.ts.map +0 -1
  82. package/lib/accounts/webSocketAccountSubscriber.d.ts.map +0 -1
  83. package/lib/addresses.d.ts.map +0 -1
  84. package/lib/admin.d.ts.map +0 -1
  85. package/lib/assert/assert.d.ts.map +0 -1
  86. package/lib/clearingHouse.d.ts.map +0 -1
  87. package/lib/clearingHouseUser.d.ts.map +0 -1
  88. package/lib/config.d.ts.map +0 -1
  89. package/lib/constants/markets.d.ts.map +0 -1
  90. package/lib/constants/numericConstants.d.ts.map +0 -1
  91. package/lib/examples/makeTradeExample.d.ts.map +0 -1
  92. package/lib/index.d.ts.map +0 -1
  93. package/lib/math/amm.d.ts.map +0 -1
  94. package/lib/math/conversion.d.ts.map +0 -1
  95. package/lib/math/funding.d.ts.map +0 -1
  96. package/lib/math/insuranceFund.d.ts.map +0 -1
  97. package/lib/math/market.d.ts.map +0 -1
  98. package/lib/math/position.d.ts.map +0 -1
  99. package/lib/math/trade.d.ts.map +0 -1
  100. package/lib/math/utils.d.ts.map +0 -1
  101. package/lib/mockUSDCFaucet.d.ts.map +0 -1
  102. package/lib/pythClient.d.ts.map +0 -1
  103. package/lib/tx/defaultTxSender.d.ts.map +0 -1
  104. package/lib/tx/types.d.ts.map +0 -1
  105. package/lib/tx/utils.d.ts.map +0 -1
  106. package/lib/types.d.ts.map +0 -1
  107. package/lib/util/computeUnits.d.ts.map +0 -1
  108. package/lib/util/tps.d.ts.map +0 -1
  109. package/lib/wallet.d.ts.map +0 -1
package/lib/admin.js CHANGED
@@ -69,7 +69,7 @@ class Admin extends clearingHouse_1.ClearingHouse {
69
69
  const tradeHistory = anchor.web3.Keypair.generate();
70
70
  const liquidationHistory = anchor.web3.Keypair.generate();
71
71
  const curveHistory = anchor.web3.Keypair.generate();
72
- const [clearingHouseStatePublicKey, clearingHouseNonce] = yield (0, addresses_1.getClearingHouseStateAccountPublicKeyAndNonce)(this.program.programId);
72
+ const [clearingHouseStatePublicKey, clearingHouseNonce] = yield addresses_1.getClearingHouseStateAccountPublicKeyAndNonce(this.program.programId);
73
73
  const initializeTx = yield this.program.transaction.initialize(clearingHouseNonce, collateralVaultNonce, insuranceVaultNonce, adminControlsPrices, {
74
74
  accounts: {
75
75
  admin: this.wallet.publicKey,
@@ -108,7 +108,7 @@ class Admin extends clearingHouse_1.ClearingHouse {
108
108
  yield this.program.account.tradeHistory.createInstruction(tradeHistory),
109
109
  yield this.program.account.liquidationHistory.createInstruction(liquidationHistory),
110
110
  yield this.program.account.depositHistory.createInstruction(depositHistory),
111
- yield this.program.account.extendedCurveHistory.createInstruction(curveHistory),
111
+ yield this.program.account.curveHistory.createInstruction(curveHistory),
112
112
  ],
113
113
  });
114
114
  const initializeHistoryTxSig = yield this.txSender.send(initializeHistoryTx, [
@@ -119,7 +119,29 @@ class Admin extends clearingHouse_1.ClearingHouse {
119
119
  fundingRateHistory,
120
120
  curveHistory,
121
121
  ], this.opts);
122
- return [initializeTxSig, initializeHistoryTxSig];
122
+ const initializeOrderStateTxSig = yield this.initializeOrderState();
123
+ return [initializeTxSig, initializeHistoryTxSig, initializeOrderStateTxSig];
124
+ });
125
+ }
126
+ initializeOrderState() {
127
+ return __awaiter(this, void 0, void 0, function* () {
128
+ const orderHistory = anchor.web3.Keypair.generate();
129
+ const [orderStatePublicKey, orderStateNonce] = yield addresses_1.getOrderStateAccountPublicKeyAndNonce(this.program.programId);
130
+ const clearingHouseStatePublicKey = yield addresses_1.getClearingHouseStateAccountPublicKey(this.program.programId);
131
+ const initializeOrderStateTx = yield this.program.transaction.initializeOrderState(orderStateNonce, {
132
+ accounts: {
133
+ admin: this.wallet.publicKey,
134
+ state: clearingHouseStatePublicKey,
135
+ orderHistory: orderHistory.publicKey,
136
+ orderState: orderStatePublicKey,
137
+ rent: web3_js_1.SYSVAR_RENT_PUBKEY,
138
+ systemProgram: anchor.web3.SystemProgram.programId,
139
+ },
140
+ instructions: [
141
+ yield this.program.account.orderHistory.createInstruction(orderHistory),
142
+ ],
143
+ });
144
+ return yield this.txSender.send(initializeOrderStateTx, [orderHistory], this.opts);
123
145
  });
124
146
  }
125
147
  initializeMarket(marketIndex, priceOracle, baseAssetReserve, quoteAssetReserve, periodicity, pegMultiplier = numericConstants_1.PEG_PRECISION) {
@@ -153,43 +175,21 @@ class Admin extends clearingHouse_1.ClearingHouse {
153
175
  updateK(sqrtK, marketIndex) {
154
176
  return __awaiter(this, void 0, void 0, function* () {
155
177
  const state = this.getStateAccount();
156
- const markets = this.getMarketsAccount();
157
- const marketData = markets.markets[marketIndex.toNumber()];
158
- const ammData = marketData.amm;
159
178
  return yield this.program.rpc.updateK(sqrtK, marketIndex, {
160
179
  accounts: {
161
180
  state: yield this.getStatePublicKey(),
162
181
  admin: this.wallet.publicKey,
163
182
  markets: state.markets,
164
- curveHistory: state.extendedCurveHistory,
165
- oracle: ammData.oracle,
166
- },
167
- });
168
- });
169
- }
170
- updateCurveHistory() {
171
- return __awaiter(this, void 0, void 0, function* () {
172
- const extendedCurveHistory = anchor.web3.Keypair.generate();
173
- const state = this.getStateAccount();
174
- return yield this.program.rpc.updateCurveHistory({
175
- accounts: {
176
- state: yield this.getStatePublicKey(),
177
- admin: this.wallet.publicKey,
178
183
  curveHistory: state.curveHistory,
179
- extendedCurveHistory: extendedCurveHistory.publicKey,
180
184
  },
181
- instructions: [
182
- yield this.program.account.extendedCurveHistory.createInstruction(extendedCurveHistory),
183
- ],
184
- signers: [extendedCurveHistory],
185
185
  });
186
186
  });
187
187
  }
188
188
  moveAmmToPrice(marketIndex, targetPrice) {
189
189
  return __awaiter(this, void 0, void 0, function* () {
190
190
  const market = this.getMarket(marketIndex);
191
- const [direction, tradeSize, _] = (0, trade_1.calculateTargetPriceTrade)(market, targetPrice);
192
- const [newQuoteAssetAmount, newBaseAssetAmount] = (0, amm_1.calculateAmmReservesAfterSwap)(market.amm, 'quote', tradeSize, (0, amm_1.getSwapDirection)('quote', direction));
191
+ const [direction, tradeSize, _] = trade_1.calculateTargetPriceTrade(market, targetPrice);
192
+ const [newQuoteAssetAmount, newBaseAssetAmount] = amm_1.calculateAmmReservesAfterSwap(market.amm, 'quote', tradeSize, amm_1.getSwapDirection('quote', direction));
193
193
  const state = this.getStateAccount();
194
194
  return yield this.program.rpc.moveAmmPrice(newBaseAssetAmount, newQuoteAssetAmount, marketIndex, {
195
195
  accounts: {
@@ -212,7 +212,7 @@ class Admin extends clearingHouse_1.ClearingHouse {
212
212
  admin: this.wallet.publicKey,
213
213
  oracle: ammData.oracle,
214
214
  markets: state.markets,
215
- curveHistory: state.extendedCurveHistory,
215
+ curveHistory: state.curveHistory,
216
216
  },
217
217
  });
218
218
  });
@@ -334,6 +334,17 @@ class Admin extends clearingHouse_1.ClearingHouse {
334
334
  });
335
335
  });
336
336
  }
337
+ updateOrderFillerRewardStructure(orderFillerRewardStructure) {
338
+ return __awaiter(this, void 0, void 0, function* () {
339
+ return yield this.program.rpc.updateOrderFillerRewardStructure(orderFillerRewardStructure, {
340
+ accounts: {
341
+ admin: this.wallet.publicKey,
342
+ state: yield this.getStatePublicKey(),
343
+ orderState: yield this.getOrderStatePublicKey(),
344
+ },
345
+ });
346
+ });
347
+ }
337
348
  updateFee(fees) {
338
349
  return __awaiter(this, void 0, void 0, function* () {
339
350
  return yield this.program.rpc.updateFee(fees, {
@@ -366,10 +377,22 @@ class Admin extends clearingHouse_1.ClearingHouse {
366
377
  });
367
378
  });
368
379
  }
369
- updateMarketMinimumTradeSize(marketIndex, minimumTradeSize) {
380
+ updateMarketMinimumQuoteAssetTradeSize(marketIndex, minimumTradeSize) {
381
+ return __awaiter(this, void 0, void 0, function* () {
382
+ const state = this.getStateAccount();
383
+ return yield this.program.rpc.updateMarketMinimumQuoteAssetTradeSize(marketIndex, minimumTradeSize, {
384
+ accounts: {
385
+ admin: this.wallet.publicKey,
386
+ state: yield this.getStatePublicKey(),
387
+ markets: state.markets,
388
+ },
389
+ });
390
+ });
391
+ }
392
+ updateMarketMinimumBaseAssetTradeSize(marketIndex, minimumTradeSize) {
370
393
  return __awaiter(this, void 0, void 0, function* () {
371
394
  const state = this.getStateAccount();
372
- return yield this.program.rpc.updateMarketMinimumTradeSize(marketIndex, minimumTradeSize, {
395
+ return yield this.program.rpc.updateMarketMinimumBaseAssetTradeSize(marketIndex, minimumTradeSize, {
373
396
  accounts: {
374
397
  admin: this.wallet.publicKey,
375
398
  state: yield this.getStatePublicKey(),
@@ -1,2 +1 @@
1
1
  export declare function assert(condition: boolean, error?: string): void;
2
- //# sourceMappingURL=assert.d.ts.map
@@ -1,7 +1,7 @@
1
1
  /// <reference types="node" />
2
2
  /// <reference types="bn.js" />
3
3
  import { BN, Program, Provider } from '@project-serum/anchor';
4
- import { MarketsAccount, StateAccount, DepositHistoryAccount, FundingPaymentHistoryAccount, FundingRateHistoryAccount, IWallet, LiquidationHistoryAccount, PositionDirection, TradeHistoryAccount, UserAccount, Market, ExtendedCurveHistoryAccount } from './types';
4
+ import { MarketsAccount, StateAccount, CurveHistoryAccount, DepositHistoryAccount, FundingPaymentHistoryAccount, FundingRateHistoryAccount, IWallet, LiquidationHistoryAccount, PositionDirection, TradeHistoryAccount, UserAccount, Market, OrderHistoryAccount, OrderStateAccount, OrderParams, Order } from './types';
5
5
  import { Connection, PublicKey, TransactionSignature, Keypair, ConfirmOptions, TransactionInstruction } from '@solana/web3.js';
6
6
  import { MockUSDCFaucet } from './mockUSDCFaucet';
7
7
  import { EventEmitter } from 'events';
@@ -56,7 +56,11 @@ export declare class ClearingHouse {
56
56
  getTradeHistoryAccount(): TradeHistoryAccount;
57
57
  getLiquidationHistoryAccount(): LiquidationHistoryAccount;
58
58
  getDepositHistoryAccount(): DepositHistoryAccount;
59
- getCurveHistoryAccount(): ExtendedCurveHistoryAccount;
59
+ getCurveHistoryAccount(): CurveHistoryAccount;
60
+ getOrderHistoryAccount(): OrderHistoryAccount;
61
+ orderStatePublicKey?: PublicKey;
62
+ getOrderStatePublicKey(): Promise<PublicKey>;
63
+ getOrderStateAccount(): OrderStateAccount;
60
64
  /**
61
65
  * Update the wallet to use for clearing house transactions and linked user account
62
66
  * @param newWallet
@@ -69,8 +73,10 @@ export declare class ClearingHouse {
69
73
  getInitializeUserInstructions(): Promise<[
70
74
  Keypair,
71
75
  PublicKey,
76
+ TransactionInstruction,
72
77
  TransactionInstruction
73
78
  ]>;
79
+ getInitializeUserOrdersInstruction(userAccountPublicKey?: PublicKey): Promise<TransactionInstruction>;
74
80
  userAccountPublicKey?: PublicKey;
75
81
  /**
76
82
  * Get the address for the Clearing House User's account. NOT the user's wallet address.
@@ -79,6 +85,12 @@ export declare class ClearingHouse {
79
85
  getUserAccountPublicKey(): Promise<PublicKey>;
80
86
  userAccount?: UserAccount;
81
87
  getUserAccount(): Promise<UserAccount>;
88
+ userOrdersAccountPublicKey?: PublicKey;
89
+ /**
90
+ * Get the address for the Clearing House User Order's account. NOT the user's wallet address.
91
+ * @returns
92
+ */
93
+ getUserOrdersAccountPublicKey(): Promise<PublicKey>;
82
94
  depositCollateral(amount: BN, collateralAccountPublicKey: PublicKey, userPositionsAccountPublicKey?: PublicKey): Promise<TransactionSignature>;
83
95
  getDepositCollateralInstruction(amount: BN, collateralAccountPublicKey: PublicKey, userPositionsAccountPublicKey?: PublicKey): Promise<TransactionInstruction>;
84
96
  /**
@@ -94,6 +106,14 @@ export declare class ClearingHouse {
94
106
  getWithdrawCollateralIx(amount: BN, collateralAccountPublicKey: PublicKey): Promise<TransactionInstruction>;
95
107
  openPosition(direction: PositionDirection, amount: BN, marketIndex: BN, limitPrice?: BN, discountToken?: PublicKey, referrer?: PublicKey): Promise<TransactionSignature>;
96
108
  getOpenPositionIx(direction: PositionDirection, amount: BN, marketIndex: BN, limitPrice?: BN, discountToken?: PublicKey, referrer?: PublicKey): Promise<TransactionInstruction>;
109
+ placeOrder(orderParams: OrderParams, discountToken?: PublicKey, referrer?: PublicKey): Promise<TransactionSignature>;
110
+ getPlaceOrderIx(orderParams: OrderParams, discountToken?: PublicKey, referrer?: PublicKey): Promise<TransactionInstruction>;
111
+ cancelOrder(orderId: BN): Promise<TransactionSignature>;
112
+ getCancelOrderIx(orderId: BN): Promise<TransactionInstruction>;
113
+ fillOrder(userAccountPublicKey: PublicKey, userOrdersAccountPublicKey: PublicKey, order: Order): Promise<TransactionSignature>;
114
+ getFillOrderIx(userAccountPublicKey: PublicKey, userOrdersAccountPublicKey: PublicKey, order: Order): Promise<TransactionInstruction>;
115
+ placeAndFillOrder(orderParams: OrderParams, discountToken?: PublicKey, referrer?: PublicKey): Promise<TransactionSignature>;
116
+ getPlaceAndFillOrderIx(orderParams: OrderParams, discountToken?: PublicKey, referrer?: PublicKey): Promise<TransactionInstruction>;
97
117
  /**
98
118
  * Close an entire position. If you want to reduce a position, use the {@link openPosition} method in the opposite direction of the current position.
99
119
  * @param marketIndex
@@ -111,4 +131,3 @@ export declare class ClearingHouse {
111
131
  getSettleFundingPaymentIx(userAccount: PublicKey, userPositionsAccount: PublicKey): Promise<TransactionInstruction>;
112
132
  triggerEvent(eventName: keyof ClearingHouseAccountEvents, data?: any): void;
113
133
  }
114
- //# sourceMappingURL=clearingHouse.d.ts.map
@@ -90,6 +90,7 @@ class ClearingHouse {
90
90
  'fundingRateHistoryAccount',
91
91
  'liquidationHistoryAccount',
92
92
  'tradeHistoryAccount',
93
+ 'orderHistoryAccount',
93
94
  ]);
94
95
  });
95
96
  }
@@ -115,7 +116,7 @@ class ClearingHouse {
115
116
  if (this.statePublicKey) {
116
117
  return this.statePublicKey;
117
118
  }
118
- this.statePublicKey = yield (0, addresses_1.getClearingHouseStateAccountPublicKey)(this.program.programId);
119
+ this.statePublicKey = yield addresses_1.getClearingHouseStateAccountPublicKey(this.program.programId);
119
120
  return this.statePublicKey;
120
121
  });
121
122
  }
@@ -149,6 +150,21 @@ class ClearingHouse {
149
150
  getCurveHistoryAccount() {
150
151
  return this.accountSubscriber.getCurveHistoryAccount();
151
152
  }
153
+ getOrderHistoryAccount() {
154
+ return this.accountSubscriber.getOrderHistoryAccount();
155
+ }
156
+ getOrderStatePublicKey() {
157
+ return __awaiter(this, void 0, void 0, function* () {
158
+ if (this.orderStatePublicKey) {
159
+ return this.orderStatePublicKey;
160
+ }
161
+ this.orderStatePublicKey = yield addresses_1.getOrderStateAccountPublicKey(this.program.programId);
162
+ return this.orderStatePublicKey;
163
+ });
164
+ }
165
+ getOrderStateAccount() {
166
+ return this.accountSubscriber.getOrderStateAccount();
167
+ }
152
168
  /**
153
169
  * Update the wallet to use for clearing house transactions and linked user account
154
170
  * @param newWallet
@@ -166,15 +182,17 @@ class ClearingHouse {
166
182
  }
167
183
  initializeUserAccount() {
168
184
  return __awaiter(this, void 0, void 0, function* () {
169
- const [userPositionsAccount, userAccountPublicKey, initializeUserAccountIx,] = yield this.getInitializeUserInstructions();
170
- const tx = new web3_js_1.Transaction().add(initializeUserAccountIx);
185
+ const [userPositionsAccount, userAccountPublicKey, initializeUserAccountIx, initializeUserOrdersAccountIx,] = yield this.getInitializeUserInstructions();
186
+ const tx = new web3_js_1.Transaction()
187
+ .add(initializeUserAccountIx)
188
+ .add(initializeUserOrdersAccountIx);
171
189
  const txSig = yield this.txSender.send(tx, [userPositionsAccount], this.opts);
172
190
  return [txSig, userAccountPublicKey];
173
191
  });
174
192
  }
175
193
  getInitializeUserInstructions() {
176
194
  return __awaiter(this, void 0, void 0, function* () {
177
- const [userPublicKey, userAccountNonce] = yield (0, addresses_1.getUserAccountPublicKeyAndNonce)(this.program.programId, this.wallet.publicKey);
195
+ const [userAccountPublicKey, userAccountNonce] = yield addresses_1.getUserAccountPublicKeyAndNonce(this.program.programId, this.wallet.publicKey);
178
196
  const remainingAccounts = [];
179
197
  const optionalAccounts = {
180
198
  whitelistToken: false,
@@ -192,7 +210,7 @@ class ClearingHouse {
192
210
  const userPositions = new web3_js_1.Keypair();
193
211
  const initializeUserAccountIx = yield this.program.instruction.initializeUser(userAccountNonce, optionalAccounts, {
194
212
  accounts: {
195
- user: userPublicKey,
213
+ user: userAccountPublicKey,
196
214
  authority: this.wallet.publicKey,
197
215
  rent: anchor.web3.SYSVAR_RENT_PUBKEY,
198
216
  systemProgram: anchor.web3.SystemProgram.programId,
@@ -201,7 +219,31 @@ class ClearingHouse {
201
219
  },
202
220
  remainingAccounts: remainingAccounts,
203
221
  });
204
- return [userPositions, userPublicKey, initializeUserAccountIx];
222
+ const initializeUserOrdersAccountIx = yield this.getInitializeUserOrdersInstruction(userAccountPublicKey);
223
+ return [
224
+ userPositions,
225
+ userAccountPublicKey,
226
+ initializeUserAccountIx,
227
+ initializeUserOrdersAccountIx,
228
+ ];
229
+ });
230
+ }
231
+ getInitializeUserOrdersInstruction(userAccountPublicKey) {
232
+ return __awaiter(this, void 0, void 0, function* () {
233
+ const [userOrdersAccountPublicKey, userOrdersAccountNonce] = yield addresses_1.getUserOrdersAccountPublicKeyAndNonce(this.program.programId, this.wallet.publicKey);
234
+ if (!userAccountPublicKey) {
235
+ userAccountPublicKey = yield this.getUserAccountPublicKey();
236
+ }
237
+ return yield this.program.instruction.initializeUserOrders(userOrdersAccountNonce, {
238
+ accounts: {
239
+ user: userAccountPublicKey,
240
+ authority: this.wallet.publicKey,
241
+ rent: anchor.web3.SYSVAR_RENT_PUBKEY,
242
+ systemProgram: anchor.web3.SystemProgram.programId,
243
+ userOrders: userOrdersAccountPublicKey,
244
+ state: yield this.getStatePublicKey(),
245
+ },
246
+ });
205
247
  });
206
248
  }
207
249
  /**
@@ -213,7 +255,7 @@ class ClearingHouse {
213
255
  if (this.userAccountPublicKey) {
214
256
  return this.userAccountPublicKey;
215
257
  }
216
- this.userAccountPublicKey = yield (0, addresses_1.getUserAccountPublicKey)(this.program.programId, this.wallet.publicKey);
258
+ this.userAccountPublicKey = yield addresses_1.getUserAccountPublicKey(this.program.programId, this.wallet.publicKey);
217
259
  return this.userAccountPublicKey;
218
260
  });
219
261
  }
@@ -226,6 +268,19 @@ class ClearingHouse {
226
268
  return this.userAccount;
227
269
  });
228
270
  }
271
+ /**
272
+ * Get the address for the Clearing House User Order's account. NOT the user's wallet address.
273
+ * @returns
274
+ */
275
+ getUserOrdersAccountPublicKey() {
276
+ return __awaiter(this, void 0, void 0, function* () {
277
+ if (this.userOrdersAccountPublicKey) {
278
+ return this.userOrdersAccountPublicKey;
279
+ }
280
+ this.userOrdersAccountPublicKey = yield addresses_1.getUserOrdersAccountPublicKey(this.program.programId, this.wallet.publicKey);
281
+ return this.userOrdersAccountPublicKey;
282
+ });
283
+ }
229
284
  depositCollateral(amount, collateralAccountPublicKey, userPositionsAccountPublicKey) {
230
285
  return __awaiter(this, void 0, void 0, function* () {
231
286
  const depositCollateralIx = yield this.getDepositCollateralInstruction(amount, collateralAccountPublicKey, userPositionsAccountPublicKey);
@@ -264,10 +319,11 @@ class ClearingHouse {
264
319
  */
265
320
  initializeUserAccountAndDepositCollateral(amount, collateralAccountPublicKey) {
266
321
  return __awaiter(this, void 0, void 0, function* () {
267
- const [userPositionsAccount, userAccountPublicKey, initializeUserAccountIx,] = yield this.getInitializeUserInstructions();
322
+ const [userPositionsAccount, userAccountPublicKey, initializeUserAccountIx, initializeUserOrdersAccountIx,] = yield this.getInitializeUserInstructions();
268
323
  const depositCollateralIx = yield this.getDepositCollateralInstruction(amount, collateralAccountPublicKey, userPositionsAccount.publicKey);
269
324
  const tx = new web3_js_1.Transaction()
270
325
  .add(initializeUserAccountIx)
326
+ .add(initializeUserOrdersAccountIx)
271
327
  .add(depositCollateralIx);
272
328
  const txSig = yield this.program.provider.send(tx, [userPositionsAccount]);
273
329
  return [txSig, userAccountPublicKey];
@@ -276,12 +332,13 @@ class ClearingHouse {
276
332
  initializeUserAccountForDevnet(mockUSDCFaucet, amount) {
277
333
  return __awaiter(this, void 0, void 0, function* () {
278
334
  const [associateTokenPublicKey, createAssociatedAccountIx, mintToIx] = yield mockUSDCFaucet.createAssociatedTokenAccountAndMintToInstructions(this.wallet.publicKey, amount);
279
- const [userPositionsAccount, userAccountPublicKey, initializeUserAccountIx,] = yield this.getInitializeUserInstructions();
335
+ const [userPositionsAccount, userAccountPublicKey, initializeUserAccountIx, initializeUserOrdersAccountIx,] = yield this.getInitializeUserInstructions();
280
336
  const depositCollateralIx = yield this.getDepositCollateralInstruction(amount, associateTokenPublicKey, userPositionsAccount.publicKey);
281
337
  const tx = new web3_js_1.Transaction()
282
338
  .add(createAssociatedAccountIx)
283
339
  .add(mintToIx)
284
340
  .add(initializeUserAccountIx)
341
+ .add(initializeUserOrdersAccountIx)
285
342
  .add(depositCollateralIx);
286
343
  const txSig = yield this.program.provider.send(tx, [userPositionsAccount]);
287
344
  return [txSig, userAccountPublicKey];
@@ -303,7 +360,7 @@ class ClearingHouse {
303
360
  }
304
361
  withdrawCollateral(amount, collateralAccountPublicKey) {
305
362
  return __awaiter(this, void 0, void 0, function* () {
306
- return this.txSender.send((0, utils_1.wrapInTx)(yield this.getWithdrawCollateralIx(amount, collateralAccountPublicKey)), [], this.opts);
363
+ return this.txSender.send(utils_1.wrapInTx(yield this.getWithdrawCollateralIx(amount, collateralAccountPublicKey)), [], this.opts);
307
364
  });
308
365
  }
309
366
  getWithdrawCollateralIx(amount, collateralAccountPublicKey) {
@@ -332,7 +389,7 @@ class ClearingHouse {
332
389
  }
333
390
  openPosition(direction, amount, marketIndex, limitPrice, discountToken, referrer) {
334
391
  return __awaiter(this, void 0, void 0, function* () {
335
- return yield this.txSender.send((0, utils_1.wrapInTx)(yield this.getOpenPositionIx(direction, amount, marketIndex, limitPrice, discountToken, referrer)), [], this.opts);
392
+ return yield this.txSender.send(utils_1.wrapInTx(yield this.getOpenPositionIx(direction, amount, marketIndex, limitPrice, discountToken, referrer)), [], this.opts);
336
393
  });
337
394
  }
338
395
  getOpenPositionIx(direction, amount, marketIndex, limitPrice, discountToken, referrer) {
@@ -381,6 +438,180 @@ class ClearingHouse {
381
438
  });
382
439
  });
383
440
  }
441
+ placeOrder(orderParams, discountToken, referrer) {
442
+ return __awaiter(this, void 0, void 0, function* () {
443
+ return yield this.txSender.send(utils_1.wrapInTx(yield this.getPlaceOrderIx(orderParams, discountToken, referrer)), [], this.opts);
444
+ });
445
+ }
446
+ getPlaceOrderIx(orderParams, discountToken, referrer) {
447
+ return __awaiter(this, void 0, void 0, function* () {
448
+ const userAccountPublicKey = yield this.getUserAccountPublicKey();
449
+ const userAccount = yield this.getUserAccount();
450
+ const priceOracle = this.getMarketsAccount().markets[orderParams.marketIndex.toNumber()].amm
451
+ .oracle;
452
+ const remainingAccounts = [];
453
+ if (orderParams.optionalAccounts.discountToken) {
454
+ if (!discountToken) {
455
+ throw Error('Optional accounts specified discount token but no discount token present');
456
+ }
457
+ remainingAccounts.push({
458
+ pubkey: discountToken,
459
+ isWritable: false,
460
+ isSigner: false,
461
+ });
462
+ }
463
+ if (orderParams.optionalAccounts.referrer) {
464
+ if (!referrer) {
465
+ throw Error('Optional accounts specified referrer but no referrer present');
466
+ }
467
+ remainingAccounts.push({
468
+ pubkey: referrer,
469
+ isWritable: false,
470
+ isSigner: false,
471
+ });
472
+ }
473
+ const state = this.getStateAccount();
474
+ const orderState = this.getOrderStateAccount();
475
+ return yield this.program.instruction.placeOrder(orderParams, {
476
+ accounts: {
477
+ state: yield this.getStatePublicKey(),
478
+ user: userAccountPublicKey,
479
+ authority: this.wallet.publicKey,
480
+ markets: state.markets,
481
+ userOrders: yield this.getUserOrdersAccountPublicKey(),
482
+ userPositions: userAccount.positions,
483
+ fundingPaymentHistory: state.fundingPaymentHistory,
484
+ fundingRateHistory: state.fundingRateHistory,
485
+ orderState: yield this.getOrderStatePublicKey(),
486
+ orderHistory: orderState.orderHistory,
487
+ oracle: priceOracle,
488
+ },
489
+ remainingAccounts,
490
+ });
491
+ });
492
+ }
493
+ cancelOrder(orderId) {
494
+ return __awaiter(this, void 0, void 0, function* () {
495
+ return yield this.txSender.send(utils_1.wrapInTx(yield this.getCancelOrderIx(orderId)), [], this.opts);
496
+ });
497
+ }
498
+ getCancelOrderIx(orderId) {
499
+ return __awaiter(this, void 0, void 0, function* () {
500
+ const userAccountPublicKey = yield this.getUserAccountPublicKey();
501
+ const userAccount = yield this.getUserAccount();
502
+ const state = this.getStateAccount();
503
+ const orderState = this.getOrderStateAccount();
504
+ return yield this.program.instruction.cancelOrder(orderId, {
505
+ accounts: {
506
+ state: yield this.getStatePublicKey(),
507
+ user: userAccountPublicKey,
508
+ authority: this.wallet.publicKey,
509
+ markets: state.markets,
510
+ userOrders: yield this.getUserOrdersAccountPublicKey(),
511
+ userPositions: userAccount.positions,
512
+ fundingPaymentHistory: state.fundingPaymentHistory,
513
+ fundingRateHistory: state.fundingRateHistory,
514
+ orderState: yield this.getOrderStatePublicKey(),
515
+ orderHistory: orderState.orderHistory,
516
+ },
517
+ });
518
+ });
519
+ }
520
+ fillOrder(userAccountPublicKey, userOrdersAccountPublicKey, order) {
521
+ return __awaiter(this, void 0, void 0, function* () {
522
+ return yield this.txSender.send(utils_1.wrapInTx(yield this.getFillOrderIx(userAccountPublicKey, userOrdersAccountPublicKey, order)), [], this.opts);
523
+ });
524
+ }
525
+ getFillOrderIx(userAccountPublicKey, userOrdersAccountPublicKey, order) {
526
+ return __awaiter(this, void 0, void 0, function* () {
527
+ const fillerPublicKey = yield this.getUserAccountPublicKey();
528
+ const userAccount = yield this.program.account.user.fetch(userAccountPublicKey);
529
+ const marketIndex = order.marketIndex;
530
+ const oracle = this.getMarket(marketIndex).amm.oracle;
531
+ const state = this.getStateAccount();
532
+ const orderState = this.getOrderStateAccount();
533
+ const remainingAccounts = [];
534
+ if (!order.referrer.equals(web3_js_1.PublicKey.default)) {
535
+ remainingAccounts.push({
536
+ pubkey: order.referrer,
537
+ isWritable: true,
538
+ isSigner: false,
539
+ });
540
+ }
541
+ const orderId = order.orderId;
542
+ return yield this.program.instruction.fillOrder(orderId, {
543
+ accounts: {
544
+ state: yield this.getStatePublicKey(),
545
+ filler: fillerPublicKey,
546
+ user: userAccountPublicKey,
547
+ authority: this.wallet.publicKey,
548
+ markets: state.markets,
549
+ userPositions: userAccount.positions,
550
+ userOrders: userOrdersAccountPublicKey,
551
+ tradeHistory: state.tradeHistory,
552
+ fundingPaymentHistory: state.fundingPaymentHistory,
553
+ fundingRateHistory: state.fundingRateHistory,
554
+ orderState: yield this.getOrderStatePublicKey(),
555
+ orderHistory: orderState.orderHistory,
556
+ oracle: oracle,
557
+ },
558
+ remainingAccounts,
559
+ });
560
+ });
561
+ }
562
+ placeAndFillOrder(orderParams, discountToken, referrer) {
563
+ return __awaiter(this, void 0, void 0, function* () {
564
+ return yield this.txSender.send(utils_1.wrapInTx(yield this.getPlaceAndFillOrderIx(orderParams, discountToken, referrer)), [], this.opts);
565
+ });
566
+ }
567
+ getPlaceAndFillOrderIx(orderParams, discountToken, referrer) {
568
+ return __awaiter(this, void 0, void 0, function* () {
569
+ const userAccountPublicKey = yield this.getUserAccountPublicKey();
570
+ const userAccount = yield this.getUserAccount();
571
+ const priceOracle = this.getMarketsAccount().markets[orderParams.marketIndex.toNumber()].amm
572
+ .oracle;
573
+ const remainingAccounts = [];
574
+ if (orderParams.optionalAccounts.discountToken) {
575
+ if (!discountToken) {
576
+ throw Error('Optional accounts specified discount token but no discount token present');
577
+ }
578
+ remainingAccounts.push({
579
+ pubkey: discountToken,
580
+ isWritable: false,
581
+ isSigner: false,
582
+ });
583
+ }
584
+ if (orderParams.optionalAccounts.referrer) {
585
+ if (!referrer) {
586
+ throw Error('Optional accounts specified referrer but no referrer present');
587
+ }
588
+ remainingAccounts.push({
589
+ pubkey: referrer,
590
+ isWritable: true,
591
+ isSigner: false,
592
+ });
593
+ }
594
+ const state = this.getStateAccount();
595
+ const orderState = this.getOrderStateAccount();
596
+ return yield this.program.instruction.placeAndFillOrder(orderParams, {
597
+ accounts: {
598
+ state: yield this.getStatePublicKey(),
599
+ user: userAccountPublicKey,
600
+ authority: this.wallet.publicKey,
601
+ markets: state.markets,
602
+ userOrders: yield this.getUserOrdersAccountPublicKey(),
603
+ userPositions: userAccount.positions,
604
+ tradeHistory: state.tradeHistory,
605
+ fundingPaymentHistory: state.fundingPaymentHistory,
606
+ fundingRateHistory: state.fundingRateHistory,
607
+ orderState: yield this.getOrderStatePublicKey(),
608
+ orderHistory: orderState.orderHistory,
609
+ oracle: priceOracle,
610
+ },
611
+ remainingAccounts,
612
+ });
613
+ });
614
+ }
384
615
  /**
385
616
  * Close an entire position. If you want to reduce a position, use the {@link openPosition} method in the opposite direction of the current position.
386
617
  * @param marketIndex
@@ -390,7 +621,7 @@ class ClearingHouse {
390
621
  */
391
622
  closePosition(marketIndex, discountToken, referrer) {
392
623
  return __awaiter(this, void 0, void 0, function* () {
393
- return yield this.txSender.send((0, utils_1.wrapInTx)(yield this.getClosePositionIx(marketIndex, discountToken, referrer)), [], this.opts);
624
+ return yield this.txSender.send(utils_1.wrapInTx(yield this.getClosePositionIx(marketIndex, discountToken, referrer)), [], this.opts);
394
625
  });
395
626
  }
396
627
  getClosePositionIx(marketIndex, discountToken, referrer) {
@@ -438,7 +669,7 @@ class ClearingHouse {
438
669
  }
439
670
  liquidate(liquidateeUserAccountPublicKey) {
440
671
  return __awaiter(this, void 0, void 0, function* () {
441
- return this.txSender.send((0, utils_1.wrapInTx)(yield this.getLiquidateIx(liquidateeUserAccountPublicKey)), [], this.opts);
672
+ return this.txSender.send(utils_1.wrapInTx(yield this.getLiquidateIx(liquidateeUserAccountPublicKey)), [], this.opts);
442
673
  });
443
674
  }
444
675
  getLiquidateIx(liquidateeUserAccountPublicKey) {
@@ -482,7 +713,7 @@ class ClearingHouse {
482
713
  }
483
714
  updateFundingRate(oracle, marketIndex) {
484
715
  return __awaiter(this, void 0, void 0, function* () {
485
- return this.txSender.send((0, utils_1.wrapInTx)(yield this.getUpdateFundingRateIx(oracle, marketIndex)), [], this.opts);
716
+ return this.txSender.send(utils_1.wrapInTx(yield this.getUpdateFundingRateIx(oracle, marketIndex)), [], this.opts);
486
717
  });
487
718
  }
488
719
  getUpdateFundingRateIx(oracle, marketIndex) {
@@ -500,7 +731,7 @@ class ClearingHouse {
500
731
  }
501
732
  settleFundingPayment(userAccount, userPositionsAccount) {
502
733
  return __awaiter(this, void 0, void 0, function* () {
503
- return this.txSender.send((0, utils_1.wrapInTx)(yield this.getSettleFundingPaymentIx(userAccount, userPositionsAccount)), [], this.opts);
734
+ return this.txSender.send(utils_1.wrapInTx(yield this.getSettleFundingPaymentIx(userAccount, userPositionsAccount)), [], this.opts);
504
735
  });
505
736
  }
506
737
  getSettleFundingPaymentIx(userAccount, userPositionsAccount) {
@@ -4,7 +4,7 @@ import BN from 'bn.js';
4
4
  import { EventEmitter } from 'events';
5
5
  import StrictEventEmitter from 'strict-event-emitter-types';
6
6
  import { ClearingHouse } from './clearingHouse';
7
- import { UserAccount, UserPosition, UserPositionsAccount } from './types';
7
+ import { Order, UserAccount, UserOrdersAccount, UserPosition, UserPositionsAccount } from './types';
8
8
  import { UserAccountSubscriber, UserAccountEvents } from './accounts/types';
9
9
  import { PositionDirection } from '.';
10
10
  export declare class ClearingHouseUser {
@@ -12,6 +12,7 @@ export declare class ClearingHouseUser {
12
12
  authority: PublicKey;
13
13
  accountSubscriber: UserAccountSubscriber;
14
14
  userAccountPublicKey?: PublicKey;
15
+ userOrdersAccountPublicKey?: PublicKey;
15
16
  isSubscribed: boolean;
16
17
  eventEmitter: StrictEventEmitter<EventEmitter, UserAccountEvents>;
17
18
  static from(clearingHouse: ClearingHouse, authority: PublicKey): ClearingHouseUser;
@@ -28,6 +29,7 @@ export declare class ClearingHouseUser {
28
29
  unsubscribe(): Promise<void>;
29
30
  getUserAccount(): UserAccount;
30
31
  getUserPositionsAccount(): UserPositionsAccount;
32
+ getUserOrdersAccount(): UserOrdersAccount;
31
33
  /**
32
34
  * Gets the user's current position for a given market. If the user has no position returns undefined
33
35
  * @param marketIndex
@@ -35,7 +37,13 @@ export declare class ClearingHouseUser {
35
37
  */
36
38
  getUserPosition(marketIndex: BN): UserPosition | undefined;
37
39
  getEmptyPosition(marketIndex: BN): UserPosition;
40
+ /**
41
+ * @param orderId
42
+ * @returns Order
43
+ */
44
+ getOrder(orderId: BN): Order | undefined;
38
45
  getUserAccountPublicKey(): Promise<PublicKey>;
46
+ getUserOrdersAccountPublicKey(): Promise<PublicKey>;
39
47
  exists(): Promise<boolean>;
40
48
  /**
41
49
  * calculates Buying Power = FC * MAX_LEVERAGE
@@ -125,21 +133,6 @@ export declare class ClearingHouseUser {
125
133
  liquidationPriceAfterClose(positionMarketIndex: BN, closeQuoteAmount: BN): BN;
126
134
  /**
127
135
  * Get the maximum trade size for a given market, taking into account the user's current leverage, positions, collateral, etc.
128
- *
129
- * To Calculate Max Quote Available:
130
- *
131
- * Case 1: SameSide
132
- * => Remaining quote to get to maxLeverage
133
- *
134
- * Case 2: NOT SameSide && currentLeverage <= maxLeverage
135
- * => Current opposite position x2 + remaining to get to maxLeverage
136
- *
137
- * Case 3: NOT SameSide && currentLeverage > maxLeverage && otherPositions - currentPosition > maxLeverage
138
- * => strictly reduce current position size
139
- *
140
- * Case 4: NOT SameSide && currentLeverage > maxLeverage && otherPositions - currentPosition < maxLeverage
141
- * => current position + remaining to get to maxLeverage
142
- *
143
136
  * @param marketIndex
144
137
  * @param tradeSide
145
138
  * @param userMaxLeverageSetting - leverage : Precision TEN_THOUSAND
@@ -166,5 +159,5 @@ export declare class ClearingHouseUser {
166
159
  * @returns positionValue : Precision QUOTE_PRECISION
167
160
  */
168
161
  private getTotalPositionValueExcludingMarket;
162
+ canFillOrder(order: Order): boolean;
169
163
  }
170
- //# sourceMappingURL=clearingHouseUser.d.ts.map