@drift-labs/sdk 0.1.22 → 0.1.23-master.3
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/lib/accounts/bulkAccountLoader.js +2 -2
- package/lib/accounts/bulkUserSubscription.js +39 -1
- package/lib/accounts/pollingClearingHouseAccountSubscriber.js +3 -3
- package/lib/accounts/pollingTokenAccountSubscriber.js +2 -2
- package/lib/accounts/pollingUserAccountSubscriber.d.ts +2 -2
- package/lib/accounts/pollingUserAccountSubscriber.js +39 -18
- package/lib/accounts/types.d.ts +5 -0
- package/lib/accounts/webSocketAccountSubscriber.js +2 -2
- package/lib/accounts/webSocketClearingHouseAccountSubscriber.js +1 -1
- package/lib/accounts/webSocketUserAccountSubscriber.js +2 -2
- package/lib/admin.js +7 -7
- package/lib/clearingHouse.js +21 -22
- package/lib/clearingHouseUser.js +21 -21
- package/lib/examples/makeTradeExample.js +6 -6
- package/lib/idl/clearing_house.json +68 -0
- package/lib/index.d.ts +2 -0
- package/lib/index.js +2 -0
- package/lib/math/amm.js +12 -12
- package/lib/math/conversion.js +1 -1
- package/lib/math/funding.js +1 -1
- package/lib/math/market.js +2 -2
- package/lib/math/orders.d.ts +1 -0
- package/lib/math/orders.js +26 -4
- package/lib/math/position.js +4 -3
- package/lib/math/trade.js +21 -17
- package/lib/orders.d.ts +3 -1
- package/lib/orders.js +47 -19
- package/lib/pythClient.js +1 -1
- package/lib/tx/retryTxSender.d.ts +19 -0
- package/lib/tx/retryTxSender.js +153 -0
- package/lib/tx/types.d.ts +2 -0
- package/package.json +1 -1
- package/src/accounts/bulkUserSubscription.ts +51 -1
- package/src/accounts/pollingUserAccountSubscriber.ts +49 -30
- package/src/accounts/types.ts +6 -0
- package/src/clearingHouse.ts +3 -3
- package/src/idl/clearing_house.json +68 -0
- package/src/index.ts +2 -0
- package/src/math/orders.ts +33 -0
- package/src/math/position.ts +3 -2
- package/src/math/trade.ts +8 -3
- package/src/orders.ts +56 -3
- package/src/tx/retryTxSender.ts +196 -0
- package/src/tx/types.ts +3 -0
package/lib/clearingHouseUser.js
CHANGED
|
@@ -38,8 +38,8 @@ class ClearingHouseUser {
|
|
|
38
38
|
static from(clearingHouse, authority) {
|
|
39
39
|
if (clearingHouse.accountSubscriber.type !== 'websocket')
|
|
40
40
|
throw 'This method only works for clearing houses with a websocket account listener. Try using the getClearingHouseUser factory method to initialize a ClearingHouseUser instead';
|
|
41
|
-
const config = clearingHouseUser_1.getWebSocketClearingHouseUserConfig(clearingHouse, authority);
|
|
42
|
-
return clearingHouseUser_1.getClearingHouseUser(config);
|
|
41
|
+
const config = (0, clearingHouseUser_1.getWebSocketClearingHouseUserConfig)(clearingHouse, authority);
|
|
42
|
+
return (0, clearingHouseUser_1.getClearingHouseUser)(config);
|
|
43
43
|
}
|
|
44
44
|
/**
|
|
45
45
|
* Subscribe to ClearingHouseUser state accounts
|
|
@@ -112,7 +112,7 @@ class ClearingHouseUser {
|
|
|
112
112
|
if (this.userAccountPublicKey) {
|
|
113
113
|
return this.userAccountPublicKey;
|
|
114
114
|
}
|
|
115
|
-
this.userAccountPublicKey = yield addresses_1.getUserAccountPublicKey(this.clearingHouse.program.programId, this.authority);
|
|
115
|
+
this.userAccountPublicKey = yield (0, addresses_1.getUserAccountPublicKey)(this.clearingHouse.program.programId, this.authority);
|
|
116
116
|
return this.userAccountPublicKey;
|
|
117
117
|
});
|
|
118
118
|
}
|
|
@@ -121,7 +121,7 @@ class ClearingHouseUser {
|
|
|
121
121
|
if (this.userOrdersAccountPublicKey) {
|
|
122
122
|
return this.userOrdersAccountPublicKey;
|
|
123
123
|
}
|
|
124
|
-
this.userOrdersAccountPublicKey = yield _1.getUserOrdersAccountPublicKey(this.clearingHouse.program.programId, yield this.getUserAccountPublicKey());
|
|
124
|
+
this.userOrdersAccountPublicKey = yield (0, _1.getUserOrdersAccountPublicKey)(this.clearingHouse.program.programId, yield this.getUserAccountPublicKey());
|
|
125
125
|
return this.userOrdersAccountPublicKey;
|
|
126
126
|
});
|
|
127
127
|
}
|
|
@@ -159,7 +159,7 @@ class ClearingHouseUser {
|
|
|
159
159
|
.positions.filter((pos) => marketIndex ? pos.marketIndex === marketIndex : true)
|
|
160
160
|
.reduce((pnl, marketPosition) => {
|
|
161
161
|
const market = this.clearingHouse.getMarket(marketPosition.marketIndex);
|
|
162
|
-
return pnl.add(_1.calculatePositionPNL(market, marketPosition, withFunding));
|
|
162
|
+
return pnl.add((0, _1.calculatePositionPNL)(market, marketPosition, withFunding));
|
|
163
163
|
}, numericConstants_1.ZERO);
|
|
164
164
|
}
|
|
165
165
|
/**
|
|
@@ -171,7 +171,7 @@ class ClearingHouseUser {
|
|
|
171
171
|
.positions.filter((pos) => marketIndex ? pos.marketIndex === marketIndex : true)
|
|
172
172
|
.reduce((pnl, marketPosition) => {
|
|
173
173
|
const market = this.clearingHouse.getMarket(marketPosition.marketIndex);
|
|
174
|
-
return pnl.add(_1.calculatePositionFundingPNL(market, marketPosition));
|
|
174
|
+
return pnl.add((0, _1.calculatePositionFundingPNL)(market, marketPosition));
|
|
175
175
|
}, numericConstants_1.ZERO);
|
|
176
176
|
}
|
|
177
177
|
/**
|
|
@@ -189,7 +189,7 @@ class ClearingHouseUser {
|
|
|
189
189
|
getTotalPositionValue() {
|
|
190
190
|
return this.getUserPositionsAccount().positions.reduce((positionValue, marketPosition) => {
|
|
191
191
|
const market = this.clearingHouse.getMarket(marketPosition.marketIndex);
|
|
192
|
-
return positionValue.add(_1.calculateBaseAssetValue(market, marketPosition));
|
|
192
|
+
return positionValue.add((0, _1.calculateBaseAssetValue)(market, marketPosition));
|
|
193
193
|
}, numericConstants_1.ZERO);
|
|
194
194
|
}
|
|
195
195
|
/**
|
|
@@ -199,7 +199,7 @@ class ClearingHouseUser {
|
|
|
199
199
|
getPositionValue(marketIndex) {
|
|
200
200
|
const userPosition = this.getUserPosition(marketIndex) || this.getEmptyPosition(marketIndex);
|
|
201
201
|
const market = this.clearingHouse.getMarket(userPosition.marketIndex);
|
|
202
|
-
return _1.calculateBaseAssetValue(market, userPosition);
|
|
202
|
+
return (0, _1.calculateBaseAssetValue)(market, userPosition);
|
|
203
203
|
}
|
|
204
204
|
getPositionSide(currentPosition) {
|
|
205
205
|
if (currentPosition.baseAssetAmount.gt(numericConstants_1.ZERO)) {
|
|
@@ -218,10 +218,10 @@ class ClearingHouseUser {
|
|
|
218
218
|
*/
|
|
219
219
|
getPositionEstimatedExitPriceAndPnl(position, amountToClose) {
|
|
220
220
|
const market = this.clearingHouse.getMarket(position.marketIndex);
|
|
221
|
-
const entryPrice = position_1.calculateEntryPrice(position);
|
|
221
|
+
const entryPrice = (0, position_1.calculateEntryPrice)(position);
|
|
222
222
|
if (amountToClose) {
|
|
223
223
|
if (amountToClose.eq(numericConstants_1.ZERO)) {
|
|
224
|
-
return [_1.calculateMarkPrice(market), numericConstants_1.ZERO];
|
|
224
|
+
return [(0, _1.calculateMarkPrice)(market), numericConstants_1.ZERO];
|
|
225
225
|
}
|
|
226
226
|
position = {
|
|
227
227
|
baseAssetAmount: amountToClose,
|
|
@@ -230,7 +230,7 @@ class ClearingHouseUser {
|
|
|
230
230
|
quoteAssetAmount: position.quoteAssetAmount,
|
|
231
231
|
};
|
|
232
232
|
}
|
|
233
|
-
const baseAssetValue = _1.calculateBaseAssetValue(market, position);
|
|
233
|
+
const baseAssetValue = (0, _1.calculateBaseAssetValue)(market, position);
|
|
234
234
|
if (position.baseAssetAmount.eq(numericConstants_1.ZERO)) {
|
|
235
235
|
return [numericConstants_1.ZERO, numericConstants_1.ZERO];
|
|
236
236
|
}
|
|
@@ -337,7 +337,7 @@ class ClearingHouseUser {
|
|
|
337
337
|
|
|
338
338
|
for 10x long, BTC down $400:
|
|
339
339
|
3. (10k - 4k) / (100k - 4k) = 6k/96k => .0625 */
|
|
340
|
-
const currentPrice = _1.calculateMarkPrice(this.clearingHouse.getMarket(targetMarket.marketIndex));
|
|
340
|
+
const currentPrice = (0, _1.calculateMarkPrice)(this.clearingHouse.getMarket(targetMarket.marketIndex));
|
|
341
341
|
const totalCollateralUSDC = this.getTotalCollateral();
|
|
342
342
|
// calculate the total position value ignoring any value from the target market of the trade
|
|
343
343
|
const totalCurrentPositionValueIgnoringTargetUSDC = this.getTotalPositionValueExcludingMarket(targetMarket.marketIndex);
|
|
@@ -353,7 +353,7 @@ class ClearingHouseUser {
|
|
|
353
353
|
openOrders: new _1.BN(0),
|
|
354
354
|
};
|
|
355
355
|
const market = this.clearingHouse.getMarket(proposedMarketPosition.marketIndex);
|
|
356
|
-
const proposedMarketPositionValueUSDC = _1.calculateBaseAssetValue(market, proposedMarketPosition);
|
|
356
|
+
const proposedMarketPositionValueUSDC = (0, _1.calculateBaseAssetValue)(market, proposedMarketPosition);
|
|
357
357
|
// total position value after trade
|
|
358
358
|
const targetTotalPositionValueUSDC = totalCurrentPositionValueIgnoringTargetUSDC.add(proposedMarketPositionValueUSDC);
|
|
359
359
|
let totalFreeCollateralUSDC = this.getTotalCollateral().sub(this.getTotalPositionValue()
|
|
@@ -439,7 +439,7 @@ class ClearingHouseUser {
|
|
|
439
439
|
openOrders: new _1.BN(0),
|
|
440
440
|
};
|
|
441
441
|
const market = this.clearingHouse.getMarket(proposedMarketPosition.marketIndex);
|
|
442
|
-
const proposedMarketPositionValueUSDC = _1.calculateBaseAssetValue(market, proposedMarketPosition);
|
|
442
|
+
const proposedMarketPositionValueUSDC = (0, _1.calculateBaseAssetValue)(market, proposedMarketPosition);
|
|
443
443
|
// total position value after trade
|
|
444
444
|
const targetTotalPositionValueUSDC = totalCurrentPositionValueIgnoringTargetUSDC.add(proposedMarketPositionValueUSDC);
|
|
445
445
|
let totalFreeCollateralUSDC = tc.sub(totalCurrentPositionValueIgnoringTargetUSDC
|
|
@@ -467,13 +467,13 @@ class ClearingHouseUser {
|
|
|
467
467
|
}
|
|
468
468
|
let currentPrice;
|
|
469
469
|
if (positionBaseSizeChange.eq(numericConstants_1.ZERO)) {
|
|
470
|
-
currentPrice = _1.calculateMarkPrice(this.clearingHouse.getMarket(targetMarket.marketIndex));
|
|
470
|
+
currentPrice = (0, _1.calculateMarkPrice)(this.clearingHouse.getMarket(targetMarket.marketIndex));
|
|
471
471
|
}
|
|
472
472
|
else {
|
|
473
473
|
const direction = positionBaseSizeChange.gt(numericConstants_1.ZERO)
|
|
474
474
|
? _1.PositionDirection.LONG
|
|
475
475
|
: _1.PositionDirection.SHORT;
|
|
476
|
-
currentPrice = _1.calculateTradeSlippage(direction, positionBaseSizeChange.abs(), this.clearingHouse.getMarket(targetMarket.marketIndex), 'base')[3]; // newPrice after swap
|
|
476
|
+
currentPrice = (0, _1.calculateTradeSlippage)(direction, positionBaseSizeChange.abs(), this.clearingHouse.getMarket(targetMarket.marketIndex), 'base')[3]; // newPrice after swap
|
|
477
477
|
}
|
|
478
478
|
// if the position value after the trade is less than total collateral, there is no liq price
|
|
479
479
|
if (targetTotalPositionValueUSDC.lte(totalFreeCollateralUSDC) &&
|
|
@@ -664,10 +664,10 @@ class ClearingHouseUser {
|
|
|
664
664
|
const userPositionsAccount = this.getUserPositionsAccount();
|
|
665
665
|
const userPosition = this.getUserPosition(order.marketIndex);
|
|
666
666
|
const market = this.clearingHouse.getMarket(order.marketIndex);
|
|
667
|
-
if (position_1.isEmptyPosition(userPosition)) {
|
|
667
|
+
if ((0, position_1.isEmptyPosition)(userPosition)) {
|
|
668
668
|
return false;
|
|
669
669
|
}
|
|
670
|
-
const newState = _1.calculateNewStateAfterOrder(userAccount, userPosition, market, order);
|
|
670
|
+
const newState = (0, _1.calculateNewStateAfterOrder)(userAccount, userPosition, market, order);
|
|
671
671
|
if (newState === null) {
|
|
672
672
|
return false;
|
|
673
673
|
}
|
|
@@ -678,20 +678,20 @@ class ClearingHouseUser {
|
|
|
678
678
|
market = marketAfter;
|
|
679
679
|
marketPosition = userPositionAfter;
|
|
680
680
|
}
|
|
681
|
-
return positionValue.add(_1.calculateBaseAssetValue(market, marketPosition));
|
|
681
|
+
return positionValue.add((0, _1.calculateBaseAssetValue)(market, marketPosition));
|
|
682
682
|
}, numericConstants_1.ZERO);
|
|
683
683
|
if (totalPositionValue.eq(numericConstants_1.ZERO)) {
|
|
684
684
|
return true;
|
|
685
685
|
}
|
|
686
686
|
const unrealizedPnL = userPositionsAccount.positions.reduce((pnl, marketPosition) => {
|
|
687
687
|
let market = this.clearingHouse.getMarket(marketPosition.marketIndex);
|
|
688
|
-
pnl = pnl.add(_1.calculatePositionFundingPNL(market, marketPosition).div(numericConstants_1.PRICE_TO_QUOTE_PRECISION));
|
|
688
|
+
pnl = pnl.add((0, _1.calculatePositionFundingPNL)(market, marketPosition).div(numericConstants_1.PRICE_TO_QUOTE_PRECISION));
|
|
689
689
|
if (marketPosition.marketIndex.eq(order.marketIndex)) {
|
|
690
690
|
market = marketAfter;
|
|
691
691
|
marketPosition = userPositionAfter;
|
|
692
692
|
}
|
|
693
693
|
// update
|
|
694
|
-
return pnl.add(_1.calculatePositionPNL(market, marketPosition, false));
|
|
694
|
+
return pnl.add((0, _1.calculatePositionPNL)(market, marketPosition, false));
|
|
695
695
|
}, numericConstants_1.ZERO);
|
|
696
696
|
const totalCollateral = userAccountAfter.collateral.add(unrealizedPnL);
|
|
697
697
|
const marginRatioAfter = totalCollateral
|
|
@@ -21,7 +21,7 @@ const getTokenAddress = (mintAddress, userPubKey) => {
|
|
|
21
21
|
exports.getTokenAddress = getTokenAddress;
|
|
22
22
|
const main = () => __awaiter(void 0, void 0, void 0, function* () {
|
|
23
23
|
// Initialize Drift SDK
|
|
24
|
-
const sdkConfig = __2.initialize({ env: 'devnet' });
|
|
24
|
+
const sdkConfig = (0, __2.initialize)({ env: 'devnet' });
|
|
25
25
|
// Set up the Wallet and Provider
|
|
26
26
|
const privateKey = process.env.BOT_PRIVATE_KEY; // stored as an array string
|
|
27
27
|
const keypair = web3_js_1.Keypair.fromSecretKey(Uint8Array.from(JSON.parse(privateKey)));
|
|
@@ -35,7 +35,7 @@ const main = () => __awaiter(void 0, void 0, void 0, function* () {
|
|
|
35
35
|
const lamportsBalance = yield connection.getBalance(wallet.publicKey);
|
|
36
36
|
console.log('SOL balance:', lamportsBalance / Math.pow(10, 9));
|
|
37
37
|
// Misc. other things to set up
|
|
38
|
-
const usdcTokenAddress = yield exports.getTokenAddress(sdkConfig.USDC_MINT_ADDRESS, wallet.publicKey.toString());
|
|
38
|
+
const usdcTokenAddress = yield (0, exports.getTokenAddress)(sdkConfig.USDC_MINT_ADDRESS, wallet.publicKey.toString());
|
|
39
39
|
// Set up the Drift Clearing House
|
|
40
40
|
const clearingHousePublicKey = new web3_js_1.PublicKey(sdkConfig.CLEARING_HOUSE_PROGRAM_ID);
|
|
41
41
|
const clearingHouse = __2.ClearingHouse.from(connection, provider.wallet, clearingHousePublicKey);
|
|
@@ -47,18 +47,18 @@ const main = () => __awaiter(void 0, void 0, void 0, function* () {
|
|
|
47
47
|
if (!userAccountExists) {
|
|
48
48
|
//// Create a Clearing House account by Depositing some USDC ($10,000 in this case)
|
|
49
49
|
const depositAmount = new anchor_1.BN(10000).mul(__2.QUOTE_PRECISION);
|
|
50
|
-
yield clearingHouse.initializeUserAccountAndDepositCollateral(depositAmount, yield exports.getTokenAddress(usdcTokenAddress.toString(), wallet.publicKey.toString()));
|
|
50
|
+
yield clearingHouse.initializeUserAccountAndDepositCollateral(depositAmount, yield (0, exports.getTokenAddress)(usdcTokenAddress.toString(), wallet.publicKey.toString()));
|
|
51
51
|
}
|
|
52
52
|
yield user.subscribe();
|
|
53
53
|
// Get current price
|
|
54
54
|
const solMarketInfo = __2.Markets.find((market) => market.baseAssetSymbol === 'SOL');
|
|
55
|
-
const currentMarketPrice = __2.calculateMarkPrice(clearingHouse.getMarket(solMarketInfo.marketIndex));
|
|
56
|
-
const formattedPrice = __2.convertToNumber(currentMarketPrice, __2.MARK_PRICE_PRECISION);
|
|
55
|
+
const currentMarketPrice = (0, __2.calculateMarkPrice)(clearingHouse.getMarket(solMarketInfo.marketIndex));
|
|
56
|
+
const formattedPrice = (0, __2.convertToNumber)(currentMarketPrice, __2.MARK_PRICE_PRECISION);
|
|
57
57
|
console.log(`Current Market Price is $${formattedPrice}`);
|
|
58
58
|
// Estimate the slippage for a $5000 LONG trade
|
|
59
59
|
const solMarketAccount = clearingHouse.getMarket(solMarketInfo.marketIndex);
|
|
60
60
|
const longAmount = new anchor_1.BN(5000).mul(__2.QUOTE_PRECISION);
|
|
61
|
-
const slippage = __2.convertToNumber(__2.calculateTradeSlippage(__2.PositionDirection.LONG, longAmount, solMarketAccount)[0], __2.MARK_PRICE_PRECISION);
|
|
61
|
+
const slippage = (0, __2.convertToNumber)((0, __2.calculateTradeSlippage)(__2.PositionDirection.LONG, longAmount, solMarketAccount)[0], __2.MARK_PRICE_PRECISION);
|
|
62
62
|
console.log(`Slippage for a $5000 LONG on the SOL market would be $${slippage}`);
|
|
63
63
|
// Make a $5000 LONG trade
|
|
64
64
|
yield clearingHouse.openPosition(__2.PositionDirection.LONG, longAmount, solMarketInfo.marketIndex);
|
|
@@ -1321,6 +1321,52 @@
|
|
|
1321
1321
|
}
|
|
1322
1322
|
]
|
|
1323
1323
|
},
|
|
1324
|
+
{
|
|
1325
|
+
"name": "initializeUserOrdersWithExplicitPayer",
|
|
1326
|
+
"accounts": [
|
|
1327
|
+
{
|
|
1328
|
+
"name": "user",
|
|
1329
|
+
"isMut": false,
|
|
1330
|
+
"isSigner": false
|
|
1331
|
+
},
|
|
1332
|
+
{
|
|
1333
|
+
"name": "userOrders",
|
|
1334
|
+
"isMut": true,
|
|
1335
|
+
"isSigner": false
|
|
1336
|
+
},
|
|
1337
|
+
{
|
|
1338
|
+
"name": "state",
|
|
1339
|
+
"isMut": false,
|
|
1340
|
+
"isSigner": false
|
|
1341
|
+
},
|
|
1342
|
+
{
|
|
1343
|
+
"name": "authority",
|
|
1344
|
+
"isMut": false,
|
|
1345
|
+
"isSigner": true
|
|
1346
|
+
},
|
|
1347
|
+
{
|
|
1348
|
+
"name": "payer",
|
|
1349
|
+
"isMut": true,
|
|
1350
|
+
"isSigner": true
|
|
1351
|
+
},
|
|
1352
|
+
{
|
|
1353
|
+
"name": "rent",
|
|
1354
|
+
"isMut": false,
|
|
1355
|
+
"isSigner": false
|
|
1356
|
+
},
|
|
1357
|
+
{
|
|
1358
|
+
"name": "systemProgram",
|
|
1359
|
+
"isMut": false,
|
|
1360
|
+
"isSigner": false
|
|
1361
|
+
}
|
|
1362
|
+
],
|
|
1363
|
+
"args": [
|
|
1364
|
+
{
|
|
1365
|
+
"name": "userOrdersNonce",
|
|
1366
|
+
"type": "u8"
|
|
1367
|
+
}
|
|
1368
|
+
]
|
|
1369
|
+
},
|
|
1324
1370
|
{
|
|
1325
1371
|
"name": "deleteUser",
|
|
1326
1372
|
"accounts": [
|
|
@@ -3667,6 +3713,23 @@
|
|
|
3667
3713
|
]
|
|
3668
3714
|
}
|
|
3669
3715
|
},
|
|
3716
|
+
{
|
|
3717
|
+
"name": "LiquidationType",
|
|
3718
|
+
"type": {
|
|
3719
|
+
"kind": "enum",
|
|
3720
|
+
"variants": [
|
|
3721
|
+
{
|
|
3722
|
+
"name": "NONE"
|
|
3723
|
+
},
|
|
3724
|
+
{
|
|
3725
|
+
"name": "PARTIAL"
|
|
3726
|
+
},
|
|
3727
|
+
{
|
|
3728
|
+
"name": "FULL"
|
|
3729
|
+
}
|
|
3730
|
+
]
|
|
3731
|
+
}
|
|
3732
|
+
},
|
|
3670
3733
|
{
|
|
3671
3734
|
"name": "OracleSource",
|
|
3672
3735
|
"type": {
|
|
@@ -4064,6 +4127,11 @@
|
|
|
4064
4127
|
"code": 6055,
|
|
4065
4128
|
"name": "UserOrderIdAlreadyInUse",
|
|
4066
4129
|
"msg": "User Order Id Already In Use"
|
|
4130
|
+
},
|
|
4131
|
+
{
|
|
4132
|
+
"code": 6056,
|
|
4133
|
+
"name": "NoPositionsLiquidatable",
|
|
4134
|
+
"msg": "No positions liquidatable"
|
|
4067
4135
|
}
|
|
4068
4136
|
]
|
|
4069
4137
|
}
|
package/lib/index.d.ts
CHANGED
|
@@ -6,6 +6,7 @@ export * from './types';
|
|
|
6
6
|
export * from './constants/markets';
|
|
7
7
|
export * from './accounts/webSocketClearingHouseAccountSubscriber';
|
|
8
8
|
export * from './accounts/bulkAccountLoader';
|
|
9
|
+
export * from './accounts/bulkUserSubscription';
|
|
9
10
|
export * from './accounts/pollingClearingHouseAccountSubscriber';
|
|
10
11
|
export * from './accounts/pollingTokenAccountSubscriber';
|
|
11
12
|
export * from './accounts/types';
|
|
@@ -30,6 +31,7 @@ export * from './types';
|
|
|
30
31
|
export * from './math/utils';
|
|
31
32
|
export * from './config';
|
|
32
33
|
export * from './constants/numericConstants';
|
|
34
|
+
export * from './tx/retryTxSender';
|
|
33
35
|
export * from './util/computeUnits';
|
|
34
36
|
export * from './util/tps';
|
|
35
37
|
export { BN, PublicKey };
|
package/lib/index.js
CHANGED
|
@@ -21,6 +21,7 @@ __exportStar(require("./types"), exports);
|
|
|
21
21
|
__exportStar(require("./constants/markets"), exports);
|
|
22
22
|
__exportStar(require("./accounts/webSocketClearingHouseAccountSubscriber"), exports);
|
|
23
23
|
__exportStar(require("./accounts/bulkAccountLoader"), exports);
|
|
24
|
+
__exportStar(require("./accounts/bulkUserSubscription"), exports);
|
|
24
25
|
__exportStar(require("./accounts/pollingClearingHouseAccountSubscriber"), exports);
|
|
25
26
|
__exportStar(require("./accounts/pollingTokenAccountSubscriber"), exports);
|
|
26
27
|
__exportStar(require("./accounts/types"), exports);
|
|
@@ -45,5 +46,6 @@ __exportStar(require("./types"), exports);
|
|
|
45
46
|
__exportStar(require("./math/utils"), exports);
|
|
46
47
|
__exportStar(require("./config"), exports);
|
|
47
48
|
__exportStar(require("./constants/numericConstants"), exports);
|
|
49
|
+
__exportStar(require("./tx/retryTxSender"), exports);
|
|
48
50
|
__exportStar(require("./util/computeUnits"), exports);
|
|
49
51
|
__exportStar(require("./util/tps"), exports);
|
package/lib/math/amm.js
CHANGED
|
@@ -36,7 +36,7 @@ exports.calculatePrice = calculatePrice;
|
|
|
36
36
|
* @returns quoteAssetReserve and baseAssetReserve after swap. : Precision AMM_RESERVE_PRECISION
|
|
37
37
|
*/
|
|
38
38
|
function calculateAmmReservesAfterSwap(amm, inputAssetType, swapAmount, swapDirection) {
|
|
39
|
-
assert_1.assert(swapAmount.gte(numericConstants_1.ZERO), 'swapAmount must be greater than 0');
|
|
39
|
+
(0, assert_1.assert)(swapAmount.gte(numericConstants_1.ZERO), 'swapAmount must be greater than 0');
|
|
40
40
|
let newQuoteAssetReserve;
|
|
41
41
|
let newBaseAssetReserve;
|
|
42
42
|
if (inputAssetType === 'quote') {
|
|
@@ -79,10 +79,10 @@ exports.calculateSwapOutput = calculateSwapOutput;
|
|
|
79
79
|
* @param positionDirection
|
|
80
80
|
*/
|
|
81
81
|
function getSwapDirection(inputAssetType, positionDirection) {
|
|
82
|
-
if (types_1.isVariant(positionDirection, 'long') && inputAssetType === 'base') {
|
|
82
|
+
if ((0, types_1.isVariant)(positionDirection, 'long') && inputAssetType === 'base') {
|
|
83
83
|
return types_1.SwapDirection.REMOVE;
|
|
84
84
|
}
|
|
85
|
-
if (types_1.isVariant(positionDirection, 'short') && inputAssetType === 'quote') {
|
|
85
|
+
if ((0, types_1.isVariant)(positionDirection, 'short') && inputAssetType === 'quote') {
|
|
86
86
|
return types_1.SwapDirection.REMOVE;
|
|
87
87
|
}
|
|
88
88
|
return types_1.SwapDirection.ADD;
|
|
@@ -104,7 +104,7 @@ function calculateAdjustKCost(market, marketIndex, numerator, denomenator) {
|
|
|
104
104
|
quoteAssetAmount: new anchor_1.BN(0),
|
|
105
105
|
openOrders: new anchor_1.BN(0),
|
|
106
106
|
};
|
|
107
|
-
const currentValue = position_1.calculateBaseAssetValue(market, netUserPosition);
|
|
107
|
+
const currentValue = (0, position_1.calculateBaseAssetValue)(market, netUserPosition);
|
|
108
108
|
const marketNewK = Object.assign({}, market);
|
|
109
109
|
marketNewK.amm = Object.assign({}, market.amm);
|
|
110
110
|
marketNewK.amm.baseAssetReserve = market.amm.baseAssetReserve
|
|
@@ -115,7 +115,7 @@ function calculateAdjustKCost(market, marketIndex, numerator, denomenator) {
|
|
|
115
115
|
.div(denomenator);
|
|
116
116
|
marketNewK.amm.sqrtK = market.amm.sqrtK.mul(numerator).div(denomenator);
|
|
117
117
|
netUserPosition.quoteAssetAmount = currentValue;
|
|
118
|
-
const cost = __1.calculatePositionPNL(marketNewK, netUserPosition);
|
|
118
|
+
const cost = (0, __1.calculatePositionPNL)(marketNewK, netUserPosition);
|
|
119
119
|
const p = numericConstants_1.PEG_PRECISION.mul(numerator).div(denomenator);
|
|
120
120
|
const x = market.amm.baseAssetReserve;
|
|
121
121
|
const y = market.amm.quoteAssetReserve;
|
|
@@ -134,7 +134,7 @@ function calculateAdjustKCost(market, marketIndex, numerator, denomenator) {
|
|
|
134
134
|
.sub(numer1)
|
|
135
135
|
.mul(market.amm.pegMultiplier)
|
|
136
136
|
.div(numericConstants_1.AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO);
|
|
137
|
-
console.log(__1.convertToNumber(formulaCost, numericConstants_1.QUOTE_PRECISION));
|
|
137
|
+
console.log((0, __1.convertToNumber)(formulaCost, numericConstants_1.QUOTE_PRECISION));
|
|
138
138
|
// p.div(p.mul(x).add(delta)).sub()
|
|
139
139
|
return cost;
|
|
140
140
|
}
|
|
@@ -155,22 +155,22 @@ function calculateRepegCost(market, marketIndex, newPeg) {
|
|
|
155
155
|
quoteAssetAmount: new anchor_1.BN(0),
|
|
156
156
|
openOrders: new anchor_1.BN(0),
|
|
157
157
|
};
|
|
158
|
-
const currentValue = position_1.calculateBaseAssetValue(market, netUserPosition);
|
|
158
|
+
const currentValue = (0, position_1.calculateBaseAssetValue)(market, netUserPosition);
|
|
159
159
|
netUserPosition.quoteAssetAmount = currentValue;
|
|
160
|
-
const prevMarketPrice = __1.calculateMarkPrice(market);
|
|
160
|
+
const prevMarketPrice = (0, __1.calculateMarkPrice)(market);
|
|
161
161
|
const marketNewPeg = Object.assign({}, market);
|
|
162
162
|
marketNewPeg.amm = Object.assign({}, market.amm);
|
|
163
163
|
// const marketNewPeg = JSON.parse(JSON.stringify(market));
|
|
164
164
|
marketNewPeg.amm.pegMultiplier = newPeg;
|
|
165
|
-
console.log('Price moves from', __1.convertToNumber(prevMarketPrice), 'to', __1.convertToNumber(__1.calculateMarkPrice(marketNewPeg)));
|
|
166
|
-
const cost = __1.calculatePositionPNL(marketNewPeg, netUserPosition);
|
|
165
|
+
console.log('Price moves from', (0, __1.convertToNumber)(prevMarketPrice), 'to', (0, __1.convertToNumber)((0, __1.calculateMarkPrice)(marketNewPeg)));
|
|
166
|
+
const cost = (0, __1.calculatePositionPNL)(marketNewPeg, netUserPosition);
|
|
167
167
|
const k = market.amm.sqrtK.mul(market.amm.sqrtK);
|
|
168
168
|
const newQuoteAssetReserve = k.div(market.amm.baseAssetReserve.add(netUserPosition.baseAssetAmount));
|
|
169
169
|
const deltaQuoteAssetReserves = newQuoteAssetReserve.sub(market.amm.quoteAssetReserve);
|
|
170
170
|
const cost2 = deltaQuoteAssetReserves
|
|
171
171
|
.mul(market.amm.pegMultiplier.sub(newPeg))
|
|
172
172
|
.div(numericConstants_1.AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO);
|
|
173
|
-
console.log(__1.convertToNumber(cost2, numericConstants_1.QUOTE_PRECISION));
|
|
173
|
+
console.log((0, __1.convertToNumber)(cost2, numericConstants_1.QUOTE_PRECISION));
|
|
174
174
|
return cost;
|
|
175
175
|
}
|
|
176
176
|
exports.calculateRepegCost = calculateRepegCost;
|
|
@@ -200,7 +200,7 @@ function calculateMaxBaseAssetAmountToTrade(amm, limit_price) {
|
|
|
200
200
|
.mul(amm.pegMultiplier)
|
|
201
201
|
.div(limit_price)
|
|
202
202
|
.div(numericConstants_1.PEG_PRECISION);
|
|
203
|
-
const newBaseAssetReserve = __1.squareRootBN(newBaseAssetReserveSquared);
|
|
203
|
+
const newBaseAssetReserve = (0, __1.squareRootBN)(newBaseAssetReserveSquared);
|
|
204
204
|
if (newBaseAssetReserve.gt(amm.baseAssetReserve)) {
|
|
205
205
|
return [
|
|
206
206
|
newBaseAssetReserve.sub(amm.baseAssetReserve),
|
package/lib/math/conversion.js
CHANGED
|
@@ -10,6 +10,6 @@ const convertToNumber = (bigNumber, precision = numericConstants_1.MARK_PRICE_PR
|
|
|
10
10
|
};
|
|
11
11
|
exports.convertToNumber = convertToNumber;
|
|
12
12
|
const convertBaseAssetAmountToNumber = (baseAssetAmount) => {
|
|
13
|
-
return exports.convertToNumber(baseAssetAmount, numericConstants_1.MARK_PRICE_PRECISION.mul(numericConstants_1.PEG_PRECISION));
|
|
13
|
+
return (0, exports.convertToNumber)(baseAssetAmount, numericConstants_1.MARK_PRICE_PRECISION.mul(numericConstants_1.PEG_PRECISION));
|
|
14
14
|
};
|
|
15
15
|
exports.convertBaseAssetAmountToNumber = convertBaseAssetAmountToNumber;
|
package/lib/math/funding.js
CHANGED
|
@@ -40,7 +40,7 @@ function calculateAllEstimatedFundingRate(market, oraclePriceData, periodAdjustm
|
|
|
40
40
|
const lastMarkPriceTwapTs = market.amm.lastMarkPriceTwapTs;
|
|
41
41
|
const timeSinceLastMarkChange = now.sub(lastMarkPriceTwapTs);
|
|
42
42
|
const markTwapTimeSinceLastUpdate = anchor_1.BN.max(secondsInHour, secondsInHour.sub(timeSinceLastMarkChange));
|
|
43
|
-
const baseAssetPriceWithMantissa = market_1.calculateMarkPrice(market);
|
|
43
|
+
const baseAssetPriceWithMantissa = (0, market_1.calculateMarkPrice)(market);
|
|
44
44
|
const markTwapWithMantissa = markTwapTimeSinceLastUpdate
|
|
45
45
|
.mul(lastMarkTwapWithMantissa)
|
|
46
46
|
.add(timeSinceLastMarkChange.mul(baseAssetPriceWithMantissa))
|
package/lib/math/market.js
CHANGED
|
@@ -9,11 +9,11 @@ const amm_1 = require("./amm");
|
|
|
9
9
|
* @return markPrice : Precision MARK_PRICE_PRECISION
|
|
10
10
|
*/
|
|
11
11
|
function calculateMarkPrice(market) {
|
|
12
|
-
return amm_1.calculatePrice(market.amm.baseAssetReserve, market.amm.quoteAssetReserve, market.amm.pegMultiplier);
|
|
12
|
+
return (0, amm_1.calculatePrice)(market.amm.baseAssetReserve, market.amm.quoteAssetReserve, market.amm.pegMultiplier);
|
|
13
13
|
}
|
|
14
14
|
exports.calculateMarkPrice = calculateMarkPrice;
|
|
15
15
|
function calculateNewMarketAfterTrade(baseAssetAmount, direction, market) {
|
|
16
|
-
const [newQuoteAssetReserve, newBaseAssetReserve] = amm_1.calculateAmmReservesAfterSwap(market.amm, 'base', baseAssetAmount.abs(), amm_1.getSwapDirection('base', direction));
|
|
16
|
+
const [newQuoteAssetReserve, newBaseAssetReserve] = (0, amm_1.calculateAmmReservesAfterSwap)(market.amm, 'base', baseAssetAmount.abs(), (0, amm_1.getSwapDirection)('base', direction));
|
|
17
17
|
const newAmm = Object.assign({}, market.amm);
|
|
18
18
|
const newMarket = Object.assign({}, market);
|
|
19
19
|
newMarket.amm = newAmm;
|
package/lib/math/orders.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
import { ClearingHouseUser } from '../clearingHouseUser';
|
|
2
2
|
import { Order } from '../types';
|
|
3
3
|
export declare function isOrderRiskIncreasing(user: ClearingHouseUser, order: Order): boolean;
|
|
4
|
+
export declare function isOrderRiskIncreasingInSameDirection(user: ClearingHouseUser, order: Order): boolean;
|
package/lib/math/orders.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.isOrderRiskIncreasing = void 0;
|
|
3
|
+
exports.isOrderRiskIncreasingInSameDirection = exports.isOrderRiskIncreasing = void 0;
|
|
4
4
|
const types_1 = require("../types");
|
|
5
5
|
const numericConstants_1 = require("../constants/numericConstants");
|
|
6
6
|
function isOrderRiskIncreasing(user, order) {
|
|
7
|
-
if (types_1.isVariant(order.status, 'init')) {
|
|
7
|
+
if ((0, types_1.isVariant)(order.status, 'init')) {
|
|
8
8
|
return false;
|
|
9
9
|
}
|
|
10
10
|
const position = user.getUserPosition(order.marketIndex) ||
|
|
@@ -14,12 +14,12 @@ function isOrderRiskIncreasing(user, order) {
|
|
|
14
14
|
return true;
|
|
15
15
|
}
|
|
16
16
|
// if position is long and order is long
|
|
17
|
-
if (position.baseAssetAmount.gt(numericConstants_1.ZERO) && types_1.isVariant(order.direction, 'long')) {
|
|
17
|
+
if (position.baseAssetAmount.gt(numericConstants_1.ZERO) && (0, types_1.isVariant)(order.direction, 'long')) {
|
|
18
18
|
return true;
|
|
19
19
|
}
|
|
20
20
|
// if position is short and order is short
|
|
21
21
|
if (position.baseAssetAmount.lt(numericConstants_1.ZERO) &&
|
|
22
|
-
types_1.isVariant(order.direction, 'short')) {
|
|
22
|
+
(0, types_1.isVariant)(order.direction, 'short')) {
|
|
23
23
|
return true;
|
|
24
24
|
}
|
|
25
25
|
const baseAssetAmountToFill = order.baseAssetAmount.sub(order.baseAssetAmountFilled);
|
|
@@ -30,3 +30,25 @@ function isOrderRiskIncreasing(user, order) {
|
|
|
30
30
|
return false;
|
|
31
31
|
}
|
|
32
32
|
exports.isOrderRiskIncreasing = isOrderRiskIncreasing;
|
|
33
|
+
function isOrderRiskIncreasingInSameDirection(user, order) {
|
|
34
|
+
if ((0, types_1.isVariant)(order.status, 'init')) {
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
const position = user.getUserPosition(order.marketIndex) ||
|
|
38
|
+
user.getEmptyPosition(order.marketIndex);
|
|
39
|
+
// if no position exists, it's risk increasing
|
|
40
|
+
if (position.baseAssetAmount.eq(numericConstants_1.ZERO)) {
|
|
41
|
+
return true;
|
|
42
|
+
}
|
|
43
|
+
// if position is long and order is long
|
|
44
|
+
if (position.baseAssetAmount.gt(numericConstants_1.ZERO) && (0, types_1.isVariant)(order.direction, 'long')) {
|
|
45
|
+
return true;
|
|
46
|
+
}
|
|
47
|
+
// if position is short and order is short
|
|
48
|
+
if (position.baseAssetAmount.lt(numericConstants_1.ZERO) &&
|
|
49
|
+
(0, types_1.isVariant)(order.direction, 'short')) {
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
exports.isOrderRiskIncreasingInSameDirection = isOrderRiskIncreasingInSameDirection;
|
package/lib/math/position.js
CHANGED
|
@@ -17,7 +17,7 @@ function calculateBaseAssetValue(market, userPosition) {
|
|
|
17
17
|
return numericConstants_1.ZERO;
|
|
18
18
|
}
|
|
19
19
|
const directionToClose = findDirectionToClose(userPosition);
|
|
20
|
-
const [newQuoteAssetReserve, _] = amm_1.calculateAmmReservesAfterSwap(market.amm, 'base', userPosition.baseAssetAmount.abs(), amm_1.getSwapDirection('base', directionToClose));
|
|
20
|
+
const [newQuoteAssetReserve, _] = (0, amm_1.calculateAmmReservesAfterSwap)(market.amm, 'base', userPosition.baseAssetAmount.abs(), (0, amm_1.getSwapDirection)('base', directionToClose));
|
|
21
21
|
switch (directionToClose) {
|
|
22
22
|
case types_1.PositionDirection.SHORT:
|
|
23
23
|
return market.amm.quoteAssetReserve
|
|
@@ -28,7 +28,8 @@ function calculateBaseAssetValue(market, userPosition) {
|
|
|
28
28
|
return newQuoteAssetReserve
|
|
29
29
|
.sub(market.amm.quoteAssetReserve)
|
|
30
30
|
.mul(market.amm.pegMultiplier)
|
|
31
|
-
.div(numericConstants_1.AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO)
|
|
31
|
+
.div(numericConstants_1.AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO)
|
|
32
|
+
.add(numericConstants_1.ONE);
|
|
32
33
|
}
|
|
33
34
|
}
|
|
34
35
|
exports.calculateBaseAssetValue = calculateBaseAssetValue;
|
|
@@ -50,7 +51,7 @@ function calculatePositionPNL(market, marketPosition, withFunding = false) {
|
|
|
50
51
|
pnl = baseAssetValue.sub(marketPosition.quoteAssetAmount);
|
|
51
52
|
}
|
|
52
53
|
else {
|
|
53
|
-
pnl = marketPosition.quoteAssetAmount.sub(baseAssetValue)
|
|
54
|
+
pnl = marketPosition.quoteAssetAmount.sub(baseAssetValue);
|
|
54
55
|
}
|
|
55
56
|
if (withFunding) {
|
|
56
57
|
const fundingRatePnL = calculatePositionFundingPNL(market, marketPosition).div(numericConstants_1.PRICE_TO_QUOTE_PRECISION);
|
package/lib/math/trade.js
CHANGED
|
@@ -25,18 +25,18 @@ const MAXPCT = new anchor_1.BN(1000); //percentage units are [0,1000] => [0,1]
|
|
|
25
25
|
* 'newPrice' => the price of the asset after the trade : Precision MARK_PRICE_PRECISION
|
|
26
26
|
*/
|
|
27
27
|
function calculateTradeSlippage(direction, amount, market, inputAssetType = 'quote') {
|
|
28
|
-
const oldPrice = market_1.calculateMarkPrice(market);
|
|
28
|
+
const oldPrice = (0, market_1.calculateMarkPrice)(market);
|
|
29
29
|
if (amount.eq(numericConstants_1.ZERO)) {
|
|
30
30
|
return [numericConstants_1.ZERO, numericConstants_1.ZERO, oldPrice, oldPrice];
|
|
31
31
|
}
|
|
32
32
|
const [acquiredBase, acquiredQuote] = calculateTradeAcquiredAmounts(direction, amount, market, inputAssetType);
|
|
33
|
-
const entryPrice = amm_1.calculatePrice(acquiredBase, acquiredQuote, market.amm.pegMultiplier).mul(new anchor_1.BN(-1));
|
|
34
|
-
const newPrice = amm_1.calculatePrice(market.amm.baseAssetReserve.sub(acquiredBase), market.amm.quoteAssetReserve.sub(acquiredQuote), market.amm.pegMultiplier);
|
|
33
|
+
const entryPrice = (0, amm_1.calculatePrice)(acquiredBase, acquiredQuote, market.amm.pegMultiplier).mul(new anchor_1.BN(-1));
|
|
34
|
+
const newPrice = (0, amm_1.calculatePrice)(market.amm.baseAssetReserve.sub(acquiredBase), market.amm.quoteAssetReserve.sub(acquiredQuote), market.amm.pegMultiplier);
|
|
35
35
|
if (direction == types_1.PositionDirection.SHORT) {
|
|
36
|
-
assert_1.assert(newPrice.lt(oldPrice));
|
|
36
|
+
(0, assert_1.assert)(newPrice.lt(oldPrice));
|
|
37
37
|
}
|
|
38
38
|
else {
|
|
39
|
-
assert_1.assert(oldPrice.lt(newPrice));
|
|
39
|
+
(0, assert_1.assert)(oldPrice.lt(newPrice));
|
|
40
40
|
}
|
|
41
41
|
const pctMaxSlippage = newPrice
|
|
42
42
|
.sub(oldPrice)
|
|
@@ -64,9 +64,13 @@ function calculateTradeAcquiredAmounts(direction, amount, market, inputAssetType
|
|
|
64
64
|
if (amount.eq(numericConstants_1.ZERO)) {
|
|
65
65
|
return [numericConstants_1.ZERO, numericConstants_1.ZERO];
|
|
66
66
|
}
|
|
67
|
-
const
|
|
67
|
+
const swapDirection = (0, amm_1.getSwapDirection)(inputAssetType, direction);
|
|
68
|
+
const [newQuoteAssetReserve, newBaseAssetReserve] = (0, amm_1.calculateAmmReservesAfterSwap)(market.amm, inputAssetType, amount, swapDirection);
|
|
68
69
|
const acquiredBase = market.amm.baseAssetReserve.sub(newBaseAssetReserve);
|
|
69
|
-
|
|
70
|
+
let acquiredQuote = market.amm.quoteAssetReserve.sub(newQuoteAssetReserve);
|
|
71
|
+
if (inputAssetType === 'base' && (0, types_1.isVariant)(swapDirection, 'remove')) {
|
|
72
|
+
acquiredQuote = acquiredQuote.sub(numericConstants_1.ONE);
|
|
73
|
+
}
|
|
70
74
|
return [acquiredBase, acquiredQuote];
|
|
71
75
|
}
|
|
72
76
|
exports.calculateTradeAcquiredAmounts = calculateTradeAcquiredAmounts;
|
|
@@ -86,10 +90,10 @@ exports.calculateTradeAcquiredAmounts = calculateTradeAcquiredAmounts;
|
|
|
86
90
|
* ]
|
|
87
91
|
*/
|
|
88
92
|
function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAssetType = 'quote') {
|
|
89
|
-
assert_1.assert(market.amm.baseAssetReserve.gt(numericConstants_1.ZERO));
|
|
90
|
-
assert_1.assert(targetPrice.gt(numericConstants_1.ZERO));
|
|
91
|
-
assert_1.assert(pct.lte(MAXPCT) && pct.gt(numericConstants_1.ZERO));
|
|
92
|
-
const markPriceBefore = market_1.calculateMarkPrice(market);
|
|
93
|
+
(0, assert_1.assert)(market.amm.baseAssetReserve.gt(numericConstants_1.ZERO));
|
|
94
|
+
(0, assert_1.assert)(targetPrice.gt(numericConstants_1.ZERO));
|
|
95
|
+
(0, assert_1.assert)(pct.lte(MAXPCT) && pct.gt(numericConstants_1.ZERO));
|
|
96
|
+
const markPriceBefore = (0, market_1.calculateMarkPrice)(market);
|
|
93
97
|
if (targetPrice.gt(markPriceBefore)) {
|
|
94
98
|
const priceGap = targetPrice.sub(markPriceBefore);
|
|
95
99
|
const priceGapScaled = priceGap.mul(pct).div(MAXPCT);
|
|
@@ -114,11 +118,11 @@ function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAsse
|
|
|
114
118
|
let markPriceAfter;
|
|
115
119
|
if (markPriceBefore.gt(targetPrice)) {
|
|
116
120
|
// overestimate y2
|
|
117
|
-
baseAssetReserveAfter = utils_1.squareRootBN(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).sub(biasModifier)).sub(new anchor_1.BN(1));
|
|
121
|
+
baseAssetReserveAfter = (0, utils_1.squareRootBN)(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).sub(biasModifier)).sub(new anchor_1.BN(1));
|
|
118
122
|
quoteAssetReserveAfter = k
|
|
119
123
|
.div(numericConstants_1.MARK_PRICE_PRECISION)
|
|
120
124
|
.div(baseAssetReserveAfter);
|
|
121
|
-
markPriceAfter = amm_1.calculatePrice(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
|
|
125
|
+
markPriceAfter = (0, amm_1.calculatePrice)(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
|
|
122
126
|
direction = types_1.PositionDirection.SHORT;
|
|
123
127
|
tradeSize = quoteAssetReserveBefore
|
|
124
128
|
.sub(quoteAssetReserveAfter)
|
|
@@ -129,11 +133,11 @@ function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAsse
|
|
|
129
133
|
}
|
|
130
134
|
else if (markPriceBefore.lt(targetPrice)) {
|
|
131
135
|
// underestimate y2
|
|
132
|
-
baseAssetReserveAfter = utils_1.squareRootBN(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).add(biasModifier)).add(new anchor_1.BN(1));
|
|
136
|
+
baseAssetReserveAfter = (0, utils_1.squareRootBN)(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).add(biasModifier)).add(new anchor_1.BN(1));
|
|
133
137
|
quoteAssetReserveAfter = k
|
|
134
138
|
.div(numericConstants_1.MARK_PRICE_PRECISION)
|
|
135
139
|
.div(baseAssetReserveAfter);
|
|
136
|
-
markPriceAfter = amm_1.calculatePrice(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
|
|
140
|
+
markPriceAfter = (0, amm_1.calculatePrice)(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
|
|
137
141
|
direction = types_1.PositionDirection.LONG;
|
|
138
142
|
tradeSize = quoteAssetReserveAfter
|
|
139
143
|
.sub(quoteAssetReserveBefore)
|
|
@@ -160,8 +164,8 @@ function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAsse
|
|
|
160
164
|
.mul(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
|
|
161
165
|
.mul(numericConstants_1.MARK_PRICE_PRECISION)
|
|
162
166
|
.div(baseSize.abs());
|
|
163
|
-
assert_1.assert(tp1.sub(tp2).lte(originalDiff), 'Target Price Calculation incorrect');
|
|
164
|
-
assert_1.assert(tp2.lte(tp1) || tp2.sub(tp1).abs() < 100000, 'Target Price Calculation incorrect' +
|
|
167
|
+
(0, assert_1.assert)(tp1.sub(tp2).lte(originalDiff), 'Target Price Calculation incorrect');
|
|
168
|
+
(0, assert_1.assert)(tp2.lte(tp1) || tp2.sub(tp1).abs() < 100000, 'Target Price Calculation incorrect' +
|
|
165
169
|
tp2.toString() +
|
|
166
170
|
'>=' +
|
|
167
171
|
tp1.toString() +
|
package/lib/orders.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
/// <reference types="bn.js" />
|
|
2
2
|
import { Market, Order, UserAccount, UserPosition } from './types';
|
|
3
|
-
import { BN } from '.';
|
|
3
|
+
import { BN, ClearingHouseUser } from '.';
|
|
4
4
|
export declare function calculateNewStateAfterOrder(userAccount: UserAccount, userPosition: UserPosition, market: Market, order: Order): [UserAccount, UserPosition, Market] | null;
|
|
5
|
+
export declare function calculateBaseAssetAmountMarketCanExecute(market: Market, order: Order): BN;
|
|
5
6
|
export declare function calculateAmountToTradeForLimit(market: Market, order: Order): BN;
|
|
6
7
|
export declare function calculateAmountToTradeForTriggerLimit(market: Market, order: Order): BN;
|
|
8
|
+
export declare function calculateBaseAssetAmountUserCanExecute(market: Market, order: Order, user: ClearingHouseUser): BN;
|