@drift-labs/sdk 0.1.36-master.7 → 0.2.0-master.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/accounts/bulkAccountLoader.d.ts +6 -6
- package/lib/accounts/bulkAccountLoader.js +81 -95
- package/lib/accounts/bulkUserSubscription.js +13 -57
- package/lib/accounts/fetch.d.ts +4 -0
- package/lib/accounts/fetch.js +18 -0
- package/lib/accounts/pollingClearingHouseAccountSubscriber.d.ts +34 -38
- package/lib/accounts/pollingClearingHouseAccountSubscriber.js +224 -224
- package/lib/accounts/pollingOracleSubscriber.d.ts +3 -3
- package/lib/accounts/pollingOracleSubscriber.js +37 -49
- package/lib/accounts/pollingTokenAccountSubscriber.d.ts +3 -3
- package/lib/accounts/pollingTokenAccountSubscriber.js +35 -50
- package/lib/accounts/pollingUserAccountSubscriber.d.ts +7 -13
- package/lib/accounts/pollingUserAccountSubscriber.js +71 -134
- package/lib/accounts/types.d.ts +34 -41
- package/lib/accounts/webSocketAccountSubscriber.d.ts +6 -4
- package/lib/accounts/webSocketAccountSubscriber.js +39 -35
- package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +33 -28
- package/lib/accounts/webSocketClearingHouseAccountSubscriber.js +153 -185
- package/lib/accounts/webSocketUserAccountSubscriber.d.ts +5 -11
- package/lib/accounts/webSocketUserAccountSubscriber.js +22 -67
- package/lib/addresses/marketAddresses.d.ts +4 -0
- package/lib/addresses/marketAddresses.js +15 -0
- package/lib/addresses/pda.d.ts +12 -0
- package/lib/addresses/pda.js +83 -0
- package/lib/admin.d.ts +9 -17
- package/lib/admin.js +375 -558
- package/lib/clearingHouse.d.ts +86 -109
- package/lib/clearingHouse.js +828 -895
- package/lib/clearingHouseConfig.d.ts +34 -0
- package/lib/clearingHouseConfig.js +2 -0
- package/lib/clearingHouseUser.d.ts +19 -22
- package/lib/clearingHouseUser.js +155 -141
- package/lib/clearingHouseUserConfig.d.ts +14 -0
- package/lib/clearingHouseUserConfig.js +2 -0
- package/lib/config.d.ts +12 -0
- package/lib/config.js +35 -4
- package/lib/constants/banks.d.ts +16 -0
- package/lib/constants/banks.js +34 -0
- package/lib/constants/markets.d.ts +8 -3
- package/lib/constants/markets.js +13 -206
- package/lib/constants/numericConstants.d.ts +17 -0
- package/lib/constants/numericConstants.js +23 -6
- package/lib/events/eventList.d.ts +22 -0
- package/lib/events/eventList.js +77 -0
- package/lib/events/eventSubscriber.d.ts +34 -0
- package/lib/events/eventSubscriber.js +126 -0
- package/lib/events/fetchLogs.d.ts +13 -0
- package/lib/events/fetchLogs.js +39 -0
- package/lib/events/pollingLogProvider.d.ts +15 -0
- package/lib/events/pollingLogProvider.js +53 -0
- package/lib/events/sort.d.ts +2 -0
- package/lib/events/sort.js +44 -0
- package/lib/events/txEventCache.d.ts +24 -0
- package/lib/events/txEventCache.js +71 -0
- package/lib/events/types.d.ts +49 -0
- package/lib/events/types.js +20 -0
- package/lib/events/webSocketLogProvider.d.ts +12 -0
- package/lib/events/webSocketLogProvider.js +30 -0
- package/lib/examples/makeTradeExample.js +26 -27
- package/lib/factory/bigNum.d.ts +118 -0
- package/lib/factory/bigNum.js +364 -0
- package/lib/factory/oracleClient.d.ts +1 -2
- package/lib/factory/oracleClient.js +6 -2
- package/lib/idl/clearing_house.json +2287 -2938
- package/lib/index.d.ts +12 -4
- package/lib/index.js +12 -4
- package/lib/math/amm.d.ts +24 -29
- package/lib/math/amm.js +239 -178
- package/lib/math/auction.d.ts +5 -0
- package/lib/math/auction.js +39 -0
- package/lib/math/bankBalance.d.ts +9 -0
- package/lib/math/bankBalance.js +75 -0
- package/lib/math/conversion.d.ts +0 -1
- package/lib/math/conversion.js +1 -5
- package/lib/math/funding.d.ts +6 -6
- package/lib/math/funding.js +158 -175
- package/lib/math/market.d.ts +6 -6
- package/lib/math/market.js +10 -9
- package/lib/math/orders.d.ts +5 -0
- package/lib/math/orders.js +31 -1
- package/lib/math/position.d.ts +7 -5
- package/lib/math/position.js +27 -27
- package/lib/math/repeg.d.ts +22 -0
- package/lib/math/repeg.js +128 -0
- package/lib/math/trade.d.ts +5 -4
- package/lib/math/trade.js +29 -21
- package/lib/mockUSDCFaucet.js +87 -116
- package/lib/oracles/oracleClientCache.d.ts +8 -0
- package/lib/oracles/oracleClientCache.js +19 -0
- package/lib/oracles/pythClient.d.ts +3 -5
- package/lib/oracles/pythClient.js +12 -31
- package/lib/oracles/quoteAssetOracleClient.d.ts +9 -0
- package/lib/oracles/quoteAssetOracleClient.js +21 -0
- package/lib/oracles/switchboardClient.d.ts +3 -5
- package/lib/oracles/switchboardClient.js +29 -50
- package/lib/oracles/types.d.ts +6 -1
- package/lib/orders.d.ts +6 -7
- package/lib/orders.js +10 -80
- package/lib/slot/SlotSubscriber.d.ts +12 -0
- package/lib/slot/SlotSubscriber.js +23 -0
- package/lib/tx/retryTxSender.d.ts +2 -2
- package/lib/tx/retryTxSender.js +108 -123
- package/lib/tx/types.d.ts +5 -1
- package/lib/tx/utils.d.ts +1 -1
- package/lib/tx/utils.js +11 -2
- package/lib/types.d.ts +110 -109
- package/lib/types.js +14 -1
- package/lib/userName.d.ts +4 -0
- package/lib/userName.js +20 -0
- package/lib/util/computeUnits.js +10 -21
- package/lib/util/tps.js +11 -22
- package/lib/wallet.js +7 -20
- package/package.json +11 -4
- package/src/accounts/bulkAccountLoader.ts +21 -15
- package/src/accounts/bulkUserSubscription.ts +1 -45
- package/src/accounts/fetch.ts +33 -0
- package/src/accounts/pollingClearingHouseAccountSubscriber.ts +249 -214
- package/src/accounts/pollingOracleSubscriber.ts +16 -8
- package/src/accounts/pollingTokenAccountSubscriber.ts +11 -8
- package/src/accounts/pollingUserAccountSubscriber.ts +21 -86
- package/src/accounts/types.ts +41 -70
- package/src/accounts/webSocketAccountSubscriber.ts +33 -16
- package/src/accounts/webSocketClearingHouseAccountSubscriber.ts +190 -240
- package/src/accounts/webSocketUserAccountSubscriber.ts +11 -71
- package/src/addresses/marketAddresses.ts +18 -0
- package/src/addresses/pda.ts +118 -0
- package/src/admin.ts +218 -346
- package/src/clearingHouse.ts +983 -952
- package/src/clearingHouseConfig.ts +37 -0
- package/src/clearingHouseUser.ts +275 -185
- package/src/clearingHouseUserConfig.ts +18 -0
- package/src/config.ts +54 -1
- package/src/constants/banks.ts +43 -0
- package/src/constants/markets.ts +16 -207
- package/src/constants/numericConstants.ts +34 -5
- package/src/events/eventList.ts +94 -0
- package/src/events/eventSubscriber.ts +194 -0
- package/src/events/fetchLogs.ts +80 -0
- package/src/events/pollingLogProvider.ts +79 -0
- package/src/events/sort.ts +65 -0
- package/src/events/txEventCache.ts +74 -0
- package/src/events/types.ts +98 -0
- package/src/events/webSocketLogProvider.ts +38 -0
- package/src/examples/makeTradeExample.ts +20 -11
- package/src/factory/bigNum.ts +524 -0
- package/src/factory/oracleClient.ts +7 -4
- package/src/idl/clearing_house.json +2287 -2938
- package/src/index.ts +12 -4
- package/src/math/amm.ts +414 -245
- package/src/math/auction.ts +39 -0
- package/src/math/bankBalance.ts +112 -0
- package/src/math/conversion.ts +1 -11
- package/src/math/funding.ts +12 -9
- package/src/math/market.ts +37 -30
- package/src/math/orders.ts +38 -0
- package/src/math/position.ts +48 -35
- package/src/math/repeg.ts +176 -0
- package/src/math/trade.ts +45 -35
- package/src/math/utils.js +27 -0
- package/src/math/utils.js.map +1 -0
- package/src/oracles/oracleClientCache.ts +20 -0
- package/src/oracles/pythClient.ts +4 -11
- package/src/oracles/quoteAssetOracleClient.ts +25 -0
- package/src/oracles/switchboardClient.ts +11 -24
- package/src/oracles/types.ts +7 -1
- package/src/orders.ts +24 -126
- package/src/slot/SlotSubscriber.ts +32 -0
- package/src/tx/retryTxSender.ts +6 -4
- package/src/tx/types.ts +6 -1
- package/src/tx/utils.ts +22 -3
- package/src/types.ts +111 -122
- package/src/userName.ts +20 -0
- package/src/util/computeUnits.js +17 -0
- package/src/util/computeUnits.js.map +1 -0
- package/tests/bn/test.ts +255 -0
- package/tsconfig.json +12 -12
- package/lib/addresses.d.ts +0 -10
- package/lib/addresses.js +0 -93
- package/lib/constants/accounts.d.ts +0 -15
- package/lib/constants/accounts.js +0 -18
- package/lib/factory/clearingHouse.d.ts +0 -35
- package/lib/factory/clearingHouse.js +0 -81
- package/lib/factory/clearingHouseUser.d.ts +0 -19
- package/lib/factory/clearingHouseUser.js +0 -34
- package/lib/math/insuranceFund.d.ts +0 -15
- package/lib/math/insuranceFund.js +0 -33
- package/lib/settlement.d.ts +0 -4
- package/lib/settlement.js +0 -10
- package/lib/tx/defaultTxSender.d.ts +0 -8
- package/lib/tx/defaultTxSender.js +0 -12
- package/src/addresses.ts +0 -82
- package/src/constants/accounts.ts +0 -26
- package/src/factory/clearingHouse.ts +0 -173
- package/src/factory/clearingHouseUser.ts +0 -73
- package/src/math/insuranceFund.ts +0 -29
- package/src/settlement.ts +0 -9
- package/src/tx/defaultTxSender.ts +0 -24
package/lib/math/amm.js
CHANGED
|
@@ -1,29 +1,143 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.calculateQuoteAssetAmountSwapped = exports.
|
|
3
|
+
exports.calculateQuoteAssetAmountSwapped = exports.calculateMaxBaseAssetAmountToTrade = exports.calculateTerminalPrice = exports.getSwapDirection = exports.calculateSwapOutput = exports.calculateSpreadReserves = exports.calculateSpread = exports.calculateSpreadBN = exports.calculateMaxSpread = exports.calculateEffectiveLeverage = exports.calculateAmmReservesAfterSwap = exports.calculatePrice = exports.calculateBidAskPrice = exports.calculateUpdatedAMMSpreadReserves = exports.calculateUpdatedAMM = exports.calculateNewAmm = exports.calculateOptimalPegAndBudget = exports.calculatePegFromTargetPrice = void 0;
|
|
4
4
|
const anchor_1 = require("@project-serum/anchor");
|
|
5
5
|
const numericConstants_1 = require("../constants/numericConstants");
|
|
6
|
-
const position_1 = require("./position");
|
|
7
6
|
const types_1 = require("../types");
|
|
8
7
|
const assert_1 = require("../assert/assert");
|
|
9
8
|
const __1 = require("..");
|
|
9
|
+
const repeg_1 = require("./repeg");
|
|
10
|
+
function calculatePegFromTargetPrice(targetPrice, baseAssetReserve, quoteAssetReserve) {
|
|
11
|
+
return targetPrice
|
|
12
|
+
.mul(baseAssetReserve)
|
|
13
|
+
.div(quoteAssetReserve)
|
|
14
|
+
.add(numericConstants_1.PRICE_DIV_PEG.div(new anchor_1.BN(2)))
|
|
15
|
+
.div(numericConstants_1.PRICE_DIV_PEG);
|
|
16
|
+
}
|
|
17
|
+
exports.calculatePegFromTargetPrice = calculatePegFromTargetPrice;
|
|
18
|
+
function calculateOptimalPegAndBudget(amm, oraclePriceData) {
|
|
19
|
+
const markPriceBefore = calculatePrice(amm.baseAssetReserve, amm.quoteAssetReserve, amm.pegMultiplier);
|
|
20
|
+
const targetPrice = oraclePriceData.price;
|
|
21
|
+
const newPeg = calculatePegFromTargetPrice(targetPrice, amm.baseAssetReserve, amm.quoteAssetReserve);
|
|
22
|
+
const prePegCost = (0, repeg_1.calculateRepegCost)(amm, newPeg);
|
|
23
|
+
const totalFeeLB = amm.totalExchangeFee.div(new anchor_1.BN(2));
|
|
24
|
+
const budget = anchor_1.BN.max(numericConstants_1.ZERO, amm.totalFeeMinusDistributions.sub(totalFeeLB));
|
|
25
|
+
if (budget.lt(prePegCost)) {
|
|
26
|
+
const maxPriceSpread = new anchor_1.BN(amm.maxSpread)
|
|
27
|
+
.mul(targetPrice)
|
|
28
|
+
.div(numericConstants_1.BID_ASK_SPREAD_PRECISION);
|
|
29
|
+
let newTargetPrice;
|
|
30
|
+
let newOptimalPeg;
|
|
31
|
+
let newBudget;
|
|
32
|
+
const targetPriceGap = markPriceBefore.sub(targetPrice);
|
|
33
|
+
if (targetPriceGap.abs().gt(maxPriceSpread)) {
|
|
34
|
+
const markAdj = targetPriceGap.abs().sub(maxPriceSpread);
|
|
35
|
+
if (targetPriceGap.lt(new anchor_1.BN(0))) {
|
|
36
|
+
newTargetPrice = markPriceBefore.add(markAdj);
|
|
37
|
+
}
|
|
38
|
+
else {
|
|
39
|
+
newTargetPrice = markPriceBefore.sub(markAdj);
|
|
40
|
+
}
|
|
41
|
+
newOptimalPeg = calculatePegFromTargetPrice(newTargetPrice, amm.baseAssetReserve, amm.quoteAssetReserve);
|
|
42
|
+
newBudget = (0, repeg_1.calculateRepegCost)(amm, newOptimalPeg);
|
|
43
|
+
return [newTargetPrice, newOptimalPeg, newBudget, false];
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return [targetPrice, newPeg, budget, true];
|
|
47
|
+
}
|
|
48
|
+
exports.calculateOptimalPegAndBudget = calculateOptimalPegAndBudget;
|
|
49
|
+
function calculateNewAmm(amm, oraclePriceData) {
|
|
50
|
+
let pKNumer = new anchor_1.BN(1);
|
|
51
|
+
let pKDenom = new anchor_1.BN(1);
|
|
52
|
+
const [targetPrice, _newPeg, budget, checkLowerBound] = calculateOptimalPegAndBudget(amm, oraclePriceData);
|
|
53
|
+
let prePegCost = (0, repeg_1.calculateRepegCost)(amm, _newPeg);
|
|
54
|
+
let newPeg = _newPeg;
|
|
55
|
+
if (prePegCost.gt(budget) && checkLowerBound) {
|
|
56
|
+
[pKNumer, pKDenom] = [new anchor_1.BN(999), new anchor_1.BN(1000)];
|
|
57
|
+
const deficitMadeup = (0, repeg_1.calculateAdjustKCost)(amm, pKNumer, pKDenom);
|
|
58
|
+
(0, assert_1.assert)(deficitMadeup.lte(new anchor_1.BN(0)));
|
|
59
|
+
prePegCost = budget.add(deficitMadeup.abs());
|
|
60
|
+
const newAmm = Object.assign({}, amm);
|
|
61
|
+
newAmm.baseAssetReserve = newAmm.baseAssetReserve.mul(pKNumer).div(pKDenom);
|
|
62
|
+
newAmm.sqrtK = newAmm.sqrtK.mul(pKNumer).div(pKDenom);
|
|
63
|
+
const invariant = newAmm.sqrtK.mul(newAmm.sqrtK);
|
|
64
|
+
newAmm.quoteAssetReserve = invariant.div(newAmm.baseAssetReserve);
|
|
65
|
+
const directionToClose = amm.netBaseAssetAmount.gt(numericConstants_1.ZERO)
|
|
66
|
+
? types_1.PositionDirection.SHORT
|
|
67
|
+
: types_1.PositionDirection.LONG;
|
|
68
|
+
const [newQuoteAssetReserve, _newBaseAssetReserve] = calculateAmmReservesAfterSwap(newAmm, 'base', amm.netBaseAssetAmount.abs(), getSwapDirection('base', directionToClose));
|
|
69
|
+
newAmm.terminalQuoteAssetReserve = newQuoteAssetReserve;
|
|
70
|
+
newPeg = (0, repeg_1.calculateBudgetedPeg)(newAmm, prePegCost, targetPrice);
|
|
71
|
+
prePegCost = (0, repeg_1.calculateRepegCost)(newAmm, newPeg);
|
|
72
|
+
}
|
|
73
|
+
return [prePegCost, pKNumer, pKDenom, newPeg];
|
|
74
|
+
}
|
|
75
|
+
exports.calculateNewAmm = calculateNewAmm;
|
|
76
|
+
function calculateUpdatedAMM(amm, oraclePriceData) {
|
|
77
|
+
if (amm.curveUpdateIntensity == 0) {
|
|
78
|
+
return amm;
|
|
79
|
+
}
|
|
80
|
+
const newAmm = Object.assign({}, amm);
|
|
81
|
+
const [prepegCost, pKNumer, pKDenom, newPeg] = calculateNewAmm(amm, oraclePriceData);
|
|
82
|
+
newAmm.baseAssetReserve = newAmm.baseAssetReserve.mul(pKNumer).div(pKDenom);
|
|
83
|
+
newAmm.sqrtK = newAmm.sqrtK.mul(pKNumer).div(pKDenom);
|
|
84
|
+
const invariant = newAmm.sqrtK.mul(newAmm.sqrtK);
|
|
85
|
+
newAmm.quoteAssetReserve = invariant.div(newAmm.baseAssetReserve);
|
|
86
|
+
newAmm.pegMultiplier = newPeg;
|
|
87
|
+
const directionToClose = amm.netBaseAssetAmount.gt(numericConstants_1.ZERO)
|
|
88
|
+
? types_1.PositionDirection.SHORT
|
|
89
|
+
: types_1.PositionDirection.LONG;
|
|
90
|
+
const [newQuoteAssetReserve, _newBaseAssetReserve] = calculateAmmReservesAfterSwap(newAmm, 'base', amm.netBaseAssetAmount.abs(), getSwapDirection('base', directionToClose));
|
|
91
|
+
newAmm.terminalQuoteAssetReserve = newQuoteAssetReserve;
|
|
92
|
+
newAmm.totalFeeMinusDistributions =
|
|
93
|
+
newAmm.totalFeeMinusDistributions.sub(prepegCost);
|
|
94
|
+
return newAmm;
|
|
95
|
+
}
|
|
96
|
+
exports.calculateUpdatedAMM = calculateUpdatedAMM;
|
|
97
|
+
function calculateUpdatedAMMSpreadReserves(amm, direction, oraclePriceData) {
|
|
98
|
+
const newAmm = calculateUpdatedAMM(amm, oraclePriceData);
|
|
99
|
+
const dirReserves = calculateSpreadReserves(newAmm, direction, oraclePriceData);
|
|
100
|
+
const result = {
|
|
101
|
+
baseAssetReserve: dirReserves.baseAssetReserve,
|
|
102
|
+
quoteAssetReserve: dirReserves.quoteAssetReserve,
|
|
103
|
+
sqrtK: newAmm.sqrtK,
|
|
104
|
+
newPeg: newAmm.pegMultiplier,
|
|
105
|
+
};
|
|
106
|
+
return result;
|
|
107
|
+
}
|
|
108
|
+
exports.calculateUpdatedAMMSpreadReserves = calculateUpdatedAMMSpreadReserves;
|
|
109
|
+
function calculateBidAskPrice(amm, oraclePriceData, withUpdate = true) {
|
|
110
|
+
let newAmm;
|
|
111
|
+
if (withUpdate) {
|
|
112
|
+
newAmm = calculateUpdatedAMM(amm, oraclePriceData);
|
|
113
|
+
}
|
|
114
|
+
else {
|
|
115
|
+
newAmm = amm;
|
|
116
|
+
}
|
|
117
|
+
const askReserves = calculateSpreadReserves(newAmm, types_1.PositionDirection.LONG, oraclePriceData);
|
|
118
|
+
const bidReserves = calculateSpreadReserves(newAmm, types_1.PositionDirection.SHORT, oraclePriceData);
|
|
119
|
+
const askPrice = calculatePrice(askReserves.baseAssetReserve, askReserves.quoteAssetReserve, newAmm.pegMultiplier);
|
|
120
|
+
const bidPrice = calculatePrice(bidReserves.baseAssetReserve, bidReserves.quoteAssetReserve, newAmm.pegMultiplier);
|
|
121
|
+
return [bidPrice, askPrice];
|
|
122
|
+
}
|
|
123
|
+
exports.calculateBidAskPrice = calculateBidAskPrice;
|
|
10
124
|
/**
|
|
11
125
|
* Calculates a price given an arbitrary base and quote amount (they must have the same precision)
|
|
12
126
|
*
|
|
13
|
-
* @param
|
|
14
|
-
* @param
|
|
15
|
-
* @param
|
|
127
|
+
* @param baseAssetReserves
|
|
128
|
+
* @param quoteAssetReserves
|
|
129
|
+
* @param pegMultiplier
|
|
16
130
|
* @returns price : Precision MARK_PRICE_PRECISION
|
|
17
131
|
*/
|
|
18
|
-
function calculatePrice(
|
|
19
|
-
if (
|
|
132
|
+
function calculatePrice(baseAssetReserves, quoteAssetReserves, pegMultiplier) {
|
|
133
|
+
if (baseAssetReserves.abs().lte(numericConstants_1.ZERO)) {
|
|
20
134
|
return new anchor_1.BN(0);
|
|
21
135
|
}
|
|
22
|
-
return
|
|
136
|
+
return quoteAssetReserves
|
|
23
137
|
.mul(numericConstants_1.MARK_PRICE_PRECISION)
|
|
24
|
-
.mul(
|
|
138
|
+
.mul(pegMultiplier)
|
|
25
139
|
.div(numericConstants_1.PEG_PRECISION)
|
|
26
|
-
.div(
|
|
140
|
+
.div(baseAssetReserves);
|
|
27
141
|
}
|
|
28
142
|
exports.calculatePrice = calculatePrice;
|
|
29
143
|
/**
|
|
@@ -51,27 +165,129 @@ function calculateAmmReservesAfterSwap(amm, inputAssetType, swapAmount, swapDire
|
|
|
51
165
|
return [newQuoteAssetReserve, newBaseAssetReserve];
|
|
52
166
|
}
|
|
53
167
|
exports.calculateAmmReservesAfterSwap = calculateAmmReservesAfterSwap;
|
|
54
|
-
function
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
168
|
+
function calculateEffectiveLeverage(baseSpread, quoteAssetReserve, terminalQuoteAssetReserve, pegMultiplier, netBaseAssetAmount, markPrice, totalFeeMinusDistributions) {
|
|
169
|
+
// inventory skew
|
|
170
|
+
const netBaseAssetValue = quoteAssetReserve
|
|
171
|
+
.sub(terminalQuoteAssetReserve)
|
|
172
|
+
.mul(pegMultiplier)
|
|
173
|
+
.div(numericConstants_1.AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO);
|
|
174
|
+
const localBaseAssetValue = netBaseAssetAmount
|
|
175
|
+
.mul(markPrice)
|
|
176
|
+
.div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO.mul(numericConstants_1.MARK_PRICE_PRECISION));
|
|
177
|
+
const effectiveLeverage = localBaseAssetValue.sub(netBaseAssetValue).toNumber() /
|
|
178
|
+
(Math.max(0, totalFeeMinusDistributions.toNumber()) + 1) +
|
|
179
|
+
1 / numericConstants_1.QUOTE_PRECISION.toNumber();
|
|
180
|
+
return effectiveLeverage;
|
|
181
|
+
}
|
|
182
|
+
exports.calculateEffectiveLeverage = calculateEffectiveLeverage;
|
|
183
|
+
function calculateMaxSpread(marginRatioInitial) {
|
|
184
|
+
const maxTargetSpread = new anchor_1.BN(marginRatioInitial)
|
|
185
|
+
.mul(numericConstants_1.BID_ASK_SPREAD_PRECISION.div(numericConstants_1.MARGIN_PRECISION))
|
|
186
|
+
.toNumber();
|
|
187
|
+
return maxTargetSpread;
|
|
188
|
+
}
|
|
189
|
+
exports.calculateMaxSpread = calculateMaxSpread;
|
|
190
|
+
function calculateSpreadBN(baseSpread, lastOracleMarkSpreadPct, lastOracleConfPct, maxSpread, quoteAssetReserve, terminalQuoteAssetReserve, pegMultiplier, netBaseAssetAmount, markPrice, totalFeeMinusDistributions) {
|
|
191
|
+
let longSpread = baseSpread / 2;
|
|
192
|
+
let shortSpread = baseSpread / 2;
|
|
193
|
+
if (lastOracleMarkSpreadPct.gt(numericConstants_1.ZERO)) {
|
|
194
|
+
shortSpread = Math.max(shortSpread, lastOracleMarkSpreadPct.abs().toNumber() + lastOracleConfPct.toNumber());
|
|
195
|
+
}
|
|
196
|
+
else if (lastOracleMarkSpreadPct.lt(numericConstants_1.ZERO)) {
|
|
197
|
+
longSpread = Math.max(longSpread, lastOracleMarkSpreadPct.abs().toNumber() + lastOracleConfPct.toNumber());
|
|
198
|
+
}
|
|
199
|
+
const maxTargetSpread = maxSpread;
|
|
200
|
+
const MAX_INVENTORY_SKEW = 5;
|
|
201
|
+
const effectiveLeverage = calculateEffectiveLeverage(baseSpread, quoteAssetReserve, terminalQuoteAssetReserve, pegMultiplier, netBaseAssetAmount, markPrice, totalFeeMinusDistributions);
|
|
202
|
+
if (totalFeeMinusDistributions.gt(numericConstants_1.ZERO)) {
|
|
203
|
+
const spreadScale = Math.min(MAX_INVENTORY_SKEW, 1 + effectiveLeverage);
|
|
204
|
+
if (netBaseAssetAmount.gt(numericConstants_1.ZERO)) {
|
|
205
|
+
longSpread *= spreadScale;
|
|
206
|
+
}
|
|
207
|
+
else {
|
|
208
|
+
shortSpread *= spreadScale;
|
|
209
|
+
}
|
|
59
210
|
}
|
|
60
211
|
else {
|
|
61
|
-
|
|
212
|
+
longSpread *= MAX_INVENTORY_SKEW;
|
|
213
|
+
shortSpread *= MAX_INVENTORY_SKEW;
|
|
214
|
+
}
|
|
215
|
+
const totalSpread = longSpread + shortSpread;
|
|
216
|
+
if (totalSpread > maxTargetSpread) {
|
|
217
|
+
if (longSpread > shortSpread) {
|
|
218
|
+
longSpread = Math.min(longSpread, maxTargetSpread);
|
|
219
|
+
shortSpread = maxTargetSpread - longSpread;
|
|
220
|
+
}
|
|
221
|
+
else {
|
|
222
|
+
shortSpread = Math.min(shortSpread, maxTargetSpread);
|
|
223
|
+
longSpread = maxTargetSpread - shortSpread;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
return [longSpread, shortSpread];
|
|
227
|
+
}
|
|
228
|
+
exports.calculateSpreadBN = calculateSpreadBN;
|
|
229
|
+
function calculateSpread(amm, direction, oraclePriceData) {
|
|
230
|
+
let spread = amm.baseSpread / 2;
|
|
231
|
+
if (amm.baseSpread == 0 || amm.curveUpdateIntensity == 0) {
|
|
232
|
+
return spread;
|
|
233
|
+
}
|
|
234
|
+
const markPrice = calculatePrice(amm.baseAssetReserve, amm.quoteAssetReserve, amm.pegMultiplier);
|
|
235
|
+
const targetPrice = (oraclePriceData === null || oraclePriceData === void 0 ? void 0 : oraclePriceData.price) || markPrice;
|
|
236
|
+
const confInterval = oraclePriceData.confidence || numericConstants_1.ZERO;
|
|
237
|
+
const targetMarkSpreadPct = markPrice
|
|
238
|
+
.sub(targetPrice)
|
|
239
|
+
.mul(numericConstants_1.BID_ASK_SPREAD_PRECISION)
|
|
240
|
+
.div(markPrice);
|
|
241
|
+
const confIntervalPct = confInterval
|
|
242
|
+
.mul(numericConstants_1.BID_ASK_SPREAD_PRECISION)
|
|
243
|
+
.div(markPrice);
|
|
244
|
+
// oracle retreat
|
|
245
|
+
if (((0, types_1.isVariant)(direction, 'long') && targetMarkSpreadPct.lt(numericConstants_1.ZERO)) ||
|
|
246
|
+
((0, types_1.isVariant)(direction, 'short') && targetMarkSpreadPct.gt(numericConstants_1.ZERO))) {
|
|
247
|
+
spread = Math.max(spread, targetMarkSpreadPct.abs().toNumber() + confIntervalPct.abs().toNumber());
|
|
248
|
+
}
|
|
249
|
+
// inventory skew
|
|
250
|
+
const MAX_INVENTORY_SKEW = 5;
|
|
251
|
+
if ((amm.netBaseAssetAmount.gt(numericConstants_1.ZERO) && (0, types_1.isVariant)(direction, 'long')) ||
|
|
252
|
+
(amm.netBaseAssetAmount.lt(numericConstants_1.ZERO) && (0, types_1.isVariant)(direction, 'short')) ||
|
|
253
|
+
amm.totalFeeMinusDistributions.eq(numericConstants_1.ZERO)) {
|
|
254
|
+
const netCostBasis = amm.quoteAssetAmountLong.sub(amm.quoteAssetAmountShort);
|
|
255
|
+
const netBaseAssetValue = amm.quoteAssetReserve
|
|
256
|
+
.sub(amm.terminalQuoteAssetReserve)
|
|
257
|
+
.mul(amm.pegMultiplier)
|
|
258
|
+
.div(numericConstants_1.AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO);
|
|
259
|
+
const localBaseAssetValue = amm.netBaseAssetAmount
|
|
260
|
+
.mul(markPrice)
|
|
261
|
+
.div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO.mul(numericConstants_1.MARK_PRICE_PRECISION));
|
|
262
|
+
const netPnl = netBaseAssetValue.sub(netCostBasis);
|
|
263
|
+
const localPnl = localBaseAssetValue.sub(netCostBasis);
|
|
264
|
+
let effectiveLeverage = MAX_INVENTORY_SKEW;
|
|
265
|
+
if (amm.totalFeeMinusDistributions.gt(numericConstants_1.ZERO)) {
|
|
266
|
+
effectiveLeverage =
|
|
267
|
+
localPnl.sub(netPnl).toNumber() /
|
|
268
|
+
(amm.totalFeeMinusDistributions.toNumber() + 1);
|
|
269
|
+
}
|
|
270
|
+
let spreadScale = Math.min(MAX_INVENTORY_SKEW, 1 + effectiveLeverage);
|
|
271
|
+
const maxTargetSpread = numericConstants_1.BID_ASK_SPREAD_PRECISION.toNumber() / 50; // 2%
|
|
272
|
+
// cap the scale to attempt to only scale up to maxTargetSpread
|
|
273
|
+
// always let the oracle retreat methods go through 100%
|
|
274
|
+
if (spreadScale * spread > maxTargetSpread) {
|
|
275
|
+
spreadScale = Math.max(1.05, maxTargetSpread / spread);
|
|
276
|
+
}
|
|
277
|
+
spread *= spreadScale;
|
|
62
278
|
}
|
|
63
279
|
return spread;
|
|
64
280
|
}
|
|
65
281
|
exports.calculateSpread = calculateSpread;
|
|
66
|
-
function calculateSpreadReserves(amm, direction) {
|
|
67
|
-
const spread = calculateSpread(amm, direction);
|
|
282
|
+
function calculateSpreadReserves(amm, direction, oraclePriceData) {
|
|
283
|
+
const spread = calculateSpread(amm, direction, oraclePriceData);
|
|
68
284
|
if (spread === 0) {
|
|
69
285
|
return {
|
|
70
286
|
baseAssetReserve: amm.baseAssetReserve,
|
|
71
287
|
quoteAssetReserve: amm.quoteAssetReserve,
|
|
72
288
|
};
|
|
73
289
|
}
|
|
74
|
-
const quoteAsserReserveDelta = amm.quoteAssetReserve.div(numericConstants_1.BID_ASK_SPREAD_PRECISION.div(new anchor_1.BN(spread /
|
|
290
|
+
const quoteAsserReserveDelta = amm.quoteAssetReserve.div(numericConstants_1.BID_ASK_SPREAD_PRECISION.div(new anchor_1.BN(spread / 2)));
|
|
75
291
|
let quoteAssetReserve;
|
|
76
292
|
if ((0, types_1.isVariant)(direction, 'long')) {
|
|
77
293
|
quoteAssetReserve = amm.quoteAssetReserve.add(quoteAsserReserveDelta);
|
|
@@ -123,92 +339,6 @@ function getSwapDirection(inputAssetType, positionDirection) {
|
|
|
123
339
|
return types_1.SwapDirection.ADD;
|
|
124
340
|
}
|
|
125
341
|
exports.getSwapDirection = getSwapDirection;
|
|
126
|
-
/**
|
|
127
|
-
* Helper function calculating adjust k cost
|
|
128
|
-
* @param market
|
|
129
|
-
* @param marketIndex
|
|
130
|
-
* @param numerator
|
|
131
|
-
* @param denomenator
|
|
132
|
-
* @returns cost : Precision QUOTE_ASSET_PRECISION
|
|
133
|
-
*/
|
|
134
|
-
function calculateAdjustKCost(market, marketIndex, numerator, denomenator) {
|
|
135
|
-
const netUserPosition = {
|
|
136
|
-
baseAssetAmount: market.baseAssetAmount,
|
|
137
|
-
lastCumulativeFundingRate: market.amm.cumulativeFundingRate,
|
|
138
|
-
marketIndex: new anchor_1.BN(marketIndex),
|
|
139
|
-
quoteAssetAmount: new anchor_1.BN(0),
|
|
140
|
-
openOrders: new anchor_1.BN(0),
|
|
141
|
-
};
|
|
142
|
-
const currentValue = (0, position_1.calculateBaseAssetValue)(market, netUserPosition);
|
|
143
|
-
const marketNewK = Object.assign({}, market);
|
|
144
|
-
marketNewK.amm = Object.assign({}, market.amm);
|
|
145
|
-
marketNewK.amm.baseAssetReserve = market.amm.baseAssetReserve
|
|
146
|
-
.mul(numerator)
|
|
147
|
-
.div(denomenator);
|
|
148
|
-
marketNewK.amm.quoteAssetReserve = market.amm.quoteAssetReserve
|
|
149
|
-
.mul(numerator)
|
|
150
|
-
.div(denomenator);
|
|
151
|
-
marketNewK.amm.sqrtK = market.amm.sqrtK.mul(numerator).div(denomenator);
|
|
152
|
-
netUserPosition.quoteAssetAmount = currentValue;
|
|
153
|
-
const cost = (0, __1.calculatePositionPNL)(marketNewK, netUserPosition);
|
|
154
|
-
const p = numericConstants_1.PEG_PRECISION.mul(numerator).div(denomenator);
|
|
155
|
-
const x = market.amm.baseAssetReserve;
|
|
156
|
-
const y = market.amm.quoteAssetReserve;
|
|
157
|
-
const delta = market.baseAssetAmount;
|
|
158
|
-
const k = market.amm.sqrtK.mul(market.amm.sqrtK);
|
|
159
|
-
const numer1 = numericConstants_1.PEG_PRECISION.sub(p).mul(y).div(numericConstants_1.PEG_PRECISION);
|
|
160
|
-
const numer20 = k
|
|
161
|
-
.mul(p)
|
|
162
|
-
.mul(p)
|
|
163
|
-
.div(numericConstants_1.PEG_PRECISION)
|
|
164
|
-
.div(numericConstants_1.PEG_PRECISION)
|
|
165
|
-
.div(x.mul(p).div(numericConstants_1.PEG_PRECISION).add(delta));
|
|
166
|
-
const numer21 = k.div(x.add(delta));
|
|
167
|
-
const formulaCost = numer21
|
|
168
|
-
.sub(numer20)
|
|
169
|
-
.sub(numer1)
|
|
170
|
-
.mul(market.amm.pegMultiplier)
|
|
171
|
-
.div(numericConstants_1.AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO);
|
|
172
|
-
console.log((0, __1.convertToNumber)(formulaCost, numericConstants_1.QUOTE_PRECISION));
|
|
173
|
-
// p.div(p.mul(x).add(delta)).sub()
|
|
174
|
-
return cost;
|
|
175
|
-
}
|
|
176
|
-
exports.calculateAdjustKCost = calculateAdjustKCost;
|
|
177
|
-
/**
|
|
178
|
-
* Helper function calculating adjust pegMultiplier (repeg) cost
|
|
179
|
-
*
|
|
180
|
-
* @param market
|
|
181
|
-
* @param marketIndex
|
|
182
|
-
* @param newPeg
|
|
183
|
-
* @returns cost : Precision QUOTE_ASSET_PRECISION
|
|
184
|
-
*/
|
|
185
|
-
function calculateRepegCost(market, marketIndex, newPeg) {
|
|
186
|
-
const netUserPosition = {
|
|
187
|
-
baseAssetAmount: market.baseAssetAmount,
|
|
188
|
-
lastCumulativeFundingRate: market.amm.cumulativeFundingRate,
|
|
189
|
-
marketIndex: new anchor_1.BN(marketIndex),
|
|
190
|
-
quoteAssetAmount: new anchor_1.BN(0),
|
|
191
|
-
openOrders: new anchor_1.BN(0),
|
|
192
|
-
};
|
|
193
|
-
const currentValue = (0, position_1.calculateBaseAssetValue)(market, netUserPosition);
|
|
194
|
-
netUserPosition.quoteAssetAmount = currentValue;
|
|
195
|
-
const prevMarketPrice = (0, __1.calculateMarkPrice)(market);
|
|
196
|
-
const marketNewPeg = Object.assign({}, market);
|
|
197
|
-
marketNewPeg.amm = Object.assign({}, market.amm);
|
|
198
|
-
// const marketNewPeg = JSON.parse(JSON.stringify(market));
|
|
199
|
-
marketNewPeg.amm.pegMultiplier = newPeg;
|
|
200
|
-
console.log('Price moves from', (0, __1.convertToNumber)(prevMarketPrice), 'to', (0, __1.convertToNumber)((0, __1.calculateMarkPrice)(marketNewPeg)));
|
|
201
|
-
const cost = (0, __1.calculatePositionPNL)(marketNewPeg, netUserPosition);
|
|
202
|
-
const k = market.amm.sqrtK.mul(market.amm.sqrtK);
|
|
203
|
-
const newQuoteAssetReserve = k.div(market.amm.baseAssetReserve.add(netUserPosition.baseAssetAmount));
|
|
204
|
-
const deltaQuoteAssetReserves = newQuoteAssetReserve.sub(market.amm.quoteAssetReserve);
|
|
205
|
-
const cost2 = deltaQuoteAssetReserves
|
|
206
|
-
.mul(market.amm.pegMultiplier.sub(newPeg))
|
|
207
|
-
.div(numericConstants_1.AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO);
|
|
208
|
-
console.log((0, __1.convertToNumber)(cost2, numericConstants_1.QUOTE_PRECISION));
|
|
209
|
-
return cost;
|
|
210
|
-
}
|
|
211
|
-
exports.calculateRepegCost = calculateRepegCost;
|
|
212
342
|
/**
|
|
213
343
|
* Helper function calculating terminal price of amm
|
|
214
344
|
*
|
|
@@ -216,10 +346,10 @@ exports.calculateRepegCost = calculateRepegCost;
|
|
|
216
346
|
* @returns cost : Precision MARK_PRICE_PRECISION
|
|
217
347
|
*/
|
|
218
348
|
function calculateTerminalPrice(market) {
|
|
219
|
-
const directionToClose = market.
|
|
349
|
+
const directionToClose = market.amm.netBaseAssetAmount.gt(numericConstants_1.ZERO)
|
|
220
350
|
? types_1.PositionDirection.SHORT
|
|
221
351
|
: types_1.PositionDirection.LONG;
|
|
222
|
-
const [newQuoteAssetReserve, newBaseAssetReserve] = calculateAmmReservesAfterSwap(market.amm, 'base', market.
|
|
352
|
+
const [newQuoteAssetReserve, newBaseAssetReserve] = calculateAmmReservesAfterSwap(market.amm, 'base', market.amm.netBaseAssetAmount.abs(), getSwapDirection('base', directionToClose));
|
|
223
353
|
const terminalPrice = newQuoteAssetReserve
|
|
224
354
|
.mul(numericConstants_1.MARK_PRICE_PRECISION)
|
|
225
355
|
.mul(market.amm.pegMultiplier)
|
|
@@ -228,7 +358,7 @@ function calculateTerminalPrice(market) {
|
|
|
228
358
|
return terminalPrice;
|
|
229
359
|
}
|
|
230
360
|
exports.calculateTerminalPrice = calculateTerminalPrice;
|
|
231
|
-
function calculateMaxBaseAssetAmountToTrade(amm, limit_price, direction,
|
|
361
|
+
function calculateMaxBaseAssetAmountToTrade(amm, limit_price, direction, oraclePriceData) {
|
|
232
362
|
const invariant = amm.sqrtK.mul(amm.sqrtK);
|
|
233
363
|
const newBaseAssetReserveSquared = invariant
|
|
234
364
|
.mul(numericConstants_1.MARK_PRICE_PRECISION)
|
|
@@ -236,13 +366,7 @@ function calculateMaxBaseAssetAmountToTrade(amm, limit_price, direction, useSpre
|
|
|
236
366
|
.div(limit_price)
|
|
237
367
|
.div(numericConstants_1.PEG_PRECISION);
|
|
238
368
|
const newBaseAssetReserve = (0, __1.squareRootBN)(newBaseAssetReserveSquared);
|
|
239
|
-
|
|
240
|
-
if (useSpread) {
|
|
241
|
-
baseAssetReserveBefore = calculateSpreadReserves(amm, direction).baseAssetReserve;
|
|
242
|
-
}
|
|
243
|
-
else {
|
|
244
|
-
baseAssetReserveBefore = amm.baseAssetReserve;
|
|
245
|
-
}
|
|
369
|
+
const baseAssetReserveBefore = calculateSpreadReserves(amm, direction, oraclePriceData).baseAssetReserve;
|
|
246
370
|
if (newBaseAssetReserve.gt(baseAssetReserveBefore)) {
|
|
247
371
|
return [
|
|
248
372
|
newBaseAssetReserve.sub(baseAssetReserveBefore),
|
|
@@ -261,69 +385,6 @@ function calculateMaxBaseAssetAmountToTrade(amm, limit_price, direction, useSpre
|
|
|
261
385
|
}
|
|
262
386
|
}
|
|
263
387
|
exports.calculateMaxBaseAssetAmountToTrade = calculateMaxBaseAssetAmountToTrade;
|
|
264
|
-
function calculateBudgetedK(market, cost) {
|
|
265
|
-
// wolframalpha.com
|
|
266
|
-
// (1/(x+d) - p/(x*p+d))*y*d*Q = C solve for p
|
|
267
|
-
// p = (d(y*d*Q - C(x+d))) / (C*x(x+d) + y*y*d*Q)
|
|
268
|
-
// todo: assumes k = x * y
|
|
269
|
-
// otherwise use: (y(1-p) + (kp^2/(x*p+d)) - k/(x+d)) * Q = C solve for p
|
|
270
|
-
// const k = market.amm.sqrtK.mul(market.amm.sqrtK);
|
|
271
|
-
const x = market.amm.baseAssetReserve;
|
|
272
|
-
const y = market.amm.quoteAssetReserve;
|
|
273
|
-
const d = market.baseAssetAmount;
|
|
274
|
-
const Q = market.amm.pegMultiplier;
|
|
275
|
-
const C = cost.mul(new anchor_1.BN(-1));
|
|
276
|
-
const numer1 = y.mul(d).mul(Q).div(numericConstants_1.AMM_RESERVE_PRECISION).div(numericConstants_1.PEG_PRECISION);
|
|
277
|
-
const numer2 = C.mul(x.add(d)).div(numericConstants_1.QUOTE_PRECISION);
|
|
278
|
-
const denom1 = C.mul(x)
|
|
279
|
-
.mul(x.add(d))
|
|
280
|
-
.div(numericConstants_1.AMM_RESERVE_PRECISION)
|
|
281
|
-
.div(numericConstants_1.QUOTE_PRECISION);
|
|
282
|
-
const denom2 = y
|
|
283
|
-
.mul(d)
|
|
284
|
-
.mul(d)
|
|
285
|
-
.mul(Q)
|
|
286
|
-
.div(numericConstants_1.AMM_RESERVE_PRECISION)
|
|
287
|
-
.div(numericConstants_1.AMM_RESERVE_PRECISION)
|
|
288
|
-
.div(numericConstants_1.PEG_PRECISION);
|
|
289
|
-
const numerator = d
|
|
290
|
-
.mul(numer1.add(numer2))
|
|
291
|
-
.div(numericConstants_1.AMM_RESERVE_PRECISION)
|
|
292
|
-
.div(numericConstants_1.AMM_RESERVE_PRECISION)
|
|
293
|
-
.div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO);
|
|
294
|
-
const denominator = denom1
|
|
295
|
-
.add(denom2)
|
|
296
|
-
.div(numericConstants_1.AMM_RESERVE_PRECISION)
|
|
297
|
-
.div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO);
|
|
298
|
-
console.log(numerator, denominator);
|
|
299
|
-
// const p = (numerator).div(denominator);
|
|
300
|
-
// const formulaCost = (numer21.sub(numer20).sub(numer1)).mul(market.amm.pegMultiplier).div(AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO)
|
|
301
|
-
// console.log(convertToNumber(formulaCost, QUOTE_PRECISION))
|
|
302
|
-
return [numerator, denominator];
|
|
303
|
-
}
|
|
304
|
-
exports.calculateBudgetedK = calculateBudgetedK;
|
|
305
|
-
function calculateBudgetedPeg(market, cost) {
|
|
306
|
-
// wolframalpha.com
|
|
307
|
-
// (1/(x+d) - p/(x*p+d))*y*d*Q = C solve for p
|
|
308
|
-
// p = (d(y*d*Q - C(x+d))) / (C*x(x+d) + y*y*d*Q)
|
|
309
|
-
// todo: assumes k = x * y
|
|
310
|
-
// otherwise use: (y(1-p) + (kp^2/(x*p+d)) - k/(x+d)) * Q = C solve for p
|
|
311
|
-
const k = market.amm.sqrtK.mul(market.amm.sqrtK);
|
|
312
|
-
const x = market.amm.baseAssetReserve;
|
|
313
|
-
const y = market.amm.quoteAssetReserve;
|
|
314
|
-
const d = market.baseAssetAmount;
|
|
315
|
-
const Q = market.amm.pegMultiplier;
|
|
316
|
-
const C = cost.mul(new anchor_1.BN(-1));
|
|
317
|
-
const deltaQuoteAssetReserves = y.sub(k.div(x.add(d)));
|
|
318
|
-
const deltaPegMultiplier = C.mul(numericConstants_1.MARK_PRICE_PRECISION)
|
|
319
|
-
.div(deltaQuoteAssetReserves.div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO))
|
|
320
|
-
.mul(numericConstants_1.PEG_PRECISION)
|
|
321
|
-
.div(numericConstants_1.QUOTE_PRECISION);
|
|
322
|
-
console.log(Q.toNumber(), 'change by', deltaPegMultiplier.toNumber() / numericConstants_1.MARK_PRICE_PRECISION.toNumber());
|
|
323
|
-
const newPeg = Q.sub(deltaPegMultiplier.mul(numericConstants_1.PEG_PRECISION).div(numericConstants_1.MARK_PRICE_PRECISION));
|
|
324
|
-
return newPeg;
|
|
325
|
-
}
|
|
326
|
-
exports.calculateBudgetedPeg = calculateBudgetedPeg;
|
|
327
388
|
function calculateQuoteAssetAmountSwapped(quoteAssetReserves, pegMultiplier, swapDirection) {
|
|
328
389
|
let quoteAssetAmount = quoteAssetReserves
|
|
329
390
|
.mul(pegMultiplier)
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getAuctionPrice = exports.isAuctionComplete = void 0;
|
|
4
|
+
const types_1 = require("../types");
|
|
5
|
+
const _1 = require("../.");
|
|
6
|
+
function isAuctionComplete(order, slot) {
|
|
7
|
+
return new _1.BN(slot).sub(order.slot).gte(new _1.BN(order.auctionDuration));
|
|
8
|
+
}
|
|
9
|
+
exports.isAuctionComplete = isAuctionComplete;
|
|
10
|
+
function getAuctionPrice(order, slot) {
|
|
11
|
+
const slotsElapsed = new _1.BN(slot).sub(order.slot);
|
|
12
|
+
const deltaDenominator = new _1.BN(order.auctionDuration);
|
|
13
|
+
const deltaNumerator = _1.BN.min(slotsElapsed, deltaDenominator);
|
|
14
|
+
if (deltaDenominator.eq(_1.ZERO)) {
|
|
15
|
+
return order.auctionEndPrice;
|
|
16
|
+
}
|
|
17
|
+
let priceDelta;
|
|
18
|
+
if ((0, types_1.isVariant)(order.direction, 'long')) {
|
|
19
|
+
priceDelta = order.auctionEndPrice
|
|
20
|
+
.sub(order.auctionStartPrice)
|
|
21
|
+
.mul(deltaNumerator)
|
|
22
|
+
.div(deltaDenominator);
|
|
23
|
+
}
|
|
24
|
+
else {
|
|
25
|
+
priceDelta = order.auctionStartPrice
|
|
26
|
+
.sub(order.auctionEndPrice)
|
|
27
|
+
.mul(deltaNumerator)
|
|
28
|
+
.div(deltaDenominator);
|
|
29
|
+
}
|
|
30
|
+
let price;
|
|
31
|
+
if ((0, types_1.isVariant)(order.direction, 'long')) {
|
|
32
|
+
price = order.auctionStartPrice.add(priceDelta);
|
|
33
|
+
}
|
|
34
|
+
else {
|
|
35
|
+
price = order.auctionStartPrice.sub(priceDelta);
|
|
36
|
+
}
|
|
37
|
+
return price;
|
|
38
|
+
}
|
|
39
|
+
exports.getAuctionPrice = getAuctionPrice;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/// <reference types="bn.js" />
|
|
2
|
+
import { BankAccount, BankBalanceType } from '../types';
|
|
3
|
+
import { BN } from '@project-serum/anchor';
|
|
4
|
+
export declare function getBalance(tokenAmount: BN, bank: BankAccount, balanceType: BankBalanceType): BN;
|
|
5
|
+
export declare function getTokenAmount(balanceAmount: BN, bank: BankAccount, balanceType: BankBalanceType): BN;
|
|
6
|
+
export declare function calculateInterestAccumulated(bank: BankAccount, now: BN): {
|
|
7
|
+
borrowInterest: BN;
|
|
8
|
+
depositInterest: BN;
|
|
9
|
+
};
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.calculateInterestAccumulated = exports.getTokenAmount = exports.getBalance = void 0;
|
|
4
|
+
const types_1 = require("../types");
|
|
5
|
+
const anchor_1 = require("@project-serum/anchor");
|
|
6
|
+
const numericConstants_1 = require("../constants/numericConstants");
|
|
7
|
+
function getBalance(tokenAmount, bank, balanceType) {
|
|
8
|
+
const precisionIncrease = numericConstants_1.TEN.pow(new anchor_1.BN(16 - bank.decimals));
|
|
9
|
+
const cumulativeInterest = (0, types_1.isVariant)(balanceType, 'deposit')
|
|
10
|
+
? bank.cumulativeDepositInterest
|
|
11
|
+
: bank.cumulativeBorrowInterest;
|
|
12
|
+
let balance = tokenAmount.mul(precisionIncrease).div(cumulativeInterest);
|
|
13
|
+
if (!balance.eq(numericConstants_1.ZERO) && (0, types_1.isVariant)(balanceType, 'borrow')) {
|
|
14
|
+
balance = balance.add(numericConstants_1.ONE);
|
|
15
|
+
}
|
|
16
|
+
return balance;
|
|
17
|
+
}
|
|
18
|
+
exports.getBalance = getBalance;
|
|
19
|
+
function getTokenAmount(balanceAmount, bank, balanceType) {
|
|
20
|
+
const precisionDecrease = numericConstants_1.TEN.pow(new anchor_1.BN(16 - bank.decimals));
|
|
21
|
+
const cumulativeInterest = (0, types_1.isVariant)(balanceType, 'deposit')
|
|
22
|
+
? bank.cumulativeDepositInterest
|
|
23
|
+
: bank.cumulativeBorrowInterest;
|
|
24
|
+
return balanceAmount.mul(cumulativeInterest).div(precisionDecrease);
|
|
25
|
+
}
|
|
26
|
+
exports.getTokenAmount = getTokenAmount;
|
|
27
|
+
function calculateInterestAccumulated(bank, now) {
|
|
28
|
+
const token_deposit_amount = getTokenAmount(bank.depositBalance, bank, types_1.BankBalanceType.DEPOSIT);
|
|
29
|
+
const token_borrow_amount = getTokenAmount(bank.borrowBalance, bank, types_1.BankBalanceType.BORROW);
|
|
30
|
+
let utilization;
|
|
31
|
+
if (token_borrow_amount.eq(numericConstants_1.ZERO) && token_deposit_amount.eq(numericConstants_1.ZERO)) {
|
|
32
|
+
utilization = numericConstants_1.ZERO;
|
|
33
|
+
}
|
|
34
|
+
else if (token_deposit_amount.eq(numericConstants_1.ZERO)) {
|
|
35
|
+
utilization = numericConstants_1.BANK_UTILIZATION_PRECISION;
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
utilization = token_borrow_amount
|
|
39
|
+
.mul(numericConstants_1.BANK_UTILIZATION_PRECISION)
|
|
40
|
+
.div(token_deposit_amount);
|
|
41
|
+
}
|
|
42
|
+
let interest_rate;
|
|
43
|
+
if (utilization.gt(bank.optimalUtilization)) {
|
|
44
|
+
const surplusUtilization = utilization.sub(bank.optimalUtilization);
|
|
45
|
+
const borrowRateSlope = bank.maxBorrowRate
|
|
46
|
+
.sub(bank.optimalBorrowRate)
|
|
47
|
+
.mul(numericConstants_1.BANK_UTILIZATION_PRECISION)
|
|
48
|
+
.div(numericConstants_1.BANK_UTILIZATION_PRECISION.sub(bank.optimalUtilization));
|
|
49
|
+
interest_rate = bank.optimalBorrowRate.add(surplusUtilization.mul(borrowRateSlope).div(numericConstants_1.BANK_UTILIZATION_PRECISION));
|
|
50
|
+
}
|
|
51
|
+
else {
|
|
52
|
+
const borrowRateSlope = bank.optimalBorrowRate
|
|
53
|
+
.mul(numericConstants_1.BANK_UTILIZATION_PRECISION)
|
|
54
|
+
.div(numericConstants_1.BANK_UTILIZATION_PRECISION.sub(bank.optimalUtilization));
|
|
55
|
+
interest_rate = utilization
|
|
56
|
+
.mul(borrowRateSlope)
|
|
57
|
+
.div(numericConstants_1.BANK_UTILIZATION_PRECISION);
|
|
58
|
+
}
|
|
59
|
+
const timeSinceLastUpdate = now.sub(bank.lastUpdated);
|
|
60
|
+
const modifiedBorrowRate = interest_rate.mul(timeSinceLastUpdate);
|
|
61
|
+
const modifiedDepositRate = modifiedBorrowRate
|
|
62
|
+
.mul(utilization)
|
|
63
|
+
.div(numericConstants_1.BANK_UTILIZATION_PRECISION);
|
|
64
|
+
const borrowInterest = bank.cumulativeBorrowInterest
|
|
65
|
+
.mul(modifiedBorrowRate)
|
|
66
|
+
.div(numericConstants_1.ONE_YEAR)
|
|
67
|
+
.div(numericConstants_1.BANK_INTEREST_PRECISION)
|
|
68
|
+
.add(numericConstants_1.ONE);
|
|
69
|
+
const depositInterest = bank.cumulativeDepositInterest
|
|
70
|
+
.mul(modifiedDepositRate)
|
|
71
|
+
.div(numericConstants_1.ONE_YEAR)
|
|
72
|
+
.div(numericConstants_1.BANK_INTEREST_PRECISION);
|
|
73
|
+
return { borrowInterest, depositInterest };
|
|
74
|
+
}
|
|
75
|
+
exports.calculateInterestAccumulated = calculateInterestAccumulated;
|
package/lib/math/conversion.d.ts
CHANGED
package/lib/math/conversion.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.
|
|
3
|
+
exports.convertToNumber = void 0;
|
|
4
4
|
const numericConstants_1 = require("../constants/numericConstants");
|
|
5
5
|
const convertToNumber = (bigNumber, precision = numericConstants_1.MARK_PRICE_PRECISION) => {
|
|
6
6
|
if (!bigNumber)
|
|
@@ -9,7 +9,3 @@ const convertToNumber = (bigNumber, precision = numericConstants_1.MARK_PRICE_PR
|
|
|
9
9
|
bigNumber.mod(precision).toNumber() / precision.toNumber());
|
|
10
10
|
};
|
|
11
11
|
exports.convertToNumber = convertToNumber;
|
|
12
|
-
const convertBaseAssetAmountToNumber = (baseAssetAmount) => {
|
|
13
|
-
return (0, exports.convertToNumber)(baseAssetAmount, numericConstants_1.MARK_PRICE_PRECISION.mul(numericConstants_1.PEG_PRECISION));
|
|
14
|
-
};
|
|
15
|
-
exports.convertBaseAssetAmountToNumber = convertBaseAssetAmountToNumber;
|