@drift-labs/sdk 2.31.1-beta.23 → 2.31.1-beta.25
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/VERSION +1 -1
- package/lib/idl/drift.json +1 -1
- package/lib/math/utils.d.ts +1 -0
- package/lib/math/utils.js +5 -1
- package/lib/user.d.ts +45 -1
- package/lib/user.js +227 -9
- package/package.json +1 -1
- package/src/idl/drift.json +1 -1
- package/src/math/utils.ts +4 -0
- package/src/user.ts +453 -15
package/VERSION
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
2.31.1-beta.
|
|
1
|
+
2.31.1-beta.25
|
package/lib/idl/drift.json
CHANGED
package/lib/math/utils.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { BN } from '../';
|
|
|
2
2
|
export declare function clampBN(x: BN, min: BN, max: BN): BN;
|
|
3
3
|
export declare const squareRootBN: (n: BN) => BN;
|
|
4
4
|
export declare const divCeil: (a: BN, b: BN) => BN;
|
|
5
|
+
export declare const sigNum: (x: BN) => BN;
|
|
5
6
|
/**
|
|
6
7
|
* calculates the time remaining until the next update based on a rounded, "on-the-hour" update schedule
|
|
7
8
|
* this schedule is used for Perpetual Funding Rate and Revenue -> Insurance Updates
|
package/lib/math/utils.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.timeRemainingUntilUpdate = exports.divCeil = exports.squareRootBN = exports.clampBN = void 0;
|
|
3
|
+
exports.timeRemainingUntilUpdate = exports.sigNum = exports.divCeil = exports.squareRootBN = exports.clampBN = void 0;
|
|
4
4
|
const __1 = require("../");
|
|
5
5
|
function clampBN(x, min, max) {
|
|
6
6
|
return __1.BN.max(min, __1.BN.min(x, max));
|
|
@@ -34,6 +34,10 @@ const divCeil = (a, b) => {
|
|
|
34
34
|
}
|
|
35
35
|
};
|
|
36
36
|
exports.divCeil = divCeil;
|
|
37
|
+
const sigNum = (x) => {
|
|
38
|
+
return x.isNeg() ? new __1.BN(-1) : new __1.BN(1);
|
|
39
|
+
};
|
|
40
|
+
exports.sigNum = sigNum;
|
|
37
41
|
/**
|
|
38
42
|
* calculates the time remaining until the next update based on a rounded, "on-the-hour" update schedule
|
|
39
43
|
* this schedule is used for Perpetual Funding Rate and Revenue -> Insurance Updates
|
package/lib/user.d.ts
CHANGED
|
@@ -42,6 +42,7 @@ export declare class User {
|
|
|
42
42
|
* @returns userSpotPosition
|
|
43
43
|
*/
|
|
44
44
|
getSpotPosition(marketIndex: number): SpotPosition | undefined;
|
|
45
|
+
getEmptySpotPosition(marketIndex: number): SpotPosition;
|
|
45
46
|
/**
|
|
46
47
|
* Returns the token amount for a given market. The spot market precision is based on the token mint decimals.
|
|
47
48
|
* Positive if it is a deposit, negative if it is a borrow.
|
|
@@ -126,7 +127,6 @@ export declare class User {
|
|
|
126
127
|
getSpotLiabilityValue(tokenAmount: BN, oraclePriceData: OraclePriceData, spotMarketAccount: SpotMarketAccount, marginCategory?: MarginCategory, liquidationBuffer?: BN, strict?: boolean, now?: BN): BN;
|
|
127
128
|
getSpotMarketAssetValue(marketIndex?: number, marginCategory?: MarginCategory, includeOpenOrders?: boolean, strict?: boolean, now?: BN): BN;
|
|
128
129
|
getSpotAssetValue(tokenAmount: BN, oraclePriceData: OraclePriceData, spotMarketAccount: SpotMarketAccount, marginCategory?: MarginCategory, strict?: boolean, now?: BN): BN;
|
|
129
|
-
getSpotTokenAmount(marketIndex: number): BN;
|
|
130
130
|
getSpotPositionValue(marketIndex: number, marginCategory?: MarginCategory, includeOpenOrders?: boolean, strict?: boolean, now?: BN): BN;
|
|
131
131
|
getNetSpotMarketValue(withWeightMarginCategory?: MarginCategory): BN;
|
|
132
132
|
/**
|
|
@@ -160,6 +160,12 @@ export declare class User {
|
|
|
160
160
|
* @returns : Precision TEN_THOUSAND
|
|
161
161
|
*/
|
|
162
162
|
getLeverage(): BN;
|
|
163
|
+
calculateLeverageFromComponents({ perpLiabilityValue, perpPnl, spotAssetValue, spotLiabilityValue, }: {
|
|
164
|
+
perpLiabilityValue: BN;
|
|
165
|
+
perpPnl: BN;
|
|
166
|
+
spotAssetValue: BN;
|
|
167
|
+
spotLiabilityValue: BN;
|
|
168
|
+
}): BN;
|
|
163
169
|
getLeverageComponents(): {
|
|
164
170
|
perpLiabilityValue: BN;
|
|
165
171
|
perpPnl: BN;
|
|
@@ -252,6 +258,44 @@ export declare class User {
|
|
|
252
258
|
* @returns tradeSizeAllowed : Precision QUOTE_PRECISION
|
|
253
259
|
*/
|
|
254
260
|
getMaxTradeSizeUSDCForSpot(targetMarketIndex: number, direction: PositionDirection, currentQuoteAssetValue?: BN, currentSpotMarketNetValue?: BN): BN;
|
|
261
|
+
/**
|
|
262
|
+
* Calculates the max amount of token that can be swapped from inMarket to outMarket
|
|
263
|
+
* Assumes swap happens at oracle price
|
|
264
|
+
*
|
|
265
|
+
* @param inMarketIndex
|
|
266
|
+
* @param outMarketIndex
|
|
267
|
+
* @param calculateSwap function to similate in to out swa
|
|
268
|
+
* @param iterationLimit how long to run appromixation before erroring out
|
|
269
|
+
*/
|
|
270
|
+
getMaxSwapAmount({ inMarketIndex, outMarketIndex, calculateSwap, iterationLimit, }: {
|
|
271
|
+
inMarketIndex: number;
|
|
272
|
+
outMarketIndex: number;
|
|
273
|
+
calculateSwap?: (inAmount: BN) => BN;
|
|
274
|
+
iterationLimit?: number;
|
|
275
|
+
}): {
|
|
276
|
+
inAmount: BN;
|
|
277
|
+
outAmount: BN;
|
|
278
|
+
leverage: BN;
|
|
279
|
+
};
|
|
280
|
+
cloneAndUpdateSpotPosition(position: SpotPosition, tokenAmount: BN, market: SpotMarketAccount): SpotPosition;
|
|
281
|
+
calculateSpotPositionFreeCollateralContribution(spotPosition: SpotPosition): BN;
|
|
282
|
+
calculateSpotPositionLeverageContribution(spotPosition: SpotPosition): {
|
|
283
|
+
totalAssetValue: BN;
|
|
284
|
+
totalLiabilityValue: BN;
|
|
285
|
+
};
|
|
286
|
+
/**
|
|
287
|
+
* Estimates what the user leverage will be after swap
|
|
288
|
+
* @param inMarketIndex
|
|
289
|
+
* @param outMarketIndex
|
|
290
|
+
* @param inAmount
|
|
291
|
+
* @param outAmount
|
|
292
|
+
*/
|
|
293
|
+
accountLeverageAfterSwap({ inMarketIndex, outMarketIndex, inAmount, outAmount, }: {
|
|
294
|
+
inMarketIndex: number;
|
|
295
|
+
outMarketIndex: number;
|
|
296
|
+
inAmount: BN;
|
|
297
|
+
outAmount: BN;
|
|
298
|
+
}): BN;
|
|
255
299
|
/**
|
|
256
300
|
* Returns the leverage ratio for the account after adding (or subtracting) the given quote size to the given position
|
|
257
301
|
* @param targetMarketIndex
|
package/lib/user.js
CHANGED
|
@@ -80,6 +80,17 @@ class User {
|
|
|
80
80
|
getSpotPosition(marketIndex) {
|
|
81
81
|
return this.getUserAccount().spotPositions.find((position) => position.marketIndex === marketIndex);
|
|
82
82
|
}
|
|
83
|
+
getEmptySpotPosition(marketIndex) {
|
|
84
|
+
return {
|
|
85
|
+
marketIndex,
|
|
86
|
+
scaledBalance: numericConstants_1.ZERO,
|
|
87
|
+
balanceType: _1.SpotBalanceType.DEPOSIT,
|
|
88
|
+
cumulativeDeposits: numericConstants_1.ZERO,
|
|
89
|
+
openAsks: numericConstants_1.ZERO,
|
|
90
|
+
openBids: numericConstants_1.ZERO,
|
|
91
|
+
openOrders: 0,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
83
94
|
/**
|
|
84
95
|
* Returns the token amount for a given market. The spot market precision is based on the token mint decimals.
|
|
85
96
|
* Positive if it is a deposit, negative if it is a borrow.
|
|
@@ -282,7 +293,7 @@ class User {
|
|
|
282
293
|
* @returns : Precision QUOTE_PRECISION
|
|
283
294
|
*/
|
|
284
295
|
getFreeCollateral() {
|
|
285
|
-
const totalCollateral = this.getTotalCollateral();
|
|
296
|
+
const totalCollateral = this.getTotalCollateral('Initial', true);
|
|
286
297
|
const initialMarginRequirement = this.getInitialMarginRequirement();
|
|
287
298
|
const freeCollateral = totalCollateral.sub(initialMarginRequirement);
|
|
288
299
|
return freeCollateral.gte(numericConstants_1.ZERO) ? freeCollateral : numericConstants_1.ZERO;
|
|
@@ -491,10 +502,6 @@ class User {
|
|
|
491
502
|
}
|
|
492
503
|
return assetValue;
|
|
493
504
|
}
|
|
494
|
-
getSpotTokenAmount(marketIndex) {
|
|
495
|
-
const spotPosition = this.getSpotPosition(marketIndex);
|
|
496
|
-
return (0, spotBalance_1.getTokenAmount)(spotPosition.scaledBalance, this.driftClient.getSpotMarketAccount(marketIndex), spotPosition.balanceType);
|
|
497
|
-
}
|
|
498
505
|
getSpotPositionValue(marketIndex, marginCategory, includeOpenOrders, strict = false, now) {
|
|
499
506
|
const { totalAssetValue, totalLiabilityValue } = this.getSpotMarketAssetAndLiabilityValue(marketIndex, marginCategory, undefined, includeOpenOrders, strict, now);
|
|
500
507
|
return totalAssetValue.sub(totalLiabilityValue);
|
|
@@ -671,8 +678,9 @@ class User {
|
|
|
671
678
|
* @returns : Precision TEN_THOUSAND
|
|
672
679
|
*/
|
|
673
680
|
getLeverage() {
|
|
674
|
-
|
|
675
|
-
|
|
681
|
+
return this.calculateLeverageFromComponents(this.getLeverageComponents());
|
|
682
|
+
}
|
|
683
|
+
calculateLeverageFromComponents({ perpLiabilityValue, perpPnl, spotAssetValue, spotLiabilityValue, }) {
|
|
676
684
|
const totalLiabilityValue = perpLiabilityValue.add(spotLiabilityValue);
|
|
677
685
|
const totalAssetValue = spotAssetValue.add(perpPnl);
|
|
678
686
|
const netAssetValue = totalAssetValue.sub(spotLiabilityValue);
|
|
@@ -1070,13 +1078,13 @@ class User {
|
|
|
1070
1078
|
// if the user is buying/selling and already short/long, need to account for closing out short/long
|
|
1071
1079
|
if ((0, types_1.isVariant)(direction, 'long') && currentSpotMarketNetValue.lt(numericConstants_1.ZERO)) {
|
|
1072
1080
|
tradeAmount = currentSpotMarketNetValue.abs();
|
|
1073
|
-
const marginRatio = (0, _1.calculateSpotMarketMarginRatio)(market, 'Initial', this.
|
|
1081
|
+
const marginRatio = (0, _1.calculateSpotMarketMarginRatio)(market, 'Initial', this.getTokenAmount(targetMarketIndex).abs(), _1.SpotBalanceType.BORROW);
|
|
1074
1082
|
freeCollateral = freeCollateral.add(tradeAmount.mul(new _1.BN(marginRatio)).div(numericConstants_1.MARGIN_PRECISION));
|
|
1075
1083
|
}
|
|
1076
1084
|
else if ((0, types_1.isVariant)(direction, 'short') &&
|
|
1077
1085
|
currentSpotMarketNetValue.gt(numericConstants_1.ZERO)) {
|
|
1078
1086
|
tradeAmount = currentSpotMarketNetValue;
|
|
1079
|
-
const marginRatio = (0, _1.calculateSpotMarketMarginRatio)(market, 'Initial', this.
|
|
1087
|
+
const marginRatio = (0, _1.calculateSpotMarketMarginRatio)(market, 'Initial', this.getTokenAmount(targetMarketIndex), _1.SpotBalanceType.DEPOSIT);
|
|
1080
1088
|
freeCollateral = freeCollateral.add(tradeAmount.mul(new _1.BN(marginRatio)).div(numericConstants_1.MARGIN_PRECISION));
|
|
1081
1089
|
}
|
|
1082
1090
|
tradeAmount = tradeAmount.add(freeCollateral.mul(numericConstants_1.MARGIN_PRECISION).div(new _1.BN(marginRatio)));
|
|
@@ -1089,6 +1097,216 @@ class User {
|
|
|
1089
1097
|
}
|
|
1090
1098
|
return tradeAmount;
|
|
1091
1099
|
}
|
|
1100
|
+
/**
|
|
1101
|
+
* Calculates the max amount of token that can be swapped from inMarket to outMarket
|
|
1102
|
+
* Assumes swap happens at oracle price
|
|
1103
|
+
*
|
|
1104
|
+
* @param inMarketIndex
|
|
1105
|
+
* @param outMarketIndex
|
|
1106
|
+
* @param calculateSwap function to similate in to out swa
|
|
1107
|
+
* @param iterationLimit how long to run appromixation before erroring out
|
|
1108
|
+
*/
|
|
1109
|
+
getMaxSwapAmount({ inMarketIndex, outMarketIndex, calculateSwap, iterationLimit = 1000, }) {
|
|
1110
|
+
const inMarket = this.driftClient.getSpotMarketAccount(inMarketIndex);
|
|
1111
|
+
const outMarket = this.driftClient.getSpotMarketAccount(outMarketIndex);
|
|
1112
|
+
const inOraclePrice = this.getOracleDataForSpotMarket(inMarketIndex).price;
|
|
1113
|
+
const outOraclePrice = this.getOracleDataForSpotMarket(outMarketIndex).price;
|
|
1114
|
+
const inPrecision = new _1.BN(10 ** inMarket.decimals);
|
|
1115
|
+
const outPrecision = new _1.BN(10 ** outMarket.decimals);
|
|
1116
|
+
const outSaferThanIn = inMarket.initialAssetWeight < outMarket.initialAssetWeight;
|
|
1117
|
+
const inSpotPosition = this.getSpotPosition(inMarketIndex) ||
|
|
1118
|
+
this.getEmptySpotPosition(inMarketIndex);
|
|
1119
|
+
const outSpotPosition = this.getSpotPosition(outMarketIndex) ||
|
|
1120
|
+
this.getEmptySpotPosition(outMarketIndex);
|
|
1121
|
+
const freeCollateral = this.getFreeCollateral();
|
|
1122
|
+
const inContributionInitial = this.calculateSpotPositionFreeCollateralContribution(inSpotPosition);
|
|
1123
|
+
const { totalAssetValue: inTotalAssetValueInitial, totalLiabilityValue: inTotalLiabilityValueInitial, } = this.calculateSpotPositionLeverageContribution(inSpotPosition);
|
|
1124
|
+
const outContributionInitial = this.calculateSpotPositionFreeCollateralContribution(outSpotPosition);
|
|
1125
|
+
const { totalAssetValue: outTotalAssetValueInitial, totalLiabilityValue: outTotalLiabilityValueInitial, } = this.calculateSpotPositionLeverageContribution(outSpotPosition);
|
|
1126
|
+
const initialContribution = inContributionInitial.add(outContributionInitial);
|
|
1127
|
+
const { perpLiabilityValue, perpPnl, spotAssetValue, spotLiabilityValue } = this.getLeverageComponents();
|
|
1128
|
+
if (!calculateSwap) {
|
|
1129
|
+
calculateSwap = (inSwap) => {
|
|
1130
|
+
return inSwap
|
|
1131
|
+
.mul(outPrecision)
|
|
1132
|
+
.mul(inOraclePrice)
|
|
1133
|
+
.div(outOraclePrice)
|
|
1134
|
+
.div(inPrecision);
|
|
1135
|
+
};
|
|
1136
|
+
}
|
|
1137
|
+
let inSwap = numericConstants_1.ZERO;
|
|
1138
|
+
let outSwap = numericConstants_1.ZERO;
|
|
1139
|
+
const inTokenAmount = this.getTokenAmount(inMarketIndex);
|
|
1140
|
+
if (freeCollateral.lt(numericConstants_1.ONE)) {
|
|
1141
|
+
if (outSaferThanIn && inTokenAmount.gt(numericConstants_1.ZERO)) {
|
|
1142
|
+
inSwap = inTokenAmount;
|
|
1143
|
+
outSwap = calculateSwap(inSwap);
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
else {
|
|
1147
|
+
let minSwap = numericConstants_1.ZERO;
|
|
1148
|
+
let maxSwap = freeCollateral
|
|
1149
|
+
.mul(inPrecision)
|
|
1150
|
+
.mul(numericConstants_1.SPOT_MARKET_WEIGHT_PRECISION)
|
|
1151
|
+
.div(numericConstants_1.SPOT_MARKET_WEIGHT_PRECISION.div(new _1.BN(100)))
|
|
1152
|
+
.div(inOraclePrice); // just assume user can go 100x
|
|
1153
|
+
inSwap = maxSwap.div(numericConstants_1.TWO);
|
|
1154
|
+
const error = _1.BN.min(numericConstants_1.QUOTE_PRECISION, freeCollateral.div(new _1.BN(100)));
|
|
1155
|
+
let i = 0;
|
|
1156
|
+
let freeCollateralAfter = freeCollateral;
|
|
1157
|
+
while (freeCollateralAfter.gt(error) || freeCollateralAfter.isNeg()) {
|
|
1158
|
+
outSwap = calculateSwap(inSwap);
|
|
1159
|
+
const inPositionAfter = this.cloneAndUpdateSpotPosition(inSpotPosition, inSwap.neg(), inMarket);
|
|
1160
|
+
const outPositionAfter = this.cloneAndUpdateSpotPosition(outSpotPosition, outSwap, outMarket);
|
|
1161
|
+
const inContributionAfter = this.calculateSpotPositionFreeCollateralContribution(inPositionAfter);
|
|
1162
|
+
const outContributionAfter = this.calculateSpotPositionFreeCollateralContribution(outPositionAfter);
|
|
1163
|
+
const contributionAfter = inContributionAfter.add(outContributionAfter);
|
|
1164
|
+
const contributionDelta = contributionAfter.sub(initialContribution);
|
|
1165
|
+
freeCollateralAfter = freeCollateral.add(contributionDelta);
|
|
1166
|
+
if (freeCollateralAfter.gt(error)) {
|
|
1167
|
+
minSwap = inSwap;
|
|
1168
|
+
inSwap = minSwap.add(maxSwap).div(numericConstants_1.TWO);
|
|
1169
|
+
}
|
|
1170
|
+
else if (freeCollateralAfter.isNeg()) {
|
|
1171
|
+
maxSwap = inSwap;
|
|
1172
|
+
inSwap = minSwap.add(maxSwap).div(numericConstants_1.TWO);
|
|
1173
|
+
}
|
|
1174
|
+
if (i++ > iterationLimit) {
|
|
1175
|
+
throw new Error('getMaxSwapAmount iteration limit reached');
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
const inPositionAfter = this.cloneAndUpdateSpotPosition(inSpotPosition, inSwap.neg(), inMarket);
|
|
1180
|
+
const outPositionAfter = this.cloneAndUpdateSpotPosition(outSpotPosition, outSwap, outMarket);
|
|
1181
|
+
const { totalAssetValue: inTotalAssetValueAfter, totalLiabilityValue: inTotalLiabilityValueAfter, } = this.calculateSpotPositionLeverageContribution(inPositionAfter);
|
|
1182
|
+
const { totalAssetValue: outTotalAssetValueAfter, totalLiabilityValue: outTotalLiabilityValueAfter, } = this.calculateSpotPositionLeverageContribution(outPositionAfter);
|
|
1183
|
+
const spotAssetValueDelta = inTotalAssetValueAfter
|
|
1184
|
+
.add(outTotalAssetValueAfter)
|
|
1185
|
+
.sub(inTotalAssetValueInitial)
|
|
1186
|
+
.sub(outTotalAssetValueInitial);
|
|
1187
|
+
const spotLiabilityValueDelta = inTotalLiabilityValueAfter
|
|
1188
|
+
.add(outTotalLiabilityValueAfter)
|
|
1189
|
+
.sub(inTotalLiabilityValueInitial)
|
|
1190
|
+
.sub(outTotalLiabilityValueInitial);
|
|
1191
|
+
const spotAssetValueAfter = spotAssetValue.add(spotAssetValueDelta);
|
|
1192
|
+
const spotLiabilityValueAfter = spotLiabilityValue.add(spotLiabilityValueDelta);
|
|
1193
|
+
const leverage = this.calculateLeverageFromComponents({
|
|
1194
|
+
perpLiabilityValue,
|
|
1195
|
+
perpPnl,
|
|
1196
|
+
spotAssetValue: spotAssetValueAfter,
|
|
1197
|
+
spotLiabilityValue: spotLiabilityValueAfter,
|
|
1198
|
+
});
|
|
1199
|
+
return { inAmount: inSwap, outAmount: outSwap, leverage };
|
|
1200
|
+
}
|
|
1201
|
+
cloneAndUpdateSpotPosition(position, tokenAmount, market) {
|
|
1202
|
+
const clonedPosition = Object.assign({}, position);
|
|
1203
|
+
if (tokenAmount.eq(numericConstants_1.ZERO)) {
|
|
1204
|
+
return clonedPosition;
|
|
1205
|
+
}
|
|
1206
|
+
const preTokenAmount = (0, _1.getSignedTokenAmount)((0, spotBalance_1.getTokenAmount)(position.scaledBalance, market, position.balanceType), position.balanceType);
|
|
1207
|
+
if ((0, _1.sigNum)(preTokenAmount).eq((0, _1.sigNum)(tokenAmount))) {
|
|
1208
|
+
const scaledBalanceDelta = (0, _1.getBalance)(tokenAmount.abs(), market, position.balanceType);
|
|
1209
|
+
clonedPosition.scaledBalance =
|
|
1210
|
+
clonedPosition.scaledBalance.add(scaledBalanceDelta);
|
|
1211
|
+
return clonedPosition;
|
|
1212
|
+
}
|
|
1213
|
+
const updateDirection = tokenAmount.isNeg()
|
|
1214
|
+
? _1.SpotBalanceType.BORROW
|
|
1215
|
+
: _1.SpotBalanceType.DEPOSIT;
|
|
1216
|
+
if (tokenAmount.abs().gte(preTokenAmount.abs())) {
|
|
1217
|
+
clonedPosition.scaledBalance = (0, _1.getBalance)(tokenAmount.abs().sub(preTokenAmount.abs()), market, updateDirection);
|
|
1218
|
+
clonedPosition.balanceType = updateDirection;
|
|
1219
|
+
}
|
|
1220
|
+
else {
|
|
1221
|
+
const scaledBalanceDelta = (0, _1.getBalance)(tokenAmount.abs(), market, position.balanceType);
|
|
1222
|
+
clonedPosition.scaledBalance =
|
|
1223
|
+
clonedPosition.scaledBalance.sub(scaledBalanceDelta);
|
|
1224
|
+
}
|
|
1225
|
+
return clonedPosition;
|
|
1226
|
+
}
|
|
1227
|
+
calculateSpotPositionFreeCollateralContribution(spotPosition) {
|
|
1228
|
+
let freeCollateralContribution = numericConstants_1.ZERO;
|
|
1229
|
+
const now = new _1.BN(new Date().getTime() / 1000);
|
|
1230
|
+
const strict = true;
|
|
1231
|
+
const marginCategory = 'Initial';
|
|
1232
|
+
const spotMarketAccount = this.driftClient.getSpotMarketAccount(spotPosition.marketIndex);
|
|
1233
|
+
const oraclePriceData = this.getOracleDataForSpotMarket(spotPosition.marketIndex);
|
|
1234
|
+
const [worstCaseTokenAmount, worstCaseQuoteTokenAmount] = (0, spotPosition_1.getWorstCaseTokenAmounts)(spotPosition, spotMarketAccount, oraclePriceData);
|
|
1235
|
+
if (worstCaseTokenAmount.gt(numericConstants_1.ZERO)) {
|
|
1236
|
+
const baseAssetValue = this.getSpotAssetValue(worstCaseTokenAmount, oraclePriceData, spotMarketAccount, marginCategory, strict, now);
|
|
1237
|
+
freeCollateralContribution =
|
|
1238
|
+
freeCollateralContribution.add(baseAssetValue);
|
|
1239
|
+
}
|
|
1240
|
+
else {
|
|
1241
|
+
const baseLiabilityValue = this.getSpotLiabilityValue(worstCaseTokenAmount, oraclePriceData, spotMarketAccount, marginCategory, undefined, strict, now).abs();
|
|
1242
|
+
freeCollateralContribution =
|
|
1243
|
+
freeCollateralContribution.sub(baseLiabilityValue);
|
|
1244
|
+
}
|
|
1245
|
+
freeCollateralContribution.add(worstCaseQuoteTokenAmount);
|
|
1246
|
+
return freeCollateralContribution;
|
|
1247
|
+
}
|
|
1248
|
+
calculateSpotPositionLeverageContribution(spotPosition) {
|
|
1249
|
+
let totalAssetValue = numericConstants_1.ZERO;
|
|
1250
|
+
let totalLiabilityValue = numericConstants_1.ZERO;
|
|
1251
|
+
const now = new _1.BN(new Date().getTime() / 1000);
|
|
1252
|
+
const spotMarketAccount = this.driftClient.getSpotMarketAccount(spotPosition.marketIndex);
|
|
1253
|
+
const oraclePriceData = this.getOracleDataForSpotMarket(spotPosition.marketIndex);
|
|
1254
|
+
const [worstCaseTokenAmount, worstCaseQuoteTokenAmount] = (0, spotPosition_1.getWorstCaseTokenAmounts)(spotPosition, spotMarketAccount, oraclePriceData);
|
|
1255
|
+
if (worstCaseTokenAmount.gt(numericConstants_1.ZERO)) {
|
|
1256
|
+
totalAssetValue = this.getSpotAssetValue(worstCaseTokenAmount, oraclePriceData, spotMarketAccount, undefined, false, now);
|
|
1257
|
+
}
|
|
1258
|
+
else {
|
|
1259
|
+
totalLiabilityValue = this.getSpotLiabilityValue(worstCaseTokenAmount, oraclePriceData, spotMarketAccount, undefined, undefined, false, now).abs();
|
|
1260
|
+
}
|
|
1261
|
+
if (worstCaseQuoteTokenAmount.gt(numericConstants_1.ZERO)) {
|
|
1262
|
+
totalAssetValue = totalAssetValue.add(worstCaseQuoteTokenAmount);
|
|
1263
|
+
}
|
|
1264
|
+
else {
|
|
1265
|
+
totalLiabilityValue = totalLiabilityValue.add(worstCaseQuoteTokenAmount.abs());
|
|
1266
|
+
}
|
|
1267
|
+
return {
|
|
1268
|
+
totalAssetValue,
|
|
1269
|
+
totalLiabilityValue,
|
|
1270
|
+
};
|
|
1271
|
+
}
|
|
1272
|
+
/**
|
|
1273
|
+
* Estimates what the user leverage will be after swap
|
|
1274
|
+
* @param inMarketIndex
|
|
1275
|
+
* @param outMarketIndex
|
|
1276
|
+
* @param inAmount
|
|
1277
|
+
* @param outAmount
|
|
1278
|
+
*/
|
|
1279
|
+
accountLeverageAfterSwap({ inMarketIndex, outMarketIndex, inAmount, outAmount, }) {
|
|
1280
|
+
const inMarket = this.driftClient.getSpotMarketAccount(inMarketIndex);
|
|
1281
|
+
const outMarket = this.driftClient.getSpotMarketAccount(outMarketIndex);
|
|
1282
|
+
const inSpotPosition = this.getSpotPosition(inMarketIndex) ||
|
|
1283
|
+
this.getEmptySpotPosition(inMarketIndex);
|
|
1284
|
+
const outSpotPosition = this.getSpotPosition(outMarketIndex) ||
|
|
1285
|
+
this.getEmptySpotPosition(outMarketIndex);
|
|
1286
|
+
const { totalAssetValue: inTotalAssetValueInitial, totalLiabilityValue: inTotalLiabilityValueInitial, } = this.calculateSpotPositionLeverageContribution(inSpotPosition);
|
|
1287
|
+
const { totalAssetValue: outTotalAssetValueInitial, totalLiabilityValue: outTotalLiabilityValueInitial, } = this.calculateSpotPositionLeverageContribution(outSpotPosition);
|
|
1288
|
+
const { perpLiabilityValue, perpPnl, spotAssetValue, spotLiabilityValue } = this.getLeverageComponents();
|
|
1289
|
+
const inPositionAfter = this.cloneAndUpdateSpotPosition(inSpotPosition, inAmount.abs().neg(), inMarket);
|
|
1290
|
+
const outPositionAfter = this.cloneAndUpdateSpotPosition(outSpotPosition, outAmount.abs(), outMarket);
|
|
1291
|
+
const { totalAssetValue: inTotalAssetValueAfter, totalLiabilityValue: inTotalLiabilityValueAfter, } = this.calculateSpotPositionLeverageContribution(inPositionAfter);
|
|
1292
|
+
const { totalAssetValue: outTotalAssetValueAfter, totalLiabilityValue: outTotalLiabilityValueAfter, } = this.calculateSpotPositionLeverageContribution(outPositionAfter);
|
|
1293
|
+
const spotAssetValueDelta = inTotalAssetValueAfter
|
|
1294
|
+
.add(outTotalAssetValueAfter)
|
|
1295
|
+
.sub(inTotalAssetValueInitial)
|
|
1296
|
+
.sub(outTotalAssetValueInitial);
|
|
1297
|
+
const spotLiabilityValueDelta = inTotalLiabilityValueAfter
|
|
1298
|
+
.add(outTotalLiabilityValueAfter)
|
|
1299
|
+
.sub(inTotalLiabilityValueInitial)
|
|
1300
|
+
.sub(outTotalLiabilityValueInitial);
|
|
1301
|
+
const spotAssetValueAfter = spotAssetValue.add(spotAssetValueDelta);
|
|
1302
|
+
const spotLiabilityValueAfter = spotLiabilityValue.add(spotLiabilityValueDelta);
|
|
1303
|
+
return this.calculateLeverageFromComponents({
|
|
1304
|
+
perpLiabilityValue,
|
|
1305
|
+
perpPnl,
|
|
1306
|
+
spotAssetValue: spotAssetValueAfter,
|
|
1307
|
+
spotLiabilityValue: spotLiabilityValueAfter,
|
|
1308
|
+
});
|
|
1309
|
+
}
|
|
1092
1310
|
// TODO - should this take the price impact of the trade into account for strict accuracy?
|
|
1093
1311
|
/**
|
|
1094
1312
|
* Returns the leverage ratio for the account after adding (or subtracting) the given quote size to the given position
|
package/package.json
CHANGED
package/src/idl/drift.json
CHANGED
package/src/math/utils.ts
CHANGED
|
@@ -34,6 +34,10 @@ export const divCeil = (a: BN, b: BN): BN => {
|
|
|
34
34
|
}
|
|
35
35
|
};
|
|
36
36
|
|
|
37
|
+
export const sigNum = (x: BN): BN => {
|
|
38
|
+
return x.isNeg() ? new BN(-1) : new BN(1);
|
|
39
|
+
};
|
|
40
|
+
|
|
37
41
|
/**
|
|
38
42
|
* calculates the time remaining until the next update based on a rounded, "on-the-hour" update schedule
|
|
39
43
|
* this schedule is used for Perpetual Funding Rate and Revenue -> Insurance Updates
|
package/src/user.ts
CHANGED
|
@@ -28,6 +28,8 @@ import {
|
|
|
28
28
|
OPEN_ORDER_MARGIN_REQUIREMENT,
|
|
29
29
|
FIVE_MINUTE,
|
|
30
30
|
BASE_PRECISION,
|
|
31
|
+
ONE,
|
|
32
|
+
TWO,
|
|
31
33
|
} from './constants/numericConstants';
|
|
32
34
|
import {
|
|
33
35
|
UserAccountSubscriber,
|
|
@@ -50,6 +52,8 @@ import {
|
|
|
50
52
|
calculateSpotMarketMarginRatio,
|
|
51
53
|
getSignedTokenAmount,
|
|
52
54
|
SpotBalanceType,
|
|
55
|
+
sigNum,
|
|
56
|
+
getBalance,
|
|
53
57
|
} from '.';
|
|
54
58
|
import {
|
|
55
59
|
getTokenAmount,
|
|
@@ -165,6 +169,18 @@ export class User {
|
|
|
165
169
|
);
|
|
166
170
|
}
|
|
167
171
|
|
|
172
|
+
getEmptySpotPosition(marketIndex: number): SpotPosition {
|
|
173
|
+
return {
|
|
174
|
+
marketIndex,
|
|
175
|
+
scaledBalance: ZERO,
|
|
176
|
+
balanceType: SpotBalanceType.DEPOSIT,
|
|
177
|
+
cumulativeDeposits: ZERO,
|
|
178
|
+
openAsks: ZERO,
|
|
179
|
+
openBids: ZERO,
|
|
180
|
+
openOrders: 0,
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
|
|
168
184
|
/**
|
|
169
185
|
* Returns the token amount for a given market. The spot market precision is based on the token mint decimals.
|
|
170
186
|
* Positive if it is a deposit, negative if it is a borrow.
|
|
@@ -442,7 +458,7 @@ export class User {
|
|
|
442
458
|
* @returns : Precision QUOTE_PRECISION
|
|
443
459
|
*/
|
|
444
460
|
public getFreeCollateral(): BN {
|
|
445
|
-
const totalCollateral = this.getTotalCollateral();
|
|
461
|
+
const totalCollateral = this.getTotalCollateral('Initial', true);
|
|
446
462
|
const initialMarginRequirement = this.getInitialMarginRequirement();
|
|
447
463
|
const freeCollateral = totalCollateral.sub(initialMarginRequirement);
|
|
448
464
|
return freeCollateral.gte(ZERO) ? freeCollateral : ZERO;
|
|
@@ -918,15 +934,6 @@ export class User {
|
|
|
918
934
|
return assetValue;
|
|
919
935
|
}
|
|
920
936
|
|
|
921
|
-
public getSpotTokenAmount(marketIndex: number): BN {
|
|
922
|
-
const spotPosition = this.getSpotPosition(marketIndex);
|
|
923
|
-
return getTokenAmount(
|
|
924
|
-
spotPosition.scaledBalance,
|
|
925
|
-
this.driftClient.getSpotMarketAccount(marketIndex),
|
|
926
|
-
spotPosition.balanceType
|
|
927
|
-
);
|
|
928
|
-
}
|
|
929
|
-
|
|
930
937
|
public getSpotPositionValue(
|
|
931
938
|
marketIndex: number,
|
|
932
939
|
marginCategory?: MarginCategory,
|
|
@@ -1231,10 +1238,20 @@ export class User {
|
|
|
1231
1238
|
* @returns : Precision TEN_THOUSAND
|
|
1232
1239
|
*/
|
|
1233
1240
|
public getLeverage(): BN {
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
this.getLeverageComponents();
|
|
1241
|
+
return this.calculateLeverageFromComponents(this.getLeverageComponents());
|
|
1242
|
+
}
|
|
1237
1243
|
|
|
1244
|
+
calculateLeverageFromComponents({
|
|
1245
|
+
perpLiabilityValue,
|
|
1246
|
+
perpPnl,
|
|
1247
|
+
spotAssetValue,
|
|
1248
|
+
spotLiabilityValue,
|
|
1249
|
+
}: {
|
|
1250
|
+
perpLiabilityValue: BN;
|
|
1251
|
+
perpPnl: BN;
|
|
1252
|
+
spotAssetValue: BN;
|
|
1253
|
+
spotLiabilityValue: BN;
|
|
1254
|
+
}): BN {
|
|
1238
1255
|
const totalLiabilityValue = perpLiabilityValue.add(spotLiabilityValue);
|
|
1239
1256
|
const totalAssetValue = spotAssetValue.add(perpPnl);
|
|
1240
1257
|
const netAssetValue = totalAssetValue.sub(spotLiabilityValue);
|
|
@@ -1925,7 +1942,7 @@ export class User {
|
|
|
1925
1942
|
const marginRatio = calculateSpotMarketMarginRatio(
|
|
1926
1943
|
market,
|
|
1927
1944
|
'Initial',
|
|
1928
|
-
this.
|
|
1945
|
+
this.getTokenAmount(targetMarketIndex).abs(),
|
|
1929
1946
|
SpotBalanceType.BORROW
|
|
1930
1947
|
);
|
|
1931
1948
|
freeCollateral = freeCollateral.add(
|
|
@@ -1939,7 +1956,7 @@ export class User {
|
|
|
1939
1956
|
const marginRatio = calculateSpotMarketMarginRatio(
|
|
1940
1957
|
market,
|
|
1941
1958
|
'Initial',
|
|
1942
|
-
this.
|
|
1959
|
+
this.getTokenAmount(targetMarketIndex),
|
|
1943
1960
|
SpotBalanceType.DEPOSIT
|
|
1944
1961
|
);
|
|
1945
1962
|
freeCollateral = freeCollateral.add(
|
|
@@ -1962,6 +1979,427 @@ export class User {
|
|
|
1962
1979
|
return tradeAmount;
|
|
1963
1980
|
}
|
|
1964
1981
|
|
|
1982
|
+
/**
|
|
1983
|
+
* Calculates the max amount of token that can be swapped from inMarket to outMarket
|
|
1984
|
+
* Assumes swap happens at oracle price
|
|
1985
|
+
*
|
|
1986
|
+
* @param inMarketIndex
|
|
1987
|
+
* @param outMarketIndex
|
|
1988
|
+
* @param calculateSwap function to similate in to out swa
|
|
1989
|
+
* @param iterationLimit how long to run appromixation before erroring out
|
|
1990
|
+
*/
|
|
1991
|
+
public getMaxSwapAmount({
|
|
1992
|
+
inMarketIndex,
|
|
1993
|
+
outMarketIndex,
|
|
1994
|
+
calculateSwap,
|
|
1995
|
+
iterationLimit = 1000,
|
|
1996
|
+
}: {
|
|
1997
|
+
inMarketIndex: number;
|
|
1998
|
+
outMarketIndex: number;
|
|
1999
|
+
calculateSwap?: (inAmount: BN) => BN;
|
|
2000
|
+
iterationLimit?: number;
|
|
2001
|
+
}): { inAmount: BN; outAmount: BN; leverage: BN } {
|
|
2002
|
+
const inMarket = this.driftClient.getSpotMarketAccount(inMarketIndex);
|
|
2003
|
+
const outMarket = this.driftClient.getSpotMarketAccount(outMarketIndex);
|
|
2004
|
+
|
|
2005
|
+
const inOraclePrice = this.getOracleDataForSpotMarket(inMarketIndex).price;
|
|
2006
|
+
const outOraclePrice =
|
|
2007
|
+
this.getOracleDataForSpotMarket(outMarketIndex).price;
|
|
2008
|
+
|
|
2009
|
+
const inPrecision = new BN(10 ** inMarket.decimals);
|
|
2010
|
+
const outPrecision = new BN(10 ** outMarket.decimals);
|
|
2011
|
+
|
|
2012
|
+
const outSaferThanIn =
|
|
2013
|
+
inMarket.initialAssetWeight < outMarket.initialAssetWeight;
|
|
2014
|
+
|
|
2015
|
+
const inSpotPosition =
|
|
2016
|
+
this.getSpotPosition(inMarketIndex) ||
|
|
2017
|
+
this.getEmptySpotPosition(inMarketIndex);
|
|
2018
|
+
const outSpotPosition =
|
|
2019
|
+
this.getSpotPosition(outMarketIndex) ||
|
|
2020
|
+
this.getEmptySpotPosition(outMarketIndex);
|
|
2021
|
+
|
|
2022
|
+
const freeCollateral = this.getFreeCollateral();
|
|
2023
|
+
|
|
2024
|
+
const inContributionInitial =
|
|
2025
|
+
this.calculateSpotPositionFreeCollateralContribution(inSpotPosition);
|
|
2026
|
+
const {
|
|
2027
|
+
totalAssetValue: inTotalAssetValueInitial,
|
|
2028
|
+
totalLiabilityValue: inTotalLiabilityValueInitial,
|
|
2029
|
+
} = this.calculateSpotPositionLeverageContribution(inSpotPosition);
|
|
2030
|
+
const outContributionInitial =
|
|
2031
|
+
this.calculateSpotPositionFreeCollateralContribution(outSpotPosition);
|
|
2032
|
+
const {
|
|
2033
|
+
totalAssetValue: outTotalAssetValueInitial,
|
|
2034
|
+
totalLiabilityValue: outTotalLiabilityValueInitial,
|
|
2035
|
+
} = this.calculateSpotPositionLeverageContribution(outSpotPosition);
|
|
2036
|
+
const initialContribution = inContributionInitial.add(
|
|
2037
|
+
outContributionInitial
|
|
2038
|
+
);
|
|
2039
|
+
|
|
2040
|
+
const { perpLiabilityValue, perpPnl, spotAssetValue, spotLiabilityValue } =
|
|
2041
|
+
this.getLeverageComponents();
|
|
2042
|
+
|
|
2043
|
+
if (!calculateSwap) {
|
|
2044
|
+
calculateSwap = (inSwap: BN) => {
|
|
2045
|
+
return inSwap
|
|
2046
|
+
.mul(outPrecision)
|
|
2047
|
+
.mul(inOraclePrice)
|
|
2048
|
+
.div(outOraclePrice)
|
|
2049
|
+
.div(inPrecision);
|
|
2050
|
+
};
|
|
2051
|
+
}
|
|
2052
|
+
|
|
2053
|
+
let inSwap = ZERO;
|
|
2054
|
+
let outSwap = ZERO;
|
|
2055
|
+
const inTokenAmount = this.getTokenAmount(inMarketIndex);
|
|
2056
|
+
if (freeCollateral.lt(ONE)) {
|
|
2057
|
+
if (outSaferThanIn && inTokenAmount.gt(ZERO)) {
|
|
2058
|
+
inSwap = inTokenAmount;
|
|
2059
|
+
outSwap = calculateSwap(inSwap);
|
|
2060
|
+
}
|
|
2061
|
+
} else {
|
|
2062
|
+
let minSwap = ZERO;
|
|
2063
|
+
let maxSwap = freeCollateral
|
|
2064
|
+
.mul(inPrecision)
|
|
2065
|
+
.mul(SPOT_MARKET_WEIGHT_PRECISION)
|
|
2066
|
+
.div(SPOT_MARKET_WEIGHT_PRECISION.div(new BN(100)))
|
|
2067
|
+
.div(inOraclePrice); // just assume user can go 100x
|
|
2068
|
+
inSwap = maxSwap.div(TWO);
|
|
2069
|
+
const error = BN.min(QUOTE_PRECISION, freeCollateral.div(new BN(100)));
|
|
2070
|
+
|
|
2071
|
+
let i = 0;
|
|
2072
|
+
let freeCollateralAfter = freeCollateral;
|
|
2073
|
+
while (freeCollateralAfter.gt(error) || freeCollateralAfter.isNeg()) {
|
|
2074
|
+
outSwap = calculateSwap(inSwap);
|
|
2075
|
+
|
|
2076
|
+
const inPositionAfter = this.cloneAndUpdateSpotPosition(
|
|
2077
|
+
inSpotPosition,
|
|
2078
|
+
inSwap.neg(),
|
|
2079
|
+
inMarket
|
|
2080
|
+
);
|
|
2081
|
+
const outPositionAfter = this.cloneAndUpdateSpotPosition(
|
|
2082
|
+
outSpotPosition,
|
|
2083
|
+
outSwap,
|
|
2084
|
+
outMarket
|
|
2085
|
+
);
|
|
2086
|
+
|
|
2087
|
+
const inContributionAfter =
|
|
2088
|
+
this.calculateSpotPositionFreeCollateralContribution(inPositionAfter);
|
|
2089
|
+
const outContributionAfter =
|
|
2090
|
+
this.calculateSpotPositionFreeCollateralContribution(
|
|
2091
|
+
outPositionAfter
|
|
2092
|
+
);
|
|
2093
|
+
|
|
2094
|
+
const contributionAfter = inContributionAfter.add(outContributionAfter);
|
|
2095
|
+
|
|
2096
|
+
const contributionDelta = contributionAfter.sub(initialContribution);
|
|
2097
|
+
|
|
2098
|
+
freeCollateralAfter = freeCollateral.add(contributionDelta);
|
|
2099
|
+
|
|
2100
|
+
if (freeCollateralAfter.gt(error)) {
|
|
2101
|
+
minSwap = inSwap;
|
|
2102
|
+
inSwap = minSwap.add(maxSwap).div(TWO);
|
|
2103
|
+
} else if (freeCollateralAfter.isNeg()) {
|
|
2104
|
+
maxSwap = inSwap;
|
|
2105
|
+
inSwap = minSwap.add(maxSwap).div(TWO);
|
|
2106
|
+
}
|
|
2107
|
+
|
|
2108
|
+
if (i++ > iterationLimit) {
|
|
2109
|
+
throw new Error('getMaxSwapAmount iteration limit reached');
|
|
2110
|
+
}
|
|
2111
|
+
}
|
|
2112
|
+
}
|
|
2113
|
+
|
|
2114
|
+
const inPositionAfter = this.cloneAndUpdateSpotPosition(
|
|
2115
|
+
inSpotPosition,
|
|
2116
|
+
inSwap.neg(),
|
|
2117
|
+
inMarket
|
|
2118
|
+
);
|
|
2119
|
+
const outPositionAfter = this.cloneAndUpdateSpotPosition(
|
|
2120
|
+
outSpotPosition,
|
|
2121
|
+
outSwap,
|
|
2122
|
+
outMarket
|
|
2123
|
+
);
|
|
2124
|
+
|
|
2125
|
+
const {
|
|
2126
|
+
totalAssetValue: inTotalAssetValueAfter,
|
|
2127
|
+
totalLiabilityValue: inTotalLiabilityValueAfter,
|
|
2128
|
+
} = this.calculateSpotPositionLeverageContribution(inPositionAfter);
|
|
2129
|
+
|
|
2130
|
+
const {
|
|
2131
|
+
totalAssetValue: outTotalAssetValueAfter,
|
|
2132
|
+
totalLiabilityValue: outTotalLiabilityValueAfter,
|
|
2133
|
+
} = this.calculateSpotPositionLeverageContribution(outPositionAfter);
|
|
2134
|
+
|
|
2135
|
+
const spotAssetValueDelta = inTotalAssetValueAfter
|
|
2136
|
+
.add(outTotalAssetValueAfter)
|
|
2137
|
+
.sub(inTotalAssetValueInitial)
|
|
2138
|
+
.sub(outTotalAssetValueInitial);
|
|
2139
|
+
const spotLiabilityValueDelta = inTotalLiabilityValueAfter
|
|
2140
|
+
.add(outTotalLiabilityValueAfter)
|
|
2141
|
+
.sub(inTotalLiabilityValueInitial)
|
|
2142
|
+
.sub(outTotalLiabilityValueInitial);
|
|
2143
|
+
|
|
2144
|
+
const spotAssetValueAfter = spotAssetValue.add(spotAssetValueDelta);
|
|
2145
|
+
const spotLiabilityValueAfter = spotLiabilityValue.add(
|
|
2146
|
+
spotLiabilityValueDelta
|
|
2147
|
+
);
|
|
2148
|
+
|
|
2149
|
+
const leverage = this.calculateLeverageFromComponents({
|
|
2150
|
+
perpLiabilityValue,
|
|
2151
|
+
perpPnl,
|
|
2152
|
+
spotAssetValue: spotAssetValueAfter,
|
|
2153
|
+
spotLiabilityValue: spotLiabilityValueAfter,
|
|
2154
|
+
});
|
|
2155
|
+
|
|
2156
|
+
return { inAmount: inSwap, outAmount: outSwap, leverage };
|
|
2157
|
+
}
|
|
2158
|
+
|
|
2159
|
+
cloneAndUpdateSpotPosition(
|
|
2160
|
+
position: SpotPosition,
|
|
2161
|
+
tokenAmount: BN,
|
|
2162
|
+
market: SpotMarketAccount
|
|
2163
|
+
): SpotPosition {
|
|
2164
|
+
const clonedPosition = Object.assign({}, position);
|
|
2165
|
+
if (tokenAmount.eq(ZERO)) {
|
|
2166
|
+
return clonedPosition;
|
|
2167
|
+
}
|
|
2168
|
+
|
|
2169
|
+
const preTokenAmount = getSignedTokenAmount(
|
|
2170
|
+
getTokenAmount(position.scaledBalance, market, position.balanceType),
|
|
2171
|
+
position.balanceType
|
|
2172
|
+
);
|
|
2173
|
+
|
|
2174
|
+
if (sigNum(preTokenAmount).eq(sigNum(tokenAmount))) {
|
|
2175
|
+
const scaledBalanceDelta = getBalance(
|
|
2176
|
+
tokenAmount.abs(),
|
|
2177
|
+
market,
|
|
2178
|
+
position.balanceType
|
|
2179
|
+
);
|
|
2180
|
+
clonedPosition.scaledBalance =
|
|
2181
|
+
clonedPosition.scaledBalance.add(scaledBalanceDelta);
|
|
2182
|
+
return clonedPosition;
|
|
2183
|
+
}
|
|
2184
|
+
|
|
2185
|
+
const updateDirection = tokenAmount.isNeg()
|
|
2186
|
+
? SpotBalanceType.BORROW
|
|
2187
|
+
: SpotBalanceType.DEPOSIT;
|
|
2188
|
+
|
|
2189
|
+
if (tokenAmount.abs().gte(preTokenAmount.abs())) {
|
|
2190
|
+
clonedPosition.scaledBalance = getBalance(
|
|
2191
|
+
tokenAmount.abs().sub(preTokenAmount.abs()),
|
|
2192
|
+
market,
|
|
2193
|
+
updateDirection
|
|
2194
|
+
);
|
|
2195
|
+
clonedPosition.balanceType = updateDirection;
|
|
2196
|
+
} else {
|
|
2197
|
+
const scaledBalanceDelta = getBalance(
|
|
2198
|
+
tokenAmount.abs(),
|
|
2199
|
+
market,
|
|
2200
|
+
position.balanceType
|
|
2201
|
+
);
|
|
2202
|
+
|
|
2203
|
+
clonedPosition.scaledBalance =
|
|
2204
|
+
clonedPosition.scaledBalance.sub(scaledBalanceDelta);
|
|
2205
|
+
}
|
|
2206
|
+
return clonedPosition;
|
|
2207
|
+
}
|
|
2208
|
+
|
|
2209
|
+
calculateSpotPositionFreeCollateralContribution(
|
|
2210
|
+
spotPosition: SpotPosition
|
|
2211
|
+
): BN {
|
|
2212
|
+
let freeCollateralContribution = ZERO;
|
|
2213
|
+
const now = new BN(new Date().getTime() / 1000);
|
|
2214
|
+
const strict = true;
|
|
2215
|
+
const marginCategory = 'Initial';
|
|
2216
|
+
|
|
2217
|
+
const spotMarketAccount: SpotMarketAccount =
|
|
2218
|
+
this.driftClient.getSpotMarketAccount(spotPosition.marketIndex);
|
|
2219
|
+
|
|
2220
|
+
const oraclePriceData = this.getOracleDataForSpotMarket(
|
|
2221
|
+
spotPosition.marketIndex
|
|
2222
|
+
);
|
|
2223
|
+
|
|
2224
|
+
const [worstCaseTokenAmount, worstCaseQuoteTokenAmount] =
|
|
2225
|
+
getWorstCaseTokenAmounts(
|
|
2226
|
+
spotPosition,
|
|
2227
|
+
spotMarketAccount,
|
|
2228
|
+
oraclePriceData
|
|
2229
|
+
);
|
|
2230
|
+
|
|
2231
|
+
if (worstCaseTokenAmount.gt(ZERO)) {
|
|
2232
|
+
const baseAssetValue = this.getSpotAssetValue(
|
|
2233
|
+
worstCaseTokenAmount,
|
|
2234
|
+
oraclePriceData,
|
|
2235
|
+
spotMarketAccount,
|
|
2236
|
+
marginCategory,
|
|
2237
|
+
strict,
|
|
2238
|
+
now
|
|
2239
|
+
);
|
|
2240
|
+
|
|
2241
|
+
freeCollateralContribution =
|
|
2242
|
+
freeCollateralContribution.add(baseAssetValue);
|
|
2243
|
+
} else {
|
|
2244
|
+
const baseLiabilityValue = this.getSpotLiabilityValue(
|
|
2245
|
+
worstCaseTokenAmount,
|
|
2246
|
+
oraclePriceData,
|
|
2247
|
+
spotMarketAccount,
|
|
2248
|
+
marginCategory,
|
|
2249
|
+
undefined,
|
|
2250
|
+
strict,
|
|
2251
|
+
now
|
|
2252
|
+
).abs();
|
|
2253
|
+
|
|
2254
|
+
freeCollateralContribution =
|
|
2255
|
+
freeCollateralContribution.sub(baseLiabilityValue);
|
|
2256
|
+
}
|
|
2257
|
+
|
|
2258
|
+
freeCollateralContribution.add(worstCaseQuoteTokenAmount);
|
|
2259
|
+
|
|
2260
|
+
return freeCollateralContribution;
|
|
2261
|
+
}
|
|
2262
|
+
|
|
2263
|
+
calculateSpotPositionLeverageContribution(spotPosition: SpotPosition): {
|
|
2264
|
+
totalAssetValue: BN;
|
|
2265
|
+
totalLiabilityValue: BN;
|
|
2266
|
+
} {
|
|
2267
|
+
let totalAssetValue = ZERO;
|
|
2268
|
+
let totalLiabilityValue = ZERO;
|
|
2269
|
+
const now = new BN(new Date().getTime() / 1000);
|
|
2270
|
+
|
|
2271
|
+
const spotMarketAccount: SpotMarketAccount =
|
|
2272
|
+
this.driftClient.getSpotMarketAccount(spotPosition.marketIndex);
|
|
2273
|
+
|
|
2274
|
+
const oraclePriceData = this.getOracleDataForSpotMarket(
|
|
2275
|
+
spotPosition.marketIndex
|
|
2276
|
+
);
|
|
2277
|
+
|
|
2278
|
+
const [worstCaseTokenAmount, worstCaseQuoteTokenAmount] =
|
|
2279
|
+
getWorstCaseTokenAmounts(
|
|
2280
|
+
spotPosition,
|
|
2281
|
+
spotMarketAccount,
|
|
2282
|
+
oraclePriceData
|
|
2283
|
+
);
|
|
2284
|
+
|
|
2285
|
+
if (worstCaseTokenAmount.gt(ZERO)) {
|
|
2286
|
+
totalAssetValue = this.getSpotAssetValue(
|
|
2287
|
+
worstCaseTokenAmount,
|
|
2288
|
+
oraclePriceData,
|
|
2289
|
+
spotMarketAccount,
|
|
2290
|
+
undefined,
|
|
2291
|
+
false,
|
|
2292
|
+
now
|
|
2293
|
+
);
|
|
2294
|
+
} else {
|
|
2295
|
+
totalLiabilityValue = this.getSpotLiabilityValue(
|
|
2296
|
+
worstCaseTokenAmount,
|
|
2297
|
+
oraclePriceData,
|
|
2298
|
+
spotMarketAccount,
|
|
2299
|
+
undefined,
|
|
2300
|
+
undefined,
|
|
2301
|
+
false,
|
|
2302
|
+
now
|
|
2303
|
+
).abs();
|
|
2304
|
+
}
|
|
2305
|
+
|
|
2306
|
+
if (worstCaseQuoteTokenAmount.gt(ZERO)) {
|
|
2307
|
+
totalAssetValue = totalAssetValue.add(worstCaseQuoteTokenAmount);
|
|
2308
|
+
} else {
|
|
2309
|
+
totalLiabilityValue = totalLiabilityValue.add(
|
|
2310
|
+
worstCaseQuoteTokenAmount.abs()
|
|
2311
|
+
);
|
|
2312
|
+
}
|
|
2313
|
+
|
|
2314
|
+
return {
|
|
2315
|
+
totalAssetValue,
|
|
2316
|
+
totalLiabilityValue,
|
|
2317
|
+
};
|
|
2318
|
+
}
|
|
2319
|
+
|
|
2320
|
+
/**
|
|
2321
|
+
* Estimates what the user leverage will be after swap
|
|
2322
|
+
* @param inMarketIndex
|
|
2323
|
+
* @param outMarketIndex
|
|
2324
|
+
* @param inAmount
|
|
2325
|
+
* @param outAmount
|
|
2326
|
+
*/
|
|
2327
|
+
public accountLeverageAfterSwap({
|
|
2328
|
+
inMarketIndex,
|
|
2329
|
+
outMarketIndex,
|
|
2330
|
+
inAmount,
|
|
2331
|
+
outAmount,
|
|
2332
|
+
}: {
|
|
2333
|
+
inMarketIndex: number;
|
|
2334
|
+
outMarketIndex: number;
|
|
2335
|
+
inAmount: BN;
|
|
2336
|
+
outAmount: BN;
|
|
2337
|
+
}): BN {
|
|
2338
|
+
const inMarket = this.driftClient.getSpotMarketAccount(inMarketIndex);
|
|
2339
|
+
const outMarket = this.driftClient.getSpotMarketAccount(outMarketIndex);
|
|
2340
|
+
|
|
2341
|
+
const inSpotPosition =
|
|
2342
|
+
this.getSpotPosition(inMarketIndex) ||
|
|
2343
|
+
this.getEmptySpotPosition(inMarketIndex);
|
|
2344
|
+
const outSpotPosition =
|
|
2345
|
+
this.getSpotPosition(outMarketIndex) ||
|
|
2346
|
+
this.getEmptySpotPosition(outMarketIndex);
|
|
2347
|
+
|
|
2348
|
+
const {
|
|
2349
|
+
totalAssetValue: inTotalAssetValueInitial,
|
|
2350
|
+
totalLiabilityValue: inTotalLiabilityValueInitial,
|
|
2351
|
+
} = this.calculateSpotPositionLeverageContribution(inSpotPosition);
|
|
2352
|
+
const {
|
|
2353
|
+
totalAssetValue: outTotalAssetValueInitial,
|
|
2354
|
+
totalLiabilityValue: outTotalLiabilityValueInitial,
|
|
2355
|
+
} = this.calculateSpotPositionLeverageContribution(outSpotPosition);
|
|
2356
|
+
|
|
2357
|
+
const { perpLiabilityValue, perpPnl, spotAssetValue, spotLiabilityValue } =
|
|
2358
|
+
this.getLeverageComponents();
|
|
2359
|
+
|
|
2360
|
+
const inPositionAfter = this.cloneAndUpdateSpotPosition(
|
|
2361
|
+
inSpotPosition,
|
|
2362
|
+
inAmount.abs().neg(),
|
|
2363
|
+
inMarket
|
|
2364
|
+
);
|
|
2365
|
+
const outPositionAfter = this.cloneAndUpdateSpotPosition(
|
|
2366
|
+
outSpotPosition,
|
|
2367
|
+
outAmount.abs(),
|
|
2368
|
+
outMarket
|
|
2369
|
+
);
|
|
2370
|
+
|
|
2371
|
+
const {
|
|
2372
|
+
totalAssetValue: inTotalAssetValueAfter,
|
|
2373
|
+
totalLiabilityValue: inTotalLiabilityValueAfter,
|
|
2374
|
+
} = this.calculateSpotPositionLeverageContribution(inPositionAfter);
|
|
2375
|
+
|
|
2376
|
+
const {
|
|
2377
|
+
totalAssetValue: outTotalAssetValueAfter,
|
|
2378
|
+
totalLiabilityValue: outTotalLiabilityValueAfter,
|
|
2379
|
+
} = this.calculateSpotPositionLeverageContribution(outPositionAfter);
|
|
2380
|
+
|
|
2381
|
+
const spotAssetValueDelta = inTotalAssetValueAfter
|
|
2382
|
+
.add(outTotalAssetValueAfter)
|
|
2383
|
+
.sub(inTotalAssetValueInitial)
|
|
2384
|
+
.sub(outTotalAssetValueInitial);
|
|
2385
|
+
const spotLiabilityValueDelta = inTotalLiabilityValueAfter
|
|
2386
|
+
.add(outTotalLiabilityValueAfter)
|
|
2387
|
+
.sub(inTotalLiabilityValueInitial)
|
|
2388
|
+
.sub(outTotalLiabilityValueInitial);
|
|
2389
|
+
|
|
2390
|
+
const spotAssetValueAfter = spotAssetValue.add(spotAssetValueDelta);
|
|
2391
|
+
const spotLiabilityValueAfter = spotLiabilityValue.add(
|
|
2392
|
+
spotLiabilityValueDelta
|
|
2393
|
+
);
|
|
2394
|
+
|
|
2395
|
+
return this.calculateLeverageFromComponents({
|
|
2396
|
+
perpLiabilityValue,
|
|
2397
|
+
perpPnl,
|
|
2398
|
+
spotAssetValue: spotAssetValueAfter,
|
|
2399
|
+
spotLiabilityValue: spotLiabilityValueAfter,
|
|
2400
|
+
});
|
|
2401
|
+
}
|
|
2402
|
+
|
|
1965
2403
|
// TODO - should this take the price impact of the trade into account for strict accuracy?
|
|
1966
2404
|
|
|
1967
2405
|
/**
|