@drift-labs/sdk 0.1.18-orders.1 → 0.1.18
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.
- package/README.md +2 -1
- package/lib/accounts/defaultClearingHouseAccountSubscriber.d.ts +4 -7
- package/lib/accounts/defaultClearingHouseAccountSubscriber.d.ts.map +1 -0
- package/lib/accounts/defaultClearingHouseAccountSubscriber.js +1 -26
- package/lib/accounts/defaultUserAccountSubscriber.d.ts +2 -3
- package/lib/accounts/defaultUserAccountSubscriber.d.ts.map +1 -0
- package/lib/accounts/defaultUserAccountSubscriber.js +4 -13
- package/lib/accounts/types.d.ts +6 -32
- package/lib/accounts/types.d.ts.map +1 -0
- package/lib/accounts/webSocketAccountSubscriber.d.ts +1 -0
- package/lib/accounts/webSocketAccountSubscriber.d.ts.map +1 -0
- package/lib/addresses.d.ts +1 -4
- package/lib/addresses.d.ts.map +1 -0
- package/lib/addresses.js +1 -28
- package/lib/admin.d.ts +6 -10
- package/lib/admin.d.ts.map +1 -0
- package/lib/admin.js +44 -50
- package/lib/assert/assert.d.ts +1 -0
- package/lib/assert/assert.d.ts.map +1 -0
- package/lib/clearingHouse.d.ts +3 -22
- package/lib/clearingHouse.d.ts.map +1 -0
- package/lib/clearingHouse.js +7 -238
- package/lib/clearingHouseUser.d.ts +17 -10
- package/lib/clearingHouseUser.d.ts.map +1 -0
- package/lib/clearingHouseUser.js +84 -98
- package/lib/config.d.ts +1 -0
- package/lib/config.d.ts.map +1 -0
- package/lib/config.js +1 -1
- package/lib/constants/markets.d.ts +1 -0
- package/lib/constants/markets.d.ts.map +1 -0
- package/lib/constants/markets.js +16 -0
- package/lib/constants/numericConstants.d.ts +1 -0
- package/lib/constants/numericConstants.d.ts.map +1 -0
- package/lib/examples/makeTradeExample.d.ts +1 -0
- package/lib/examples/makeTradeExample.d.ts.map +1 -0
- package/lib/idl/clearing_house.json +233 -911
- package/lib/index.d.ts +1 -4
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +0 -4
- package/lib/math/amm.d.ts +1 -1
- package/lib/math/amm.d.ts.map +1 -0
- package/lib/math/amm.js +8 -31
- package/lib/math/conversion.d.ts +1 -0
- package/lib/math/conversion.d.ts.map +1 -0
- package/lib/math/funding.d.ts +1 -0
- package/lib/math/funding.d.ts.map +1 -0
- package/lib/math/funding.js +4 -1
- package/lib/math/insuranceFund.d.ts +1 -0
- package/lib/math/insuranceFund.d.ts.map +1 -0
- package/lib/math/market.d.ts +2 -2
- package/lib/math/market.d.ts.map +1 -0
- package/lib/math/market.js +1 -11
- package/lib/math/position.d.ts +2 -4
- package/lib/math/position.d.ts.map +1 -0
- package/lib/math/position.js +4 -18
- package/lib/math/trade.d.ts +1 -0
- package/lib/math/trade.d.ts.map +1 -0
- package/lib/math/utils.d.ts +1 -0
- package/lib/math/utils.d.ts.map +1 -0
- package/lib/mockUSDCFaucet.d.ts +1 -0
- package/lib/mockUSDCFaucet.d.ts.map +1 -0
- package/lib/pythClient.d.ts +1 -0
- package/lib/pythClient.d.ts.map +1 -0
- package/lib/tx/defaultTxSender.d.ts +1 -0
- package/lib/tx/defaultTxSender.d.ts.map +1 -0
- package/lib/tx/types.d.ts +1 -0
- package/lib/tx/types.d.ts.map +1 -0
- package/lib/tx/utils.d.ts +1 -0
- package/lib/tx/utils.d.ts.map +1 -0
- package/lib/types.d.ts +8 -140
- package/lib/types.d.ts.map +1 -0
- package/lib/types.js +1 -36
- package/lib/util/computeUnits.d.ts +1 -0
- package/lib/util/computeUnits.d.ts.map +1 -0
- package/lib/util/tps.d.ts +1 -0
- package/lib/util/tps.d.ts.map +1 -0
- package/lib/wallet.d.ts +1 -0
- package/lib/wallet.d.ts.map +1 -0
- package/package.json +1 -1
- package/src/accounts/defaultClearingHouseAccountSubscriber.ts +5 -52
- package/src/accounts/defaultUserAccountSubscriber.ts +6 -31
- package/src/accounts/types.ts +5 -42
- package/src/addresses.ts +0 -35
- package/src/admin.ts +52 -86
- package/src/clearingHouse.ts +7 -340
- package/src/clearingHouseUser.ts +102 -154
- package/src/config.ts +1 -1
- package/src/constants/markets.ts +16 -0
- package/src/idl/clearing_house.json +233 -911
- package/src/index.ts +0 -4
- package/src/math/amm.ts +14 -47
- package/src/math/funding.ts +5 -1
- package/src/math/market.ts +2 -28
- package/src/math/position.ts +3 -23
- package/src/types.ts +7 -124
- package/tsconfig.json +1 -0
- package/lib/accounts/defaultHistoryAccountSubscriber.d.ts +0 -28
- package/lib/accounts/defaultHistoryAccountSubscriber.js +0 -110
- package/lib/math/orders.d.ts +0 -3
- package/lib/math/orders.js +0 -30
- package/lib/orderParams.d.ts +0 -7
- package/lib/orderParams.js +0 -88
- package/lib/orders.d.ts +0 -5
- package/lib/orders.js +0 -136
- package/src/accounts/defaultHistoryAccountSubscriber.ts +0 -176
- package/src/math/orders.ts +0 -39
- package/src/orderParams.ts +0 -128
- package/src/orders.ts +0 -230
package/lib/clearingHouse.js
CHANGED
|
@@ -90,7 +90,6 @@ class ClearingHouse {
|
|
|
90
90
|
'fundingRateHistoryAccount',
|
|
91
91
|
'liquidationHistoryAccount',
|
|
92
92
|
'tradeHistoryAccount',
|
|
93
|
-
'orderHistoryAccount',
|
|
94
93
|
]);
|
|
95
94
|
});
|
|
96
95
|
}
|
|
@@ -150,21 +149,6 @@ class ClearingHouse {
|
|
|
150
149
|
getCurveHistoryAccount() {
|
|
151
150
|
return this.accountSubscriber.getCurveHistoryAccount();
|
|
152
151
|
}
|
|
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
|
-
}
|
|
168
152
|
/**
|
|
169
153
|
* Update the wallet to use for clearing house transactions and linked user account
|
|
170
154
|
* @param newWallet
|
|
@@ -182,17 +166,15 @@ class ClearingHouse {
|
|
|
182
166
|
}
|
|
183
167
|
initializeUserAccount() {
|
|
184
168
|
return __awaiter(this, void 0, void 0, function* () {
|
|
185
|
-
const [userPositionsAccount, userAccountPublicKey, initializeUserAccountIx,
|
|
186
|
-
const tx = new web3_js_1.Transaction()
|
|
187
|
-
.add(initializeUserAccountIx)
|
|
188
|
-
.add(initializeUserOrdersAccountIx);
|
|
169
|
+
const [userPositionsAccount, userAccountPublicKey, initializeUserAccountIx,] = yield this.getInitializeUserInstructions();
|
|
170
|
+
const tx = new web3_js_1.Transaction().add(initializeUserAccountIx);
|
|
189
171
|
const txSig = yield this.txSender.send(tx, [userPositionsAccount], this.opts);
|
|
190
172
|
return [txSig, userAccountPublicKey];
|
|
191
173
|
});
|
|
192
174
|
}
|
|
193
175
|
getInitializeUserInstructions() {
|
|
194
176
|
return __awaiter(this, void 0, void 0, function* () {
|
|
195
|
-
const [
|
|
177
|
+
const [userPublicKey, userAccountNonce] = yield addresses_1.getUserAccountPublicKeyAndNonce(this.program.programId, this.wallet.publicKey);
|
|
196
178
|
const remainingAccounts = [];
|
|
197
179
|
const optionalAccounts = {
|
|
198
180
|
whitelistToken: false,
|
|
@@ -210,7 +192,7 @@ class ClearingHouse {
|
|
|
210
192
|
const userPositions = new web3_js_1.Keypair();
|
|
211
193
|
const initializeUserAccountIx = yield this.program.instruction.initializeUser(userAccountNonce, optionalAccounts, {
|
|
212
194
|
accounts: {
|
|
213
|
-
user:
|
|
195
|
+
user: userPublicKey,
|
|
214
196
|
authority: this.wallet.publicKey,
|
|
215
197
|
rent: anchor.web3.SYSVAR_RENT_PUBKEY,
|
|
216
198
|
systemProgram: anchor.web3.SystemProgram.programId,
|
|
@@ -219,31 +201,7 @@ class ClearingHouse {
|
|
|
219
201
|
},
|
|
220
202
|
remainingAccounts: remainingAccounts,
|
|
221
203
|
});
|
|
222
|
-
|
|
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
|
-
});
|
|
204
|
+
return [userPositions, userPublicKey, initializeUserAccountIx];
|
|
247
205
|
});
|
|
248
206
|
}
|
|
249
207
|
/**
|
|
@@ -268,19 +226,6 @@ class ClearingHouse {
|
|
|
268
226
|
return this.userAccount;
|
|
269
227
|
});
|
|
270
228
|
}
|
|
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
|
-
}
|
|
284
229
|
depositCollateral(amount, collateralAccountPublicKey, userPositionsAccountPublicKey) {
|
|
285
230
|
return __awaiter(this, void 0, void 0, function* () {
|
|
286
231
|
const depositCollateralIx = yield this.getDepositCollateralInstruction(amount, collateralAccountPublicKey, userPositionsAccountPublicKey);
|
|
@@ -319,11 +264,10 @@ class ClearingHouse {
|
|
|
319
264
|
*/
|
|
320
265
|
initializeUserAccountAndDepositCollateral(amount, collateralAccountPublicKey) {
|
|
321
266
|
return __awaiter(this, void 0, void 0, function* () {
|
|
322
|
-
const [userPositionsAccount, userAccountPublicKey, initializeUserAccountIx,
|
|
267
|
+
const [userPositionsAccount, userAccountPublicKey, initializeUserAccountIx,] = yield this.getInitializeUserInstructions();
|
|
323
268
|
const depositCollateralIx = yield this.getDepositCollateralInstruction(amount, collateralAccountPublicKey, userPositionsAccount.publicKey);
|
|
324
269
|
const tx = new web3_js_1.Transaction()
|
|
325
270
|
.add(initializeUserAccountIx)
|
|
326
|
-
.add(initializeUserOrdersAccountIx)
|
|
327
271
|
.add(depositCollateralIx);
|
|
328
272
|
const txSig = yield this.program.provider.send(tx, [userPositionsAccount]);
|
|
329
273
|
return [txSig, userAccountPublicKey];
|
|
@@ -332,13 +276,12 @@ class ClearingHouse {
|
|
|
332
276
|
initializeUserAccountForDevnet(mockUSDCFaucet, amount) {
|
|
333
277
|
return __awaiter(this, void 0, void 0, function* () {
|
|
334
278
|
const [associateTokenPublicKey, createAssociatedAccountIx, mintToIx] = yield mockUSDCFaucet.createAssociatedTokenAccountAndMintToInstructions(this.wallet.publicKey, amount);
|
|
335
|
-
const [userPositionsAccount, userAccountPublicKey, initializeUserAccountIx,
|
|
279
|
+
const [userPositionsAccount, userAccountPublicKey, initializeUserAccountIx,] = yield this.getInitializeUserInstructions();
|
|
336
280
|
const depositCollateralIx = yield this.getDepositCollateralInstruction(amount, associateTokenPublicKey, userPositionsAccount.publicKey);
|
|
337
281
|
const tx = new web3_js_1.Transaction()
|
|
338
282
|
.add(createAssociatedAccountIx)
|
|
339
283
|
.add(mintToIx)
|
|
340
284
|
.add(initializeUserAccountIx)
|
|
341
|
-
.add(initializeUserOrdersAccountIx)
|
|
342
285
|
.add(depositCollateralIx);
|
|
343
286
|
const txSig = yield this.program.provider.send(tx, [userPositionsAccount]);
|
|
344
287
|
return [txSig, userAccountPublicKey];
|
|
@@ -438,180 +381,6 @@ class ClearingHouse {
|
|
|
438
381
|
});
|
|
439
382
|
});
|
|
440
383
|
}
|
|
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
|
-
}
|
|
615
384
|
/**
|
|
616
385
|
* Close an entire position. If you want to reduce a position, use the {@link openPosition} method in the opposite direction of the current position.
|
|
617
386
|
* @param marketIndex
|
|
@@ -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 {
|
|
7
|
+
import { UserAccount, UserPosition, UserPositionsAccount } from './types';
|
|
8
8
|
import { UserAccountSubscriber, UserAccountEvents } from './accounts/types';
|
|
9
9
|
import { PositionDirection } from '.';
|
|
10
10
|
export declare class ClearingHouseUser {
|
|
@@ -12,7 +12,6 @@ export declare class ClearingHouseUser {
|
|
|
12
12
|
authority: PublicKey;
|
|
13
13
|
accountSubscriber: UserAccountSubscriber;
|
|
14
14
|
userAccountPublicKey?: PublicKey;
|
|
15
|
-
userOrdersAccountPublicKey?: PublicKey;
|
|
16
15
|
isSubscribed: boolean;
|
|
17
16
|
eventEmitter: StrictEventEmitter<EventEmitter, UserAccountEvents>;
|
|
18
17
|
static from(clearingHouse: ClearingHouse, authority: PublicKey): ClearingHouseUser;
|
|
@@ -29,7 +28,6 @@ export declare class ClearingHouseUser {
|
|
|
29
28
|
unsubscribe(): Promise<void>;
|
|
30
29
|
getUserAccount(): UserAccount;
|
|
31
30
|
getUserPositionsAccount(): UserPositionsAccount;
|
|
32
|
-
getUserOrdersAccount(): UserOrdersAccount;
|
|
33
31
|
/**
|
|
34
32
|
* Gets the user's current position for a given market. If the user has no position returns undefined
|
|
35
33
|
* @param marketIndex
|
|
@@ -37,13 +35,7 @@ export declare class ClearingHouseUser {
|
|
|
37
35
|
*/
|
|
38
36
|
getUserPosition(marketIndex: BN): UserPosition | undefined;
|
|
39
37
|
getEmptyPosition(marketIndex: BN): UserPosition;
|
|
40
|
-
/**
|
|
41
|
-
* @param orderId
|
|
42
|
-
* @returns Order
|
|
43
|
-
*/
|
|
44
|
-
getOrder(orderId: BN): Order | undefined;
|
|
45
38
|
getUserAccountPublicKey(): Promise<PublicKey>;
|
|
46
|
-
getUserOrdersAccountPublicKey(): Promise<PublicKey>;
|
|
47
39
|
exists(): Promise<boolean>;
|
|
48
40
|
/**
|
|
49
41
|
* calculates Buying Power = FC * MAX_LEVERAGE
|
|
@@ -133,6 +125,21 @@ export declare class ClearingHouseUser {
|
|
|
133
125
|
liquidationPriceAfterClose(positionMarketIndex: BN, closeQuoteAmount: BN): BN;
|
|
134
126
|
/**
|
|
135
127
|
* 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
|
+
*
|
|
136
143
|
* @param marketIndex
|
|
137
144
|
* @param tradeSide
|
|
138
145
|
* @param userMaxLeverageSetting - leverage : Precision TEN_THOUSAND
|
|
@@ -159,5 +166,5 @@ export declare class ClearingHouseUser {
|
|
|
159
166
|
* @returns positionValue : Precision QUOTE_PRECISION
|
|
160
167
|
*/
|
|
161
168
|
private getTotalPositionValueExcludingMarket;
|
|
162
|
-
canFillOrder(order: Order): boolean;
|
|
163
169
|
}
|
|
170
|
+
//# sourceMappingURL=clearingHouseUser.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"clearingHouseUser.d.ts","sourceRoot":"","sources":["../src/clearingHouseUser.ts"],"names":[],"mappings":"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"}
|
package/lib/clearingHouseUser.js
CHANGED
|
@@ -63,9 +63,6 @@ class ClearingHouseUser {
|
|
|
63
63
|
getUserPositionsAccount() {
|
|
64
64
|
return this.accountSubscriber.getUserPositionsAccount();
|
|
65
65
|
}
|
|
66
|
-
getUserOrdersAccount() {
|
|
67
|
-
return this.accountSubscriber.getUserOrdersAccount();
|
|
68
|
-
}
|
|
69
66
|
/**
|
|
70
67
|
* Gets the user's current position for a given market. If the user has no position returns undefined
|
|
71
68
|
* @param marketIndex
|
|
@@ -80,16 +77,8 @@ class ClearingHouseUser {
|
|
|
80
77
|
lastCumulativeFundingRate: numericConstants_1.ZERO,
|
|
81
78
|
marketIndex,
|
|
82
79
|
quoteAssetAmount: numericConstants_1.ZERO,
|
|
83
|
-
openOrders: numericConstants_1.ZERO,
|
|
84
80
|
};
|
|
85
81
|
}
|
|
86
|
-
/**
|
|
87
|
-
* @param orderId
|
|
88
|
-
* @returns Order
|
|
89
|
-
*/
|
|
90
|
-
getOrder(orderId) {
|
|
91
|
-
return this.getUserOrdersAccount().orders.find((order) => order.orderId.eq(orderId));
|
|
92
|
-
}
|
|
93
82
|
getUserAccountPublicKey() {
|
|
94
83
|
return __awaiter(this, void 0, void 0, function* () {
|
|
95
84
|
if (this.userAccountPublicKey) {
|
|
@@ -99,15 +88,6 @@ class ClearingHouseUser {
|
|
|
99
88
|
return this.userAccountPublicKey;
|
|
100
89
|
});
|
|
101
90
|
}
|
|
102
|
-
getUserOrdersAccountPublicKey() {
|
|
103
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
104
|
-
if (this.userOrdersAccountPublicKey) {
|
|
105
|
-
return this.userOrdersAccountPublicKey;
|
|
106
|
-
}
|
|
107
|
-
this.userOrdersAccountPublicKey = yield _1.getUserOrdersAccountPublicKey(this.clearingHouse.program.programId, this.authority);
|
|
108
|
-
return this.userOrdersAccountPublicKey;
|
|
109
|
-
});
|
|
110
|
-
}
|
|
111
91
|
exists() {
|
|
112
92
|
return __awaiter(this, void 0, void 0, function* () {
|
|
113
93
|
const userAccountPublicKey = yield this.getUserAccountPublicKey();
|
|
@@ -333,7 +313,6 @@ class ClearingHouseUser {
|
|
|
333
313
|
baseAssetAmount: currentMarketPositionBaseSize.add(positionBaseSizeChange),
|
|
334
314
|
lastCumulativeFundingRate: new bn_js_1.default(0),
|
|
335
315
|
quoteAssetAmount: new bn_js_1.default(0),
|
|
336
|
-
openOrders: new bn_js_1.default(0),
|
|
337
316
|
};
|
|
338
317
|
const market = this.clearingHouse.getMarket(proposedMarketPosition.marketIndex);
|
|
339
318
|
const proposedMarketPositionValueUSDC = _1.calculateBaseAssetValue(market, proposedMarketPosition);
|
|
@@ -394,14 +373,14 @@ class ClearingHouseUser {
|
|
|
394
373
|
liquidationPrice(targetMarket, positionBaseSizeChange = numericConstants_1.ZERO, partial = false) {
|
|
395
374
|
// solves formula for example calc below
|
|
396
375
|
/* example: assume BTC price is $40k (examine 10% up/down)
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
376
|
+
|
|
377
|
+
if 10k deposit and levered 10x short BTC => BTC up $400 means:
|
|
378
|
+
1. higher base_asset_value (+$4k)
|
|
379
|
+
2. lower collateral (-$4k)
|
|
380
|
+
3. (10k - 4k)/(100k + 4k) => 6k/104k => .0576
|
|
381
|
+
|
|
382
|
+
for 10x long, BTC down $400:
|
|
383
|
+
3. (10k - 4k) / (100k - 4k) = 6k/96k => .0625 */
|
|
405
384
|
const tc = this.getTotalCollateral();
|
|
406
385
|
const tpv = this.getTotalPositionValue();
|
|
407
386
|
const partialLev = 16;
|
|
@@ -419,7 +398,6 @@ class ClearingHouseUser {
|
|
|
419
398
|
baseAssetAmount: proposedBaseAssetAmount,
|
|
420
399
|
lastCumulativeFundingRate: currentMarketPosition.lastCumulativeFundingRate,
|
|
421
400
|
quoteAssetAmount: new bn_js_1.default(0),
|
|
422
|
-
openOrders: new bn_js_1.default(0),
|
|
423
401
|
};
|
|
424
402
|
const market = this.clearingHouse.getMarket(proposedMarketPosition.marketIndex);
|
|
425
403
|
const proposedMarketPositionValueUSDC = _1.calculateBaseAssetValue(market, proposedMarketPosition);
|
|
@@ -496,32 +474,42 @@ class ClearingHouseUser {
|
|
|
496
474
|
}
|
|
497
475
|
/**
|
|
498
476
|
* Get the maximum trade size for a given market, taking into account the user's current leverage, positions, collateral, etc.
|
|
477
|
+
*
|
|
478
|
+
* To Calculate Max Quote Available:
|
|
479
|
+
*
|
|
480
|
+
* Case 1: SameSide
|
|
481
|
+
* => Remaining quote to get to maxLeverage
|
|
482
|
+
*
|
|
483
|
+
* Case 2: NOT SameSide && currentLeverage <= maxLeverage
|
|
484
|
+
* => Current opposite position x2 + remaining to get to maxLeverage
|
|
485
|
+
*
|
|
486
|
+
* Case 3: NOT SameSide && currentLeverage > maxLeverage && otherPositions - currentPosition > maxLeverage
|
|
487
|
+
* => strictly reduce current position size
|
|
488
|
+
*
|
|
489
|
+
* Case 4: NOT SameSide && currentLeverage > maxLeverage && otherPositions - currentPosition < maxLeverage
|
|
490
|
+
* => current position + remaining to get to maxLeverage
|
|
491
|
+
*
|
|
499
492
|
* @param marketIndex
|
|
500
493
|
* @param tradeSide
|
|
501
494
|
* @param userMaxLeverageSetting - leverage : Precision TEN_THOUSAND
|
|
502
495
|
* @returns tradeSizeAllowed : Precision QUOTE_PRECISION
|
|
503
496
|
*/
|
|
504
497
|
getMaxTradeSizeUSDC(targetMarketIndex, tradeSide, userMaxLeverageSetting) {
|
|
505
|
-
// inline function which get's the current position size on the opposite side of the target trade
|
|
506
|
-
const getOppositePositionValueUSDC = () => {
|
|
507
|
-
if (!currentPosition)
|
|
508
|
-
return numericConstants_1.ZERO;
|
|
509
|
-
const side = tradeSide === _1.PositionDirection.SHORT ? 'short' : 'long';
|
|
510
|
-
if (side === 'long' && (currentPosition === null || currentPosition === void 0 ? void 0 : currentPosition.baseAssetAmount.isNeg())) {
|
|
511
|
-
return this.getPositionValue(targetMarketIndex);
|
|
512
|
-
}
|
|
513
|
-
else if (side === 'short' &&
|
|
514
|
-
!(currentPosition === null || currentPosition === void 0 ? void 0 : currentPosition.baseAssetAmount.isNeg())) {
|
|
515
|
-
return this.getPositionValue(targetMarketIndex);
|
|
516
|
-
}
|
|
517
|
-
return numericConstants_1.ZERO;
|
|
518
|
-
};
|
|
519
498
|
const currentPosition = this.getUserPosition(targetMarketIndex) ||
|
|
520
499
|
this.getEmptyPosition(targetMarketIndex);
|
|
500
|
+
const targetSide = tradeSide === _1.PositionDirection.SHORT ? 'short' : 'long';
|
|
501
|
+
const currentPositionSide = (currentPosition === null || currentPosition === void 0 ? void 0 : currentPosition.baseAssetAmount.isNeg())
|
|
502
|
+
? 'short'
|
|
503
|
+
: 'long';
|
|
504
|
+
const targettingSameSide = !currentPosition
|
|
505
|
+
? true
|
|
506
|
+
: targetSide === currentPositionSide;
|
|
507
|
+
// add any position we have on the opposite side of the current trade, because we can "flip" the size of this position without taking any extra leverage.
|
|
508
|
+
const oppositeSizeValueUSDC = targettingSameSide
|
|
509
|
+
? numericConstants_1.ZERO
|
|
510
|
+
: this.getPositionValue(targetMarketIndex);
|
|
521
511
|
// get current leverage
|
|
522
512
|
const currentLeverage = this.getLeverage();
|
|
523
|
-
// remaining leverage
|
|
524
|
-
// let remainingLeverage = userMaxLeverageSetting;
|
|
525
513
|
const remainingLeverage = bn_js_1.default.max(userMaxLeverageSetting.sub(currentLeverage), numericConstants_1.ZERO);
|
|
526
514
|
// get total collateral
|
|
527
515
|
const totalCollateral = this.getTotalCollateral();
|
|
@@ -529,9 +517,43 @@ class ClearingHouseUser {
|
|
|
529
517
|
let maxPositionSize = remainingLeverage
|
|
530
518
|
.mul(totalCollateral)
|
|
531
519
|
.div(numericConstants_1.TEN_THOUSAND);
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
520
|
+
if (userMaxLeverageSetting.sub(currentLeverage).gte(numericConstants_1.ZERO)) {
|
|
521
|
+
if (oppositeSizeValueUSDC.eq(numericConstants_1.ZERO)) {
|
|
522
|
+
// case 1 : Regular trade where current total position less than max, and no opposite position to account for
|
|
523
|
+
// do nothing
|
|
524
|
+
}
|
|
525
|
+
else {
|
|
526
|
+
// case 2 : trade where current total position less than max, but need to account for flipping the current position over to the other side
|
|
527
|
+
maxPositionSize = maxPositionSize.add(oppositeSizeValueUSDC.mul(new bn_js_1.default(2)));
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
else {
|
|
531
|
+
// current leverage is greater than max leverage - can only reduce position size
|
|
532
|
+
if (!targettingSameSide) {
|
|
533
|
+
const currentPositionQuoteSize = this.getPositionValue(targetMarketIndex);
|
|
534
|
+
const currentTotalQuoteSize = currentLeverage
|
|
535
|
+
.mul(totalCollateral)
|
|
536
|
+
.div(numericConstants_1.TEN_THOUSAND);
|
|
537
|
+
const otherPositionsTotalQuoteSize = currentTotalQuoteSize.sub(currentPositionQuoteSize);
|
|
538
|
+
const quoteValueOfMaxLeverage = userMaxLeverageSetting
|
|
539
|
+
.mul(totalCollateral)
|
|
540
|
+
.div(numericConstants_1.TEN_THOUSAND);
|
|
541
|
+
if (otherPositionsTotalQuoteSize
|
|
542
|
+
.sub(currentPositionQuoteSize)
|
|
543
|
+
.gte(quoteValueOfMaxLeverage)) {
|
|
544
|
+
// case 3: Can only reduce the current position because it will still be greater than max leverage
|
|
545
|
+
maxPositionSize = currentPositionQuoteSize;
|
|
546
|
+
}
|
|
547
|
+
else {
|
|
548
|
+
// case 4: Can reduce the position, and then take extra remaining quote to get to max leverage
|
|
549
|
+
const allowedQuoteSizeAfterClosingCurrentPosition = quoteValueOfMaxLeverage.sub(otherPositionsTotalQuoteSize);
|
|
550
|
+
maxPositionSize = currentPositionQuoteSize.add(allowedQuoteSizeAfterClosingCurrentPosition);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
else {
|
|
554
|
+
// do nothing if targetting same side
|
|
555
|
+
}
|
|
556
|
+
}
|
|
535
557
|
// subtract oneMillionth of maxPositionSize
|
|
536
558
|
// => to avoid rounding errors when taking max leverage
|
|
537
559
|
const oneMilli = maxPositionSize.div(numericConstants_1.QUOTE_PRECISION);
|
|
@@ -560,12 +582,18 @@ class ClearingHouseUser {
|
|
|
560
582
|
.add(tradeQuoteAmount)
|
|
561
583
|
.abs();
|
|
562
584
|
const totalPositionAfterTradeExcludingTargetMarket = this.getTotalPositionValueExcludingMarket(targetMarketIndex);
|
|
563
|
-
const
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
585
|
+
const totalCollateral = this.getTotalCollateral();
|
|
586
|
+
if (totalCollateral.gt(numericConstants_1.ZERO)) {
|
|
587
|
+
const newLeverage = currentMarketPositionAfterTrade
|
|
588
|
+
.add(totalPositionAfterTradeExcludingTargetMarket)
|
|
589
|
+
.abs()
|
|
590
|
+
.mul(numericConstants_1.TEN_THOUSAND)
|
|
591
|
+
.div(totalCollateral);
|
|
592
|
+
return newLeverage;
|
|
593
|
+
}
|
|
594
|
+
else {
|
|
595
|
+
return new bn_js_1.default(0);
|
|
596
|
+
}
|
|
569
597
|
}
|
|
570
598
|
/**
|
|
571
599
|
* Calculates how much fee will be taken for a given sized trade
|
|
@@ -588,51 +616,9 @@ class ClearingHouseUser {
|
|
|
588
616
|
this.getEmptyPosition(marketToIgnore);
|
|
589
617
|
let currentMarketPositionValueUSDC = numericConstants_1.ZERO;
|
|
590
618
|
if (currentMarketPosition) {
|
|
591
|
-
|
|
592
|
-
currentMarketPositionValueUSDC = _1.calculateBaseAssetValue(market, currentMarketPosition);
|
|
619
|
+
currentMarketPositionValueUSDC = this.getPositionValue(marketToIgnore);
|
|
593
620
|
}
|
|
594
621
|
return this.getTotalPositionValue().sub(currentMarketPositionValueUSDC);
|
|
595
622
|
}
|
|
596
|
-
canFillOrder(order) {
|
|
597
|
-
const userAccount = this.getUserAccount();
|
|
598
|
-
const userPositionsAccount = this.getUserPositionsAccount();
|
|
599
|
-
const userPosition = this.getUserPosition(order.marketIndex);
|
|
600
|
-
const market = this.clearingHouse.getMarket(order.marketIndex);
|
|
601
|
-
if (position_1.isEmptyPosition(userPosition)) {
|
|
602
|
-
return false;
|
|
603
|
-
}
|
|
604
|
-
const newState = _1.calculateNewStateAfterOrder(userAccount, userPosition, market, order);
|
|
605
|
-
if (newState === null) {
|
|
606
|
-
return false;
|
|
607
|
-
}
|
|
608
|
-
const [userAccountAfter, userPositionAfter, marketAfter] = newState;
|
|
609
|
-
const totalPositionValue = userPositionsAccount.positions.reduce((positionValue, marketPosition) => {
|
|
610
|
-
let market = this.clearingHouse.getMarket(marketPosition.marketIndex);
|
|
611
|
-
if (marketPosition.marketIndex.eq(order.marketIndex)) {
|
|
612
|
-
market = marketAfter;
|
|
613
|
-
marketPosition = userPositionAfter;
|
|
614
|
-
}
|
|
615
|
-
return positionValue.add(_1.calculateBaseAssetValue(market, marketPosition));
|
|
616
|
-
}, numericConstants_1.ZERO);
|
|
617
|
-
if (totalPositionValue.eq(numericConstants_1.ZERO)) {
|
|
618
|
-
return true;
|
|
619
|
-
}
|
|
620
|
-
const unrealizedPnL = userPositionsAccount.positions.reduce((pnl, marketPosition) => {
|
|
621
|
-
let market = this.clearingHouse.getMarket(marketPosition.marketIndex);
|
|
622
|
-
pnl = pnl.add(_1.calculatePositionFundingPNL(market, marketPosition).div(numericConstants_1.PRICE_TO_QUOTE_PRECISION));
|
|
623
|
-
if (marketPosition.marketIndex.eq(order.marketIndex)) {
|
|
624
|
-
market = marketAfter;
|
|
625
|
-
marketPosition = userPositionAfter;
|
|
626
|
-
}
|
|
627
|
-
// update
|
|
628
|
-
return pnl.add(_1.calculatePositionPNL(market, marketPosition, false));
|
|
629
|
-
}, numericConstants_1.ZERO);
|
|
630
|
-
const totalCollateral = userAccountAfter.collateral.add(unrealizedPnL);
|
|
631
|
-
const marginRatioAfter = totalCollateral
|
|
632
|
-
.mul(numericConstants_1.TEN_THOUSAND)
|
|
633
|
-
.div(totalPositionValue);
|
|
634
|
-
const marginRatioInitial = this.clearingHouse.getStateAccount().marginRatioInitial;
|
|
635
|
-
return marginRatioAfter.gte(marginRatioInitial);
|
|
636
|
-
}
|
|
637
623
|
}
|
|
638
624
|
exports.ClearingHouseUser = ClearingHouseUser;
|
package/lib/config.d.ts
CHANGED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,aAAK,WAAW,GAAG;IAClB,GAAG,EAAE,QAAQ,CAAC;IACd,2BAA2B,EAAE,MAAM,CAAC;IACpC,yBAAyB,EAAE,MAAM,CAAC;IAClC,iBAAiB,EAAE,MAAM,CAAC;CAC1B,CAAC;AAEF,oBAAY,QAAQ,GAAG,QAAQ,GAAG,cAAc,CAAC;AAEjD,eAAO,MAAM,OAAO,EAAE;KAAG,GAAG,IAAI,QAAQ,GAAG,WAAW;CAarD,CAAC;AAIF,eAAO,MAAM,SAAS,QAAO,WAA4B,CAAC;AAE1D;;;;;;GAMG;AACH,eAAO,MAAM,UAAU,UAAW;IACjC,GAAG,EAAE,QAAQ,CAAC;IACd,WAAW,CAAC,EAAE,QAAQ,WAAW,CAAC,CAAC;CACnC,KAAG,WAQH,CAAC"}
|