@drift-labs/sdk 0.1.16 → 0.1.17-master.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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.d.ts.map +1 -1
- package/lib/clearingHouseUser.js +20 -18
- package/lib/examples/makeTradeExample.js +10 -11
- package/lib/math/amm.js +7 -7
- package/lib/math/conversion.js +1 -1
- package/lib/math/funding.d.ts +2 -4
- package/lib/math/funding.d.ts.map +1 -1
- package/lib/math/funding.js +5 -7
- 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 +1 -1
- package/src/clearingHouseUser.ts +11 -10
- package/src/examples/makeTradeExample.ts +5 -11
- package/src/math/funding.ts +7 -6
|
@@ -34,7 +34,7 @@ class DefaultClearingHouseAccountSubscriber {
|
|
|
34
34
|
this.subscriptionPromise = new Promise((res) => {
|
|
35
35
|
this.subscriptionPromiseResolver = res;
|
|
36
36
|
});
|
|
37
|
-
const statePublicKey = yield addresses_1.getClearingHouseStateAccountPublicKey(this.program.programId);
|
|
37
|
+
const statePublicKey = yield (0, 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 addresses_1.getUserAccountPublicKey(this.program.programId, this.authority);
|
|
29
|
+
const userPublicKey = yield (0, 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 addresses_1.getClearingHouseStateAccountPublicKeyAndNonce(this.program.programId);
|
|
72
|
+
const [clearingHouseStatePublicKey, clearingHouseNonce] = yield (0, 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, _] = trade_1.calculateTargetPriceTrade(market, targetPrice);
|
|
170
|
-
const [newQuoteAssetAmount, newBaseAssetAmount] = amm_1.calculateAmmReservesAfterSwap(market.amm, 'quote', tradeSize, amm_1.getSwapDirection('quote', direction));
|
|
169
|
+
const [direction, tradeSize, _] = (0, trade_1.calculateTargetPriceTrade)(market, targetPrice);
|
|
170
|
+
const [newQuoteAssetAmount, newBaseAssetAmount] = (0, amm_1.calculateAmmReservesAfterSwap)(market.amm, 'quote', tradeSize, (0, 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 addresses_1.getClearingHouseStateAccountPublicKey(this.program.programId);
|
|
118
|
+
this.statePublicKey = yield (0, 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 addresses_1.getUserAccountPublicKeyAndNonce(this.program.programId, this.wallet.publicKey);
|
|
177
|
+
const [userPublicKey, userAccountNonce] = yield (0, 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 addresses_1.getUserAccountPublicKey(this.program.programId, this.wallet.publicKey);
|
|
216
|
+
this.userAccountPublicKey = yield (0, 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(utils_1.wrapInTx(yield this.getWithdrawCollateralIx(amount, collateralAccountPublicKey)), [], this.opts);
|
|
306
|
+
return this.txSender.send((0, 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(utils_1.wrapInTx(yield this.getOpenPositionIx(direction, amount, marketIndex, limitPrice, discountToken, referrer)), [], this.opts);
|
|
335
|
+
return yield this.txSender.send((0, 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(utils_1.wrapInTx(yield this.getClosePositionIx(marketIndex, discountToken, referrer)), [], this.opts);
|
|
393
|
+
return yield this.txSender.send((0, 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(utils_1.wrapInTx(yield this.getLiquidateIx(liquidateeUserAccountPublicKey)), [], this.opts);
|
|
441
|
+
return this.txSender.send((0, 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(utils_1.wrapInTx(yield this.getUpdateFundingRateIx(oracle, marketIndex)), [], this.opts);
|
|
485
|
+
return this.txSender.send((0, 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(utils_1.wrapInTx(yield this.getSettleFundingPaymentIx(userAccount, userPositionsAccount)), [], this.opts);
|
|
503
|
+
return this.txSender.send((0, utils_1.wrapInTx)(yield this.getSettleFundingPaymentIx(userAccount, userPositionsAccount)), [], this.opts);
|
|
504
504
|
});
|
|
505
505
|
}
|
|
506
506
|
getSettleFundingPaymentIx(userAccount, userPositionsAccount) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"clearingHouseUser.d.ts","sourceRoot":"","sources":["../src/clearingHouseUser.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,MAAM,OAAO,CAAC;AACvB,OAAO,EAA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;;;;;;;;;;;;;OAqBG;IACI,mBAAmB,CACzB,iBAAiB,EAAE,EAAE,EACrB,SAAS,EAAE,iBAAiB,EAC5B,sBAAsB,EAAE,EAAE,GACxB,EAAE;IAgGL;;;;;;OAMG;IACI,8BAA8B,CACpC,iBAAiB,EAAE,EAAE,EACrB,gBAAgB,EAAE,EAAE,EACpB,SAAS,EAAE,iBAAiB,GAC1B,EAAE;IAuCL;;;;OAIG;IACI,0BAA0B,CAAC,WAAW,EAAE,EAAE,GAAG,EAAE;IAQtD;;;;OAIG;IACH,OAAO,CAAC,oCAAoC;CAY5C"}
|
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 addresses_1.getUserAccountPublicKey(this.clearingHouse.program.programId, this.authority);
|
|
87
|
+
this.userAccountPublicKey = yield (0, 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(_1.calculatePositionPNL(market, marketPosition, withFunding));
|
|
125
|
+
return pnl.add((0, _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(_1.calculatePositionFundingPNL(market, marketPosition));
|
|
137
|
+
return pnl.add((0, _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(_1.calculateBaseAssetValue(market, marketPosition));
|
|
155
|
+
return positionValue.add((0, _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 _1.calculateBaseAssetValue(market, userPosition);
|
|
165
|
+
return (0, _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 = position_1.calculateEntryPrice(position);
|
|
184
|
+
const entryPrice = (0, position_1.calculateEntryPrice)(position);
|
|
185
185
|
if (amountToClose) {
|
|
186
186
|
if (amountToClose.eq(numericConstants_1.ZERO)) {
|
|
187
|
-
return [_1.calculateMarkPrice(market), numericConstants_1.ZERO];
|
|
187
|
+
return [(0, _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 = _1.calculateBaseAssetValue(market, position);
|
|
196
|
+
const baseAssetValue = (0, _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 = _1.calculateMarkPrice(this.clearingHouse.getMarket(targetMarket.marketIndex));
|
|
303
|
+
const currentPrice = (0, _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 = _1.calculateBaseAssetValue(market, proposedMarketPosition);
|
|
318
|
+
const proposedMarketPositionValueUSDC = (0, _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 = _1.calculateBaseAssetValue(market, proposedMarketPosition);
|
|
403
|
+
const proposedMarketPositionValueUSDC = (0, _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
|
|
@@ -413,26 +413,28 @@ class ClearingHouseUser {
|
|
|
413
413
|
}
|
|
414
414
|
let priceDelt;
|
|
415
415
|
if (proposedBaseAssetAmount.lt(numericConstants_1.ZERO)) {
|
|
416
|
-
priceDelt =
|
|
416
|
+
priceDelt = tc
|
|
417
417
|
.mul(thisLev)
|
|
418
|
-
.sub(tpv)
|
|
418
|
+
.sub(tpv)
|
|
419
419
|
.mul(numericConstants_1.PRICE_TO_QUOTE_PRECISION)
|
|
420
420
|
.div(thisLev.add(new bn_js_1.default(1)));
|
|
421
421
|
}
|
|
422
422
|
else {
|
|
423
|
-
priceDelt =
|
|
423
|
+
priceDelt = tc
|
|
424
424
|
.mul(thisLev)
|
|
425
|
-
.sub(tpv)
|
|
425
|
+
.sub(tpv)
|
|
426
426
|
.mul(numericConstants_1.PRICE_TO_QUOTE_PRECISION)
|
|
427
427
|
.div(thisLev.sub(new bn_js_1.default(1)));
|
|
428
428
|
}
|
|
429
429
|
let currentPrice;
|
|
430
430
|
if (positionBaseSizeChange.eq(numericConstants_1.ZERO)) {
|
|
431
|
-
currentPrice = _1.calculateMarkPrice(this.clearingHouse.getMarket(targetMarket.marketIndex));
|
|
431
|
+
currentPrice = (0, _1.calculateMarkPrice)(this.clearingHouse.getMarket(targetMarket.marketIndex));
|
|
432
432
|
}
|
|
433
433
|
else {
|
|
434
|
-
const direction = positionBaseSizeChange.gt(numericConstants_1.ZERO)
|
|
435
|
-
|
|
434
|
+
const direction = positionBaseSizeChange.gt(numericConstants_1.ZERO)
|
|
435
|
+
? _1.PositionDirection.LONG
|
|
436
|
+
: _1.PositionDirection.SHORT;
|
|
437
|
+
currentPrice = (0, _1.calculateTradeSlippage)(direction, positionBaseSizeChange.abs(), this.clearingHouse.getMarket(targetMarket.marketIndex), 'base')[3]; // newPrice after swap
|
|
436
438
|
}
|
|
437
439
|
// if the position value after the trade is less than total collateral, there is no liq price
|
|
438
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 = __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,26 +47,25 @@ 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.QUOTE_PRECISION);
|
|
55
|
+
const currentMarketPrice = (0, __2.calculateMarkPrice)(clearingHouse.getMarket(solMarketInfo.marketIndex));
|
|
56
|
+
const formattedPrice = (0, __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
|
-
const
|
|
60
|
+
const longAmount = new anchor_1.BN(5000).mul(__2.QUOTE_PRECISION);
|
|
61
|
+
const slippage = (0, __2.convertToNumber)((0, __2.calculateTradeSlippage)(__2.PositionDirection.LONG, longAmount, solMarketAccount)[0], __2.MARK_PRICE_PRECISION);
|
|
61
62
|
console.log(`Slippage for a $5000 LONG on the SOL market would be $${slippage}`);
|
|
62
63
|
// Make a $5000 LONG trade
|
|
63
|
-
yield clearingHouse.openPosition(__2.PositionDirection.LONG,
|
|
64
|
+
yield clearingHouse.openPosition(__2.PositionDirection.LONG, longAmount, solMarketInfo.marketIndex);
|
|
64
65
|
console.log(`LONGED $5000 SOL`);
|
|
65
|
-
// Make a $5000 LONG trade
|
|
66
|
-
yield clearingHouse.openPosition(__2.PositionDirection.LONG, new anchor_1.BN(5000).mul(__2.QUOTE_PRECISION), solMarketInfo.marketIndex);
|
|
67
|
-
console.log(`LONGED $5000 worth of SOL`);
|
|
68
66
|
// Reduce the position by $2000
|
|
69
|
-
|
|
67
|
+
const reduceAmount = new anchor_1.BN(2000).mul(__2.QUOTE_PRECISION);
|
|
68
|
+
yield clearingHouse.openPosition(__2.PositionDirection.SHORT, reduceAmount, solMarketInfo.marketIndex);
|
|
70
69
|
// Close the rest of the position
|
|
71
70
|
yield clearingHouse.closePosition(solMarketInfo.marketIndex);
|
|
72
71
|
});
|
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') {
|
|
@@ -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 = position_1.calculateBaseAssetValue(market, netUserPosition);
|
|
108
|
+
const currentValue = (0, 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 = __1.calculatePositionPNL(marketNewK, netUserPosition);
|
|
119
|
+
const cost = (0, __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 = position_1.calculateBaseAssetValue(market, netUserPosition);
|
|
138
|
+
const currentValue = (0, position_1.calculateBaseAssetValue)(market, netUserPosition);
|
|
139
139
|
netUserPosition.quoteAssetAmount = currentValue;
|
|
140
|
-
const prevMarketPrice = __1.calculateMarkPrice(market);
|
|
140
|
+
const prevMarketPrice = (0, __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', __1.convertToNumber(prevMarketPrice), 'to', __1.convertToNumber(__1.calculateMarkPrice(marketNewPeg)));
|
|
146
|
-
const cost = __1.calculatePositionPNL(marketNewPeg, netUserPosition);
|
|
145
|
+
console.log('Price moves from', (0, __1.convertToNumber)(prevMarketPrice), 'to', (0, __1.convertToNumber)((0, __1.calculateMarkPrice)(marketNewPeg)));
|
|
146
|
+
const cost = (0, __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 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.d.ts
CHANGED
|
@@ -22,18 +22,16 @@ export declare function calculateEstimatedFundingRate(market: Market, oraclePric
|
|
|
22
22
|
/**
|
|
23
23
|
*
|
|
24
24
|
* @param market
|
|
25
|
-
* @param
|
|
25
|
+
* @param oraclePriceData
|
|
26
26
|
* @param periodAdjustment
|
|
27
|
-
* @param estimationMethod
|
|
28
27
|
* @returns Estimated funding rate. : Precision //TODO-PRECISION
|
|
29
28
|
*/
|
|
30
29
|
export declare function calculateLongShortFundingRate(market: Market, oraclePriceData: PriceData, periodAdjustment?: BN): Promise<[BN, BN]>;
|
|
31
30
|
/**
|
|
32
31
|
*
|
|
33
32
|
* @param market
|
|
34
|
-
* @param
|
|
33
|
+
* @param oraclePriceData
|
|
35
34
|
* @param periodAdjustment
|
|
36
|
-
* @param estimationMethod
|
|
37
35
|
* @returns Estimated funding rate. : Precision //TODO-PRECISION
|
|
38
36
|
*/
|
|
39
37
|
export declare function calculateLongShortFundingRateAndLiveTwaps(market: Market, oraclePriceData: PriceData, periodAdjustment?: BN): Promise<[BN, BN, BN, BN]>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"funding.d.ts","sourceRoot":"","sources":["../../src/math/funding.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,uBAAuB,CAAC;AAC3C,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAOhD,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAGlC;;;;;;GAMG;AACH,wBAAsB,gCAAgC,CACrD,MAAM,EAAE,MAAM,EACd,eAAe,EAAE,SAAS,EAC1B,gBAAgB,GAAE,EAAc,GAC9B,OAAO,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,CA0K/B;AAED;;;;;;;GAOG;AACH,wBAAsB,6BAA6B,CAClD,MAAM,EAAE,MAAM,EACd,eAAe,EAAE,SAAS,EAC1B,gBAAgB,EAAE,EAAc,EAChC,gBAAgB,EAAE,cAAc,GAAG,YAAY,GAAG,QAAQ,GACxD,OAAO,CAAC,EAAE,CAAC,CAgBb;AAED
|
|
1
|
+
{"version":3,"file":"funding.d.ts","sourceRoot":"","sources":["../../src/math/funding.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,uBAAuB,CAAC;AAC3C,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAOhD,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAGlC;;;;;;GAMG;AACH,wBAAsB,gCAAgC,CACrD,MAAM,EAAE,MAAM,EACd,eAAe,EAAE,SAAS,EAC1B,gBAAgB,GAAE,EAAc,GAC9B,OAAO,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,CA0K/B;AAED;;;;;;;GAOG;AACH,wBAAsB,6BAA6B,CAClD,MAAM,EAAE,MAAM,EACd,eAAe,EAAE,SAAS,EAC1B,gBAAgB,EAAE,EAAc,EAChC,gBAAgB,EAAE,cAAc,GAAG,YAAY,GAAG,QAAQ,GACxD,OAAO,CAAC,EAAE,CAAC,CAgBb;AAED;;;;;;GAMG;AACH,wBAAsB,6BAA6B,CAClD,MAAM,EAAE,MAAM,EACd,eAAe,EAAE,SAAS,EAC1B,gBAAgB,GAAE,EAAc,GAC9B,OAAO,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,CAenB;AAED;;;;;;GAMG;AACH,wBAAsB,yCAAyC,CAC9D,MAAM,EAAE,MAAM,EACd,eAAe,EAAE,SAAS,EAC1B,gBAAgB,GAAE,EAAc,GAC9B,OAAO,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,CAe3B;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,MAAM,GAAG,EAAE,CAQvD"}
|
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))
|
|
@@ -78,7 +78,7 @@ function calculateAllEstimatedFundingRate(market, oraclePriceData, periodAdjustm
|
|
|
78
78
|
.add(timeSinceLastMarkChange.mul(oraclePriceStableWithMantissa))
|
|
79
79
|
.div(timeSinceLastOracleTwapUpdate.add(oracleTwapTimeSinceLastUpdate));
|
|
80
80
|
}
|
|
81
|
-
const twapSpread =
|
|
81
|
+
const twapSpread = lastMarkTwapWithMantissa.sub(lastOracleTwapWithMantissa);
|
|
82
82
|
const twapSpreadPct = twapSpread
|
|
83
83
|
.mul(numericConstants_1.MARK_PRICE_PRECISION)
|
|
84
84
|
.mul(new anchor_1.BN(100))
|
|
@@ -193,9 +193,8 @@ exports.calculateEstimatedFundingRate = calculateEstimatedFundingRate;
|
|
|
193
193
|
/**
|
|
194
194
|
*
|
|
195
195
|
* @param market
|
|
196
|
-
* @param
|
|
196
|
+
* @param oraclePriceData
|
|
197
197
|
* @param periodAdjustment
|
|
198
|
-
* @param estimationMethod
|
|
199
198
|
* @returns Estimated funding rate. : Precision //TODO-PRECISION
|
|
200
199
|
*/
|
|
201
200
|
function calculateLongShortFundingRate(market, oraclePriceData, periodAdjustment = new anchor_1.BN(1)) {
|
|
@@ -216,9 +215,8 @@ exports.calculateLongShortFundingRate = calculateLongShortFundingRate;
|
|
|
216
215
|
/**
|
|
217
216
|
*
|
|
218
217
|
* @param market
|
|
219
|
-
* @param
|
|
218
|
+
* @param oraclePriceData
|
|
220
219
|
* @param periodAdjustment
|
|
221
|
-
* @param estimationMethod
|
|
222
220
|
* @returns Estimated funding rate. : Precision //TODO-PRECISION
|
|
223
221
|
*/
|
|
224
222
|
function calculateLongShortFundingRateAndLiveTwaps(market, oraclePriceData, periodAdjustment = new anchor_1.BN(1)) {
|
|
@@ -244,7 +242,7 @@ exports.calculateLongShortFundingRateAndLiveTwaps = calculateLongShortFundingRat
|
|
|
244
242
|
function calculateFundingPool(market) {
|
|
245
243
|
// todo
|
|
246
244
|
const totalFeeLB = market.amm.totalFee.div(new anchor_1.BN(2));
|
|
247
|
-
const feePool = market.amm.totalFeeMinusDistributions.sub(totalFeeLB);
|
|
245
|
+
const feePool = anchor_1.BN.max(numericConstants_1.ZERO, market.amm.totalFeeMinusDistributions.sub(totalFeeLB));
|
|
248
246
|
return feePool;
|
|
249
247
|
}
|
|
250
248
|
exports.calculateFundingPool = calculateFundingPool;
|
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 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;
|
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, _] = amm_1.calculateAmmReservesAfterSwap(market.amm, 'base', userPosition.baseAssetAmount.abs(), amm_1.getSwapDirection('base', directionToClose));
|
|
25
|
+
const [newQuoteAssetReserve, _] = (0, amm_1.calculateAmmReservesAfterSwap)(market.amm, 'base', userPosition.baseAssetAmount.abs(), (0, 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 = 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,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] = amm_1.calculateAmmReservesAfterSwap(market.amm, inputAssetType, amount, amm_1.getSwapDirection(inputAssetType, direction));
|
|
67
|
+
const [newQuoteAssetReserve, newBaseAssetReserve] = (0, amm_1.calculateAmmReservesAfterSwap)(market.amm, inputAssetType, amount, (0, 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
|
-
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);
|
|
89
|
+
(0, assert_1.assert)(market.amm.baseAssetReserve.gt(numericConstants_1.ZERO));
|
|
90
|
+
(0, assert_1.assert)(targetPrice.gt(numericConstants_1.ZERO));
|
|
91
|
+
(0, assert_1.assert)(pct.lte(MAXPCT) && pct.gt(numericConstants_1.ZERO));
|
|
92
|
+
const markPriceBefore = (0, 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 = utils_1.squareRootBN(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).sub(biasModifier)).sub(new anchor_1.BN(1));
|
|
117
|
+
baseAssetReserveAfter = (0, 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 = amm_1.calculatePrice(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
|
|
121
|
+
markPriceAfter = (0, 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 = utils_1.squareRootBN(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).add(biasModifier)).add(new anchor_1.BN(1));
|
|
132
|
+
baseAssetReserveAfter = (0, 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 = amm_1.calculatePrice(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
|
|
136
|
+
markPriceAfter = (0, 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
|
-
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' +
|
|
163
|
+
(0, assert_1.assert)(tp1.sub(tp2).lte(originalDiff), 'Target Price Calculation incorrect');
|
|
164
|
+
(0, 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 client_1.parsePriceData(account.data);
|
|
21
|
+
return (0, client_1.parsePriceData)(account.data);
|
|
22
22
|
});
|
|
23
23
|
}
|
|
24
24
|
}
|
package/package.json
CHANGED
package/src/clearingHouseUser.ts
CHANGED
|
@@ -579,34 +579,35 @@ export class ClearingHouseUser {
|
|
|
579
579
|
|
|
580
580
|
let priceDelt;
|
|
581
581
|
if (proposedBaseAssetAmount.lt(ZERO)) {
|
|
582
|
-
priceDelt =
|
|
582
|
+
priceDelt = tc
|
|
583
583
|
.mul(thisLev)
|
|
584
|
-
.sub(tpv)
|
|
584
|
+
.sub(tpv)
|
|
585
585
|
.mul(PRICE_TO_QUOTE_PRECISION)
|
|
586
586
|
.div(thisLev.add(new BN(1)));
|
|
587
587
|
} else {
|
|
588
|
-
priceDelt =
|
|
588
|
+
priceDelt = tc
|
|
589
589
|
.mul(thisLev)
|
|
590
|
-
.sub(tpv)
|
|
590
|
+
.sub(tpv)
|
|
591
591
|
.mul(PRICE_TO_QUOTE_PRECISION)
|
|
592
592
|
.div(thisLev.sub(new BN(1)));
|
|
593
593
|
}
|
|
594
594
|
|
|
595
595
|
let currentPrice;
|
|
596
|
-
if(positionBaseSizeChange.eq(ZERO)){
|
|
596
|
+
if (positionBaseSizeChange.eq(ZERO)) {
|
|
597
597
|
currentPrice = calculateMarkPrice(
|
|
598
598
|
this.clearingHouse.getMarket(targetMarket.marketIndex)
|
|
599
599
|
);
|
|
600
|
-
} else{
|
|
601
|
-
const direction = positionBaseSizeChange.gt(ZERO)
|
|
600
|
+
} else {
|
|
601
|
+
const direction = positionBaseSizeChange.gt(ZERO)
|
|
602
|
+
? PositionDirection.LONG
|
|
603
|
+
: PositionDirection.SHORT;
|
|
602
604
|
currentPrice = calculateTradeSlippage(
|
|
603
605
|
direction,
|
|
604
606
|
positionBaseSizeChange.abs(),
|
|
605
607
|
this.clearingHouse.getMarket(targetMarket.marketIndex),
|
|
606
|
-
'base'
|
|
608
|
+
'base'
|
|
607
609
|
)[3]; // newPrice after swap
|
|
608
610
|
}
|
|
609
|
-
|
|
610
611
|
|
|
611
612
|
// if the position value after the trade is less than total collateral, there is no liq price
|
|
612
613
|
if (
|
|
@@ -622,7 +623,7 @@ export class ClearingHouseUser {
|
|
|
622
623
|
.mul(AMM_RESERVE_PRECISION)
|
|
623
624
|
.div(proposedBaseAssetAmount);
|
|
624
625
|
|
|
625
|
-
if(eatMargin2.gt(currentPrice)){
|
|
626
|
+
if (eatMargin2.gt(currentPrice)) {
|
|
626
627
|
return new BN(-1);
|
|
627
628
|
}
|
|
628
629
|
|
|
@@ -102,10 +102,11 @@ const main = async () => {
|
|
|
102
102
|
// Estimate the slippage for a $5000 LONG trade
|
|
103
103
|
const solMarketAccount = clearingHouse.getMarket(solMarketInfo.marketIndex);
|
|
104
104
|
|
|
105
|
+
const longAmount = new BN(5000).mul(QUOTE_PRECISION);
|
|
105
106
|
const slippage = convertToNumber(
|
|
106
107
|
calculateTradeSlippage(
|
|
107
108
|
PositionDirection.LONG,
|
|
108
|
-
|
|
109
|
+
longAmount,
|
|
109
110
|
solMarketAccount
|
|
110
111
|
)[0],
|
|
111
112
|
MARK_PRICE_PRECISION
|
|
@@ -118,23 +119,16 @@ const main = async () => {
|
|
|
118
119
|
// Make a $5000 LONG trade
|
|
119
120
|
await clearingHouse.openPosition(
|
|
120
121
|
PositionDirection.LONG,
|
|
121
|
-
|
|
122
|
+
longAmount,
|
|
122
123
|
solMarketInfo.marketIndex
|
|
123
124
|
);
|
|
124
125
|
console.log(`LONGED $5000 SOL`);
|
|
125
126
|
|
|
126
|
-
// Make a $5000 LONG trade
|
|
127
|
-
await clearingHouse.openPosition(
|
|
128
|
-
PositionDirection.LONG,
|
|
129
|
-
new BN(5000).mul(QUOTE_PRECISION),
|
|
130
|
-
solMarketInfo.marketIndex
|
|
131
|
-
);
|
|
132
|
-
console.log(`LONGED $5000 worth of SOL`);
|
|
133
|
-
|
|
134
127
|
// Reduce the position by $2000
|
|
128
|
+
const reduceAmount = new BN(2000).mul(QUOTE_PRECISION);
|
|
135
129
|
await clearingHouse.openPosition(
|
|
136
130
|
PositionDirection.SHORT,
|
|
137
|
-
|
|
131
|
+
reduceAmount,
|
|
138
132
|
solMarketInfo.marketIndex
|
|
139
133
|
);
|
|
140
134
|
|
package/src/math/funding.ts
CHANGED
|
@@ -99,7 +99,7 @@ export async function calculateAllEstimatedFundingRate(
|
|
|
99
99
|
.div(timeSinceLastOracleTwapUpdate.add(oracleTwapTimeSinceLastUpdate));
|
|
100
100
|
}
|
|
101
101
|
|
|
102
|
-
const twapSpread =
|
|
102
|
+
const twapSpread = lastMarkTwapWithMantissa.sub(lastOracleTwapWithMantissa);
|
|
103
103
|
|
|
104
104
|
const twapSpreadPct = twapSpread
|
|
105
105
|
.mul(MARK_PRICE_PRECISION)
|
|
@@ -226,9 +226,8 @@ export async function calculateEstimatedFundingRate(
|
|
|
226
226
|
/**
|
|
227
227
|
*
|
|
228
228
|
* @param market
|
|
229
|
-
* @param
|
|
229
|
+
* @param oraclePriceData
|
|
230
230
|
* @param periodAdjustment
|
|
231
|
-
* @param estimationMethod
|
|
232
231
|
* @returns Estimated funding rate. : Precision //TODO-PRECISION
|
|
233
232
|
*/
|
|
234
233
|
export async function calculateLongShortFundingRate(
|
|
@@ -255,9 +254,8 @@ export async function calculateLongShortFundingRate(
|
|
|
255
254
|
/**
|
|
256
255
|
*
|
|
257
256
|
* @param market
|
|
258
|
-
* @param
|
|
257
|
+
* @param oraclePriceData
|
|
259
258
|
* @param periodAdjustment
|
|
260
|
-
* @param estimationMethod
|
|
261
259
|
* @returns Estimated funding rate. : Precision //TODO-PRECISION
|
|
262
260
|
*/
|
|
263
261
|
export async function calculateLongShortFundingRateAndLiveTwaps(
|
|
@@ -289,6 +287,9 @@ export async function calculateLongShortFundingRateAndLiveTwaps(
|
|
|
289
287
|
export function calculateFundingPool(market: Market): BN {
|
|
290
288
|
// todo
|
|
291
289
|
const totalFeeLB = market.amm.totalFee.div(new BN(2));
|
|
292
|
-
const feePool =
|
|
290
|
+
const feePool = BN.max(
|
|
291
|
+
ZERO,
|
|
292
|
+
market.amm.totalFeeMinusDistributions.sub(totalFeeLB)
|
|
293
|
+
);
|
|
293
294
|
return feePool;
|
|
294
295
|
}
|