@drift-labs/sdk 0.1.17-master.2 → 0.1.17
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/defaultClearingHouseAccountSubscriber.js +1 -1
- package/lib/accounts/defaultUserAccountSubscriber.js +1 -1
- package/lib/admin.js +3 -3
- package/lib/clearingHouse.js +9 -9
- package/lib/clearingHouseUser.js +13 -13
- package/lib/examples/makeTradeExample.js +6 -6
- package/lib/math/amm.js +7 -7
- package/lib/math/conversion.js +1 -1
- package/lib/math/funding.js +1 -1
- package/lib/math/market.js +1 -1
- package/lib/math/position.js +1 -1
- package/lib/math/trade.js +16 -16
- package/lib/pythClient.js +1 -1
- package/package.json +2 -2
|
@@ -34,7 +34,7 @@ class DefaultClearingHouseAccountSubscriber {
|
|
|
34
34
|
this.subscriptionPromise = new Promise((res) => {
|
|
35
35
|
this.subscriptionPromiseResolver = res;
|
|
36
36
|
});
|
|
37
|
-
const statePublicKey = yield
|
|
37
|
+
const statePublicKey = yield addresses_1.getClearingHouseStateAccountPublicKey(this.program.programId);
|
|
38
38
|
// create and activate main state account subscription
|
|
39
39
|
this.stateAccountSubscriber = new webSocketAccountSubscriber_1.WebSocketAccountSubscriber('state', this.program, statePublicKey);
|
|
40
40
|
yield this.stateAccountSubscriber.subscribe((data) => {
|
|
@@ -26,7 +26,7 @@ class DefaultUserAccountSubscriber {
|
|
|
26
26
|
if (this.isSubscribed) {
|
|
27
27
|
return true;
|
|
28
28
|
}
|
|
29
|
-
const userPublicKey = yield
|
|
29
|
+
const userPublicKey = yield addresses_1.getUserAccountPublicKey(this.program.programId, this.authority);
|
|
30
30
|
this.userDataAccountSubscriber = new webSocketAccountSubscriber_1.WebSocketAccountSubscriber('user', this.program, userPublicKey);
|
|
31
31
|
yield this.userDataAccountSubscriber.subscribe((data) => {
|
|
32
32
|
this.eventEmitter.emit('userAccountData', data);
|
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
|
|
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,
|
|
@@ -166,8 +166,8 @@ class Admin extends clearingHouse_1.ClearingHouse {
|
|
|
166
166
|
moveAmmToPrice(marketIndex, targetPrice) {
|
|
167
167
|
return __awaiter(this, void 0, void 0, function* () {
|
|
168
168
|
const market = this.getMarket(marketIndex);
|
|
169
|
-
const [direction, tradeSize, _] =
|
|
170
|
-
const [newQuoteAssetAmount, newBaseAssetAmount] =
|
|
169
|
+
const [direction, tradeSize, _] = trade_1.calculateTargetPriceTrade(market, targetPrice);
|
|
170
|
+
const [newQuoteAssetAmount, newBaseAssetAmount] = amm_1.calculateAmmReservesAfterSwap(market.amm, 'quote', tradeSize, amm_1.getSwapDirection('quote', direction));
|
|
171
171
|
const state = this.getStateAccount();
|
|
172
172
|
return yield this.program.rpc.moveAmmPrice(newBaseAssetAmount, newQuoteAssetAmount, marketIndex, {
|
|
173
173
|
accounts: {
|
package/lib/clearingHouse.js
CHANGED
|
@@ -115,7 +115,7 @@ class ClearingHouse {
|
|
|
115
115
|
if (this.statePublicKey) {
|
|
116
116
|
return this.statePublicKey;
|
|
117
117
|
}
|
|
118
|
-
this.statePublicKey = yield
|
|
118
|
+
this.statePublicKey = yield addresses_1.getClearingHouseStateAccountPublicKey(this.program.programId);
|
|
119
119
|
return this.statePublicKey;
|
|
120
120
|
});
|
|
121
121
|
}
|
|
@@ -174,7 +174,7 @@ class ClearingHouse {
|
|
|
174
174
|
}
|
|
175
175
|
getInitializeUserInstructions() {
|
|
176
176
|
return __awaiter(this, void 0, void 0, function* () {
|
|
177
|
-
const [userPublicKey, userAccountNonce] = yield
|
|
177
|
+
const [userPublicKey, userAccountNonce] = yield addresses_1.getUserAccountPublicKeyAndNonce(this.program.programId, this.wallet.publicKey);
|
|
178
178
|
const remainingAccounts = [];
|
|
179
179
|
const optionalAccounts = {
|
|
180
180
|
whitelistToken: false,
|
|
@@ -213,7 +213,7 @@ class ClearingHouse {
|
|
|
213
213
|
if (this.userAccountPublicKey) {
|
|
214
214
|
return this.userAccountPublicKey;
|
|
215
215
|
}
|
|
216
|
-
this.userAccountPublicKey = yield
|
|
216
|
+
this.userAccountPublicKey = yield addresses_1.getUserAccountPublicKey(this.program.programId, this.wallet.publicKey);
|
|
217
217
|
return this.userAccountPublicKey;
|
|
218
218
|
});
|
|
219
219
|
}
|
|
@@ -303,7 +303,7 @@ class ClearingHouse {
|
|
|
303
303
|
}
|
|
304
304
|
withdrawCollateral(amount, collateralAccountPublicKey) {
|
|
305
305
|
return __awaiter(this, void 0, void 0, function* () {
|
|
306
|
-
return this.txSender.send(
|
|
306
|
+
return this.txSender.send(utils_1.wrapInTx(yield this.getWithdrawCollateralIx(amount, collateralAccountPublicKey)), [], this.opts);
|
|
307
307
|
});
|
|
308
308
|
}
|
|
309
309
|
getWithdrawCollateralIx(amount, collateralAccountPublicKey) {
|
|
@@ -332,7 +332,7 @@ class ClearingHouse {
|
|
|
332
332
|
}
|
|
333
333
|
openPosition(direction, amount, marketIndex, limitPrice, discountToken, referrer) {
|
|
334
334
|
return __awaiter(this, void 0, void 0, function* () {
|
|
335
|
-
return yield this.txSender.send(
|
|
335
|
+
return yield this.txSender.send(utils_1.wrapInTx(yield this.getOpenPositionIx(direction, amount, marketIndex, limitPrice, discountToken, referrer)), [], this.opts);
|
|
336
336
|
});
|
|
337
337
|
}
|
|
338
338
|
getOpenPositionIx(direction, amount, marketIndex, limitPrice, discountToken, referrer) {
|
|
@@ -390,7 +390,7 @@ class ClearingHouse {
|
|
|
390
390
|
*/
|
|
391
391
|
closePosition(marketIndex, discountToken, referrer) {
|
|
392
392
|
return __awaiter(this, void 0, void 0, function* () {
|
|
393
|
-
return yield this.txSender.send(
|
|
393
|
+
return yield this.txSender.send(utils_1.wrapInTx(yield this.getClosePositionIx(marketIndex, discountToken, referrer)), [], this.opts);
|
|
394
394
|
});
|
|
395
395
|
}
|
|
396
396
|
getClosePositionIx(marketIndex, discountToken, referrer) {
|
|
@@ -438,7 +438,7 @@ class ClearingHouse {
|
|
|
438
438
|
}
|
|
439
439
|
liquidate(liquidateeUserAccountPublicKey) {
|
|
440
440
|
return __awaiter(this, void 0, void 0, function* () {
|
|
441
|
-
return this.txSender.send(
|
|
441
|
+
return this.txSender.send(utils_1.wrapInTx(yield this.getLiquidateIx(liquidateeUserAccountPublicKey)), [], this.opts);
|
|
442
442
|
});
|
|
443
443
|
}
|
|
444
444
|
getLiquidateIx(liquidateeUserAccountPublicKey) {
|
|
@@ -482,7 +482,7 @@ class ClearingHouse {
|
|
|
482
482
|
}
|
|
483
483
|
updateFundingRate(oracle, marketIndex) {
|
|
484
484
|
return __awaiter(this, void 0, void 0, function* () {
|
|
485
|
-
return this.txSender.send(
|
|
485
|
+
return this.txSender.send(utils_1.wrapInTx(yield this.getUpdateFundingRateIx(oracle, marketIndex)), [], this.opts);
|
|
486
486
|
});
|
|
487
487
|
}
|
|
488
488
|
getUpdateFundingRateIx(oracle, marketIndex) {
|
|
@@ -500,7 +500,7 @@ class ClearingHouse {
|
|
|
500
500
|
}
|
|
501
501
|
settleFundingPayment(userAccount, userPositionsAccount) {
|
|
502
502
|
return __awaiter(this, void 0, void 0, function* () {
|
|
503
|
-
return this.txSender.send(
|
|
503
|
+
return this.txSender.send(utils_1.wrapInTx(yield this.getSettleFundingPaymentIx(userAccount, userPositionsAccount)), [], this.opts);
|
|
504
504
|
});
|
|
505
505
|
}
|
|
506
506
|
getSettleFundingPaymentIx(userAccount, userPositionsAccount) {
|
package/lib/clearingHouseUser.js
CHANGED
|
@@ -84,7 +84,7 @@ class ClearingHouseUser {
|
|
|
84
84
|
if (this.userAccountPublicKey) {
|
|
85
85
|
return this.userAccountPublicKey;
|
|
86
86
|
}
|
|
87
|
-
this.userAccountPublicKey = yield
|
|
87
|
+
this.userAccountPublicKey = yield addresses_1.getUserAccountPublicKey(this.clearingHouse.program.programId, this.authority);
|
|
88
88
|
return this.userAccountPublicKey;
|
|
89
89
|
});
|
|
90
90
|
}
|
|
@@ -122,7 +122,7 @@ class ClearingHouseUser {
|
|
|
122
122
|
.positions.filter((pos) => marketIndex ? pos.marketIndex === marketIndex : true)
|
|
123
123
|
.reduce((pnl, marketPosition) => {
|
|
124
124
|
const market = this.clearingHouse.getMarket(marketPosition.marketIndex);
|
|
125
|
-
return pnl.add(
|
|
125
|
+
return pnl.add(_1.calculatePositionPNL(market, marketPosition, withFunding));
|
|
126
126
|
}, numericConstants_1.ZERO);
|
|
127
127
|
}
|
|
128
128
|
/**
|
|
@@ -134,7 +134,7 @@ class ClearingHouseUser {
|
|
|
134
134
|
.positions.filter((pos) => marketIndex ? pos.marketIndex === marketIndex : true)
|
|
135
135
|
.reduce((pnl, marketPosition) => {
|
|
136
136
|
const market = this.clearingHouse.getMarket(marketPosition.marketIndex);
|
|
137
|
-
return pnl.add(
|
|
137
|
+
return pnl.add(_1.calculatePositionFundingPNL(market, marketPosition));
|
|
138
138
|
}, numericConstants_1.ZERO);
|
|
139
139
|
}
|
|
140
140
|
/**
|
|
@@ -152,7 +152,7 @@ class ClearingHouseUser {
|
|
|
152
152
|
getTotalPositionValue() {
|
|
153
153
|
return this.getUserPositionsAccount().positions.reduce((positionValue, marketPosition) => {
|
|
154
154
|
const market = this.clearingHouse.getMarket(marketPosition.marketIndex);
|
|
155
|
-
return positionValue.add(
|
|
155
|
+
return positionValue.add(_1.calculateBaseAssetValue(market, marketPosition));
|
|
156
156
|
}, numericConstants_1.ZERO);
|
|
157
157
|
}
|
|
158
158
|
/**
|
|
@@ -162,7 +162,7 @@ class ClearingHouseUser {
|
|
|
162
162
|
getPositionValue(marketIndex) {
|
|
163
163
|
const userPosition = this.getUserPosition(marketIndex) || this.getEmptyPosition(marketIndex);
|
|
164
164
|
const market = this.clearingHouse.getMarket(userPosition.marketIndex);
|
|
165
|
-
return
|
|
165
|
+
return _1.calculateBaseAssetValue(market, userPosition);
|
|
166
166
|
}
|
|
167
167
|
getPositionSide(currentPosition) {
|
|
168
168
|
if (currentPosition.baseAssetAmount.gt(numericConstants_1.ZERO)) {
|
|
@@ -181,10 +181,10 @@ class ClearingHouseUser {
|
|
|
181
181
|
*/
|
|
182
182
|
getPositionEstimatedExitPriceAndPnl(position, amountToClose) {
|
|
183
183
|
const market = this.clearingHouse.getMarket(position.marketIndex);
|
|
184
|
-
const entryPrice =
|
|
184
|
+
const entryPrice = position_1.calculateEntryPrice(position);
|
|
185
185
|
if (amountToClose) {
|
|
186
186
|
if (amountToClose.eq(numericConstants_1.ZERO)) {
|
|
187
|
-
return [
|
|
187
|
+
return [_1.calculateMarkPrice(market), numericConstants_1.ZERO];
|
|
188
188
|
}
|
|
189
189
|
position = {
|
|
190
190
|
baseAssetAmount: amountToClose,
|
|
@@ -193,7 +193,7 @@ class ClearingHouseUser {
|
|
|
193
193
|
quoteAssetAmount: position.quoteAssetAmount,
|
|
194
194
|
};
|
|
195
195
|
}
|
|
196
|
-
const baseAssetValue =
|
|
196
|
+
const baseAssetValue = _1.calculateBaseAssetValue(market, position);
|
|
197
197
|
if (position.baseAssetAmount.eq(numericConstants_1.ZERO)) {
|
|
198
198
|
return [numericConstants_1.ZERO, numericConstants_1.ZERO];
|
|
199
199
|
}
|
|
@@ -300,7 +300,7 @@ class ClearingHouseUser {
|
|
|
300
300
|
|
|
301
301
|
for 10x long, BTC down $400:
|
|
302
302
|
3. (10k - 4k) / (100k - 4k) = 6k/96k => .0625 */
|
|
303
|
-
const currentPrice =
|
|
303
|
+
const currentPrice = _1.calculateMarkPrice(this.clearingHouse.getMarket(targetMarket.marketIndex));
|
|
304
304
|
const totalCollateralUSDC = this.getTotalCollateral();
|
|
305
305
|
// calculate the total position value ignoring any value from the target market of the trade
|
|
306
306
|
const totalCurrentPositionValueIgnoringTargetUSDC = this.getTotalPositionValueExcludingMarket(targetMarket.marketIndex);
|
|
@@ -315,7 +315,7 @@ class ClearingHouseUser {
|
|
|
315
315
|
quoteAssetAmount: new bn_js_1.default(0),
|
|
316
316
|
};
|
|
317
317
|
const market = this.clearingHouse.getMarket(proposedMarketPosition.marketIndex);
|
|
318
|
-
const proposedMarketPositionValueUSDC =
|
|
318
|
+
const proposedMarketPositionValueUSDC = _1.calculateBaseAssetValue(market, proposedMarketPosition);
|
|
319
319
|
// total position value after trade
|
|
320
320
|
const targetTotalPositionValueUSDC = totalCurrentPositionValueIgnoringTargetUSDC.add(proposedMarketPositionValueUSDC);
|
|
321
321
|
let totalFreeCollateralUSDC = this.getTotalCollateral().sub(this.getTotalPositionValue()
|
|
@@ -400,7 +400,7 @@ class ClearingHouseUser {
|
|
|
400
400
|
quoteAssetAmount: new bn_js_1.default(0),
|
|
401
401
|
};
|
|
402
402
|
const market = this.clearingHouse.getMarket(proposedMarketPosition.marketIndex);
|
|
403
|
-
const proposedMarketPositionValueUSDC =
|
|
403
|
+
const proposedMarketPositionValueUSDC = _1.calculateBaseAssetValue(market, proposedMarketPosition);
|
|
404
404
|
// total position value after trade
|
|
405
405
|
const targetTotalPositionValueUSDC = totalCurrentPositionValueIgnoringTargetUSDC.add(proposedMarketPositionValueUSDC);
|
|
406
406
|
let totalFreeCollateralUSDC = tc.sub(totalCurrentPositionValueIgnoringTargetUSDC
|
|
@@ -428,13 +428,13 @@ class ClearingHouseUser {
|
|
|
428
428
|
}
|
|
429
429
|
let currentPrice;
|
|
430
430
|
if (positionBaseSizeChange.eq(numericConstants_1.ZERO)) {
|
|
431
|
-
currentPrice =
|
|
431
|
+
currentPrice = _1.calculateMarkPrice(this.clearingHouse.getMarket(targetMarket.marketIndex));
|
|
432
432
|
}
|
|
433
433
|
else {
|
|
434
434
|
const direction = positionBaseSizeChange.gt(numericConstants_1.ZERO)
|
|
435
435
|
? _1.PositionDirection.LONG
|
|
436
436
|
: _1.PositionDirection.SHORT;
|
|
437
|
-
currentPrice =
|
|
437
|
+
currentPrice = _1.calculateTradeSlippage(direction, positionBaseSizeChange.abs(), this.clearingHouse.getMarket(targetMarket.marketIndex), 'base')[3]; // newPrice after swap
|
|
438
438
|
}
|
|
439
439
|
// if the position value after the trade is less than total collateral, there is no liq price
|
|
440
440
|
if (targetTotalPositionValueUSDC.lte(totalFreeCollateralUSDC) &&
|
|
@@ -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 =
|
|
24
|
+
const sdkConfig = __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
|
|
38
|
+
const usdcTokenAddress = yield 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
|
|
50
|
+
yield clearingHouse.initializeUserAccountAndDepositCollateral(depositAmount, yield 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 =
|
|
56
|
-
const formattedPrice =
|
|
55
|
+
const currentMarketPrice = __2.calculateMarkPrice(clearingHouse.getMarket(solMarketInfo.marketIndex));
|
|
56
|
+
const formattedPrice = __2.convertToNumber(currentMarketPrice, __2.QUOTE_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 =
|
|
61
|
+
const slippage = __2.convertToNumber(__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);
|
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
|
-
|
|
39
|
+
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') {
|
|
@@ -105,7 +105,7 @@ function calculateAdjustKCost(market, marketIndex, numerator, denomenator) {
|
|
|
105
105
|
marketIndex: new anchor_1.BN(marketIndex),
|
|
106
106
|
quoteAssetAmount: new anchor_1.BN(0),
|
|
107
107
|
};
|
|
108
|
-
const currentValue =
|
|
108
|
+
const currentValue = position_1.calculateBaseAssetValue(market, netUserPosition);
|
|
109
109
|
const marketNewK = Object.assign({}, market);
|
|
110
110
|
marketNewK.amm = Object.assign({}, market.amm);
|
|
111
111
|
marketNewK.amm.baseAssetReserve = market.amm.baseAssetReserve
|
|
@@ -116,7 +116,7 @@ function calculateAdjustKCost(market, marketIndex, numerator, denomenator) {
|
|
|
116
116
|
.div(denomenator);
|
|
117
117
|
marketNewK.amm.sqrtK = market.amm.sqrtK.mul(numerator).div(denomenator);
|
|
118
118
|
netUserPosition.quoteAssetAmount = currentValue;
|
|
119
|
-
const cost =
|
|
119
|
+
const cost = __1.calculatePositionPNL(marketNewK, netUserPosition);
|
|
120
120
|
return cost;
|
|
121
121
|
}
|
|
122
122
|
exports.calculateAdjustKCost = calculateAdjustKCost;
|
|
@@ -135,15 +135,15 @@ function calculateRepegCost(market, marketIndex, newPeg) {
|
|
|
135
135
|
marketIndex: new anchor_1.BN(marketIndex),
|
|
136
136
|
quoteAssetAmount: new anchor_1.BN(0),
|
|
137
137
|
};
|
|
138
|
-
const currentValue =
|
|
138
|
+
const currentValue = position_1.calculateBaseAssetValue(market, netUserPosition);
|
|
139
139
|
netUserPosition.quoteAssetAmount = currentValue;
|
|
140
|
-
const prevMarketPrice =
|
|
140
|
+
const prevMarketPrice = __1.calculateMarkPrice(market);
|
|
141
141
|
const marketNewPeg = Object.assign({}, market);
|
|
142
142
|
marketNewPeg.amm = Object.assign({}, market.amm);
|
|
143
143
|
// const marketNewPeg = JSON.parse(JSON.stringify(market));
|
|
144
144
|
marketNewPeg.amm.pegMultiplier = newPeg;
|
|
145
|
-
console.log('Price moves from',
|
|
146
|
-
const cost =
|
|
145
|
+
console.log('Price moves from', __1.convertToNumber(prevMarketPrice), 'to', __1.convertToNumber(__1.calculateMarkPrice(marketNewPeg)));
|
|
146
|
+
const cost = __1.calculatePositionPNL(marketNewPeg, netUserPosition);
|
|
147
147
|
return cost;
|
|
148
148
|
}
|
|
149
149
|
exports.calculateRepegCost = calculateRepegCost;
|
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
|
|
13
|
+
return 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 =
|
|
43
|
+
const baseAssetPriceWithMantissa = 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,6 +9,6 @@ const amm_1 = require("./amm");
|
|
|
9
9
|
* @return markPrice : Precision MARK_PRICE_PRECISION
|
|
10
10
|
*/
|
|
11
11
|
function calculateMarkPrice(market) {
|
|
12
|
-
return
|
|
12
|
+
return amm_1.calculatePrice(market.amm.baseAssetReserve, market.amm.quoteAssetReserve, market.amm.pegMultiplier);
|
|
13
13
|
}
|
|
14
14
|
exports.calculateMarkPrice = calculateMarkPrice;
|
package/lib/math/position.js
CHANGED
|
@@ -22,7 +22,7 @@ function calculateBaseAssetValue(market, userPosition) {
|
|
|
22
22
|
const directionToClose = userPosition.baseAssetAmount.gt(numericConstants_1.ZERO)
|
|
23
23
|
? types_1.PositionDirection.SHORT
|
|
24
24
|
: types_1.PositionDirection.LONG;
|
|
25
|
-
const [newQuoteAssetReserve, _] =
|
|
25
|
+
const [newQuoteAssetReserve, _] = amm_1.calculateAmmReservesAfterSwap(market.amm, 'base', userPosition.baseAssetAmount.abs(), amm_1.getSwapDirection('base', directionToClose));
|
|
26
26
|
switch (directionToClose) {
|
|
27
27
|
case types_1.PositionDirection.SHORT:
|
|
28
28
|
return market.amm.quoteAssetReserve
|
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 =
|
|
28
|
+
const oldPrice = 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 =
|
|
34
|
-
const newPrice =
|
|
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);
|
|
35
35
|
if (direction == types_1.PositionDirection.SHORT) {
|
|
36
|
-
|
|
36
|
+
assert_1.assert(newPrice.lt(oldPrice));
|
|
37
37
|
}
|
|
38
38
|
else {
|
|
39
|
-
|
|
39
|
+
assert_1.assert(oldPrice.lt(newPrice));
|
|
40
40
|
}
|
|
41
41
|
const pctMaxSlippage = newPrice
|
|
42
42
|
.sub(oldPrice)
|
|
@@ -64,7 +64,7 @@ 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 [newQuoteAssetReserve, newBaseAssetReserve] =
|
|
67
|
+
const [newQuoteAssetReserve, newBaseAssetReserve] = amm_1.calculateAmmReservesAfterSwap(market.amm, inputAssetType, amount, amm_1.getSwapDirection(inputAssetType, direction));
|
|
68
68
|
const acquiredBase = market.amm.baseAssetReserve.sub(newBaseAssetReserve);
|
|
69
69
|
const acquiredQuote = market.amm.quoteAssetReserve.sub(newQuoteAssetReserve);
|
|
70
70
|
return [acquiredBase, acquiredQuote];
|
|
@@ -86,10 +86,10 @@ exports.calculateTradeAcquiredAmounts = calculateTradeAcquiredAmounts;
|
|
|
86
86
|
* ]
|
|
87
87
|
*/
|
|
88
88
|
function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAssetType = 'quote') {
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
const markPriceBefore =
|
|
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
93
|
if (targetPrice.gt(markPriceBefore)) {
|
|
94
94
|
const priceGap = targetPrice.sub(markPriceBefore);
|
|
95
95
|
const priceGapScaled = priceGap.mul(pct).div(MAXPCT);
|
|
@@ -114,11 +114,11 @@ function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAsse
|
|
|
114
114
|
let markPriceAfter;
|
|
115
115
|
if (markPriceBefore.gt(targetPrice)) {
|
|
116
116
|
// overestimate y2
|
|
117
|
-
baseAssetReserveAfter =
|
|
117
|
+
baseAssetReserveAfter = utils_1.squareRootBN(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).sub(biasModifier)).sub(new anchor_1.BN(1));
|
|
118
118
|
quoteAssetReserveAfter = k
|
|
119
119
|
.div(numericConstants_1.MARK_PRICE_PRECISION)
|
|
120
120
|
.div(baseAssetReserveAfter);
|
|
121
|
-
markPriceAfter =
|
|
121
|
+
markPriceAfter = amm_1.calculatePrice(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
|
|
122
122
|
direction = types_1.PositionDirection.SHORT;
|
|
123
123
|
tradeSize = quoteAssetReserveBefore
|
|
124
124
|
.sub(quoteAssetReserveAfter)
|
|
@@ -129,11 +129,11 @@ function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAsse
|
|
|
129
129
|
}
|
|
130
130
|
else if (markPriceBefore.lt(targetPrice)) {
|
|
131
131
|
// underestimate y2
|
|
132
|
-
baseAssetReserveAfter =
|
|
132
|
+
baseAssetReserveAfter = utils_1.squareRootBN(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).add(biasModifier)).add(new anchor_1.BN(1));
|
|
133
133
|
quoteAssetReserveAfter = k
|
|
134
134
|
.div(numericConstants_1.MARK_PRICE_PRECISION)
|
|
135
135
|
.div(baseAssetReserveAfter);
|
|
136
|
-
markPriceAfter =
|
|
136
|
+
markPriceAfter = amm_1.calculatePrice(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
|
|
137
137
|
direction = types_1.PositionDirection.LONG;
|
|
138
138
|
tradeSize = quoteAssetReserveAfter
|
|
139
139
|
.sub(quoteAssetReserveBefore)
|
|
@@ -160,8 +160,8 @@ function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAsse
|
|
|
160
160
|
.mul(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
|
|
161
161
|
.mul(numericConstants_1.MARK_PRICE_PRECISION)
|
|
162
162
|
.div(baseSize.abs());
|
|
163
|
-
|
|
164
|
-
|
|
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' +
|
|
165
165
|
tp2.toString() +
|
|
166
166
|
'>=' +
|
|
167
167
|
tp1.toString() +
|
package/lib/pythClient.js
CHANGED
|
@@ -18,7 +18,7 @@ class PythClient {
|
|
|
18
18
|
getPriceData(pricePublicKey) {
|
|
19
19
|
return __awaiter(this, void 0, void 0, function* () {
|
|
20
20
|
const account = yield this.connection.getAccountInfo(pricePublicKey);
|
|
21
|
-
return
|
|
21
|
+
return client_1.parsePriceData(account.data);
|
|
22
22
|
});
|
|
23
23
|
}
|
|
24
24
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@drift-labs/sdk",
|
|
3
|
-
"version": "0.1.17
|
|
3
|
+
"version": "0.1.17",
|
|
4
4
|
"main": "lib/index.js",
|
|
5
5
|
"types": "lib/index.d.ts",
|
|
6
6
|
"author": "crispheaney",
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
},
|
|
29
29
|
"dependencies": {
|
|
30
30
|
"@project-serum/anchor": "0.19.1-beta.1",
|
|
31
|
-
"@pythnetwork/client": "^2.
|
|
31
|
+
"@pythnetwork/client": "^2.5.1",
|
|
32
32
|
"@solana/spl-token": "^0.1.6",
|
|
33
33
|
"@solana/web3.js": "^1.22.0",
|
|
34
34
|
"@types/bn.js": "^5.1.0",
|