@drift-labs/sdk 0.2.0-master.7 → 0.2.0-master.8
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/clearingHouse.js +38 -25
- package/lib/constants/banks.js +9 -1
- package/package.json +1 -1
- package/src/accounts/bulkAccountLoader.js +197 -0
- package/src/accounts/bulkUserSubscription.js +33 -0
- package/src/accounts/fetch.js +29 -0
- package/src/accounts/pollingClearingHouseAccountSubscriber.js +311 -0
- package/src/accounts/pollingOracleSubscriber.js +93 -0
- package/src/accounts/pollingTokenAccountSubscriber.js +90 -0
- package/src/accounts/pollingUserAccountSubscriber.js +132 -0
- package/src/accounts/types.js +10 -0
- package/src/accounts/utils.js +7 -0
- package/src/accounts/webSocketAccountSubscriber.js +93 -0
- package/src/accounts/webSocketClearingHouseAccountSubscriber.js +233 -0
- package/src/accounts/webSocketUserAccountSubscriber.js +62 -0
- package/src/addresses/marketAddresses.js +26 -0
- package/src/addresses/pda.js +104 -0
- package/src/assert/assert.js +9 -0
- package/src/clearingHouse.ts +43 -27
- package/src/constants/banks.ts +9 -1
- package/src/events/eventList.js +77 -0
- package/src/events/eventSubscriber.js +139 -0
- package/src/events/fetchLogs.js +50 -0
- package/src/events/pollingLogProvider.js +64 -0
- package/src/events/sort.js +44 -0
- package/src/events/txEventCache.js +71 -0
- package/src/events/types.js +20 -0
- package/src/events/webSocketLogProvider.js +41 -0
- package/src/examples/makeTradeExample.js +80 -0
- package/src/factory/bigNum.js +364 -0
- package/src/factory/oracleClient.js +20 -0
- package/src/index.js +69 -0
- package/src/math/amm.js +369 -0
- package/src/math/auction.js +42 -0
- package/src/math/bankBalance.js +75 -0
- package/src/math/conversion.js +11 -0
- package/src/math/funding.js +248 -0
- package/src/math/market.js +57 -0
- package/src/math/oracles.js +26 -0
- package/src/math/orders.js +110 -0
- package/src/math/position.js +140 -0
- package/src/math/repeg.js +128 -0
- package/src/math/state.js +15 -0
- package/src/math/trade.js +253 -0
- package/src/math/utils.js +0 -1
- package/src/mockUSDCFaucet.js +171 -0
- package/src/oracles/oracleClientCache.js +19 -0
- package/src/oracles/pythClient.js +46 -0
- package/src/oracles/quoteAssetOracleClient.js +32 -0
- package/src/oracles/switchboardClient.js +69 -0
- package/src/oracles/types.js +2 -0
- package/src/orderParams.js +20 -0
- package/src/orders.js +134 -0
- package/src/slot/SlotSubscriber.js +39 -0
- package/src/token/index.js +38 -0
- package/src/tx/retryTxSender.js +188 -0
- package/src/tx/types.js +2 -0
- package/src/tx/utils.js +17 -0
- package/src/types.js +114 -0
- package/src/userName.js +20 -0
- package/src/util/promiseTimeout.js +14 -0
- package/src/util/tps.js +27 -0
- package/src/wallet.js +35 -0
- package/src/util/computeUnits.js +0 -17
- package/src/util/computeUnits.js.map +0 -1
package/src/math/amm.js
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
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
|
+
const anchor_1 = require("@project-serum/anchor");
|
|
5
|
+
const numericConstants_1 = require("../constants/numericConstants");
|
|
6
|
+
const types_1 = require("../types");
|
|
7
|
+
const assert_1 = require("../assert/assert");
|
|
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 = 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 = 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 = 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 = repeg_1.calculateAdjustKCost(amm, pKNumer, pKDenom);
|
|
58
|
+
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 = repeg_1.calculateBudgetedPeg(newAmm, prePegCost, targetPrice);
|
|
71
|
+
prePegCost = 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;
|
|
124
|
+
/**
|
|
125
|
+
* Calculates a price given an arbitrary base and quote amount (they must have the same precision)
|
|
126
|
+
*
|
|
127
|
+
* @param baseAssetReserves
|
|
128
|
+
* @param quoteAssetReserves
|
|
129
|
+
* @param pegMultiplier
|
|
130
|
+
* @returns price : Precision MARK_PRICE_PRECISION
|
|
131
|
+
*/
|
|
132
|
+
function calculatePrice(baseAssetReserves, quoteAssetReserves, pegMultiplier) {
|
|
133
|
+
if (baseAssetReserves.abs().lte(numericConstants_1.ZERO)) {
|
|
134
|
+
return new anchor_1.BN(0);
|
|
135
|
+
}
|
|
136
|
+
return quoteAssetReserves
|
|
137
|
+
.mul(numericConstants_1.MARK_PRICE_PRECISION)
|
|
138
|
+
.mul(pegMultiplier)
|
|
139
|
+
.div(numericConstants_1.PEG_PRECISION)
|
|
140
|
+
.div(baseAssetReserves);
|
|
141
|
+
}
|
|
142
|
+
exports.calculatePrice = calculatePrice;
|
|
143
|
+
/**
|
|
144
|
+
* Calculates what the amm reserves would be after swapping a quote or base asset amount.
|
|
145
|
+
*
|
|
146
|
+
* @param amm
|
|
147
|
+
* @param inputAssetType
|
|
148
|
+
* @param swapAmount
|
|
149
|
+
* @param swapDirection
|
|
150
|
+
* @returns quoteAssetReserve and baseAssetReserve after swap. : Precision AMM_RESERVE_PRECISION
|
|
151
|
+
*/
|
|
152
|
+
function calculateAmmReservesAfterSwap(amm, inputAssetType, swapAmount, swapDirection) {
|
|
153
|
+
assert_1.assert(swapAmount.gte(numericConstants_1.ZERO), 'swapAmount must be greater than 0');
|
|
154
|
+
let newQuoteAssetReserve;
|
|
155
|
+
let newBaseAssetReserve;
|
|
156
|
+
if (inputAssetType === 'quote') {
|
|
157
|
+
swapAmount = swapAmount
|
|
158
|
+
.mul(numericConstants_1.AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO)
|
|
159
|
+
.div(amm.pegMultiplier);
|
|
160
|
+
[newQuoteAssetReserve, newBaseAssetReserve] = calculateSwapOutput(amm.quoteAssetReserve, swapAmount, swapDirection, amm.sqrtK.mul(amm.sqrtK));
|
|
161
|
+
}
|
|
162
|
+
else {
|
|
163
|
+
[newBaseAssetReserve, newQuoteAssetReserve] = calculateSwapOutput(amm.baseAssetReserve, swapAmount, swapDirection, amm.sqrtK.mul(amm.sqrtK));
|
|
164
|
+
}
|
|
165
|
+
return [newQuoteAssetReserve, newBaseAssetReserve];
|
|
166
|
+
}
|
|
167
|
+
exports.calculateAmmReservesAfterSwap = calculateAmmReservesAfterSwap;
|
|
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
|
+
}
|
|
210
|
+
}
|
|
211
|
+
else {
|
|
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
|
+
if (amm.baseSpread == 0 || amm.curveUpdateIntensity == 0) {
|
|
231
|
+
return amm.baseSpread / 2;
|
|
232
|
+
}
|
|
233
|
+
const markPrice = calculatePrice(amm.baseAssetReserve, amm.quoteAssetReserve, amm.pegMultiplier);
|
|
234
|
+
const targetPrice = (oraclePriceData === null || oraclePriceData === void 0 ? void 0 : oraclePriceData.price) || markPrice;
|
|
235
|
+
const confInterval = oraclePriceData.confidence || numericConstants_1.ZERO;
|
|
236
|
+
const targetMarkSpreadPct = markPrice
|
|
237
|
+
.sub(targetPrice)
|
|
238
|
+
.mul(numericConstants_1.BID_ASK_SPREAD_PRECISION)
|
|
239
|
+
.div(markPrice);
|
|
240
|
+
const confIntervalPct = confInterval
|
|
241
|
+
.mul(numericConstants_1.BID_ASK_SPREAD_PRECISION)
|
|
242
|
+
.div(markPrice);
|
|
243
|
+
const [longSpread, shortSpread] = calculateSpreadBN(amm.baseSpread, targetMarkSpreadPct, confIntervalPct, amm.maxSpread, amm.quoteAssetReserve, amm.terminalQuoteAssetReserve, amm.pegMultiplier, amm.netBaseAssetAmount, markPrice, amm.totalFeeMinusDistributions);
|
|
244
|
+
let spread;
|
|
245
|
+
if (types_1.isVariant(direction, 'long')) {
|
|
246
|
+
spread = longSpread;
|
|
247
|
+
}
|
|
248
|
+
else {
|
|
249
|
+
spread = shortSpread;
|
|
250
|
+
}
|
|
251
|
+
return spread;
|
|
252
|
+
}
|
|
253
|
+
exports.calculateSpread = calculateSpread;
|
|
254
|
+
function calculateSpreadReserves(amm, direction, oraclePriceData) {
|
|
255
|
+
const spread = calculateSpread(amm, direction, oraclePriceData);
|
|
256
|
+
if (spread === 0) {
|
|
257
|
+
return {
|
|
258
|
+
baseAssetReserve: amm.baseAssetReserve,
|
|
259
|
+
quoteAssetReserve: amm.quoteAssetReserve,
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
const quoteAsserReserveDelta = amm.quoteAssetReserve.div(numericConstants_1.BID_ASK_SPREAD_PRECISION.div(new anchor_1.BN(spread / 2)));
|
|
263
|
+
let quoteAssetReserve;
|
|
264
|
+
if (types_1.isVariant(direction, 'long')) {
|
|
265
|
+
quoteAssetReserve = amm.quoteAssetReserve.add(quoteAsserReserveDelta);
|
|
266
|
+
}
|
|
267
|
+
else {
|
|
268
|
+
quoteAssetReserve = amm.quoteAssetReserve.sub(quoteAsserReserveDelta);
|
|
269
|
+
}
|
|
270
|
+
const baseAssetReserve = amm.sqrtK.mul(amm.sqrtK).div(quoteAssetReserve);
|
|
271
|
+
return {
|
|
272
|
+
baseAssetReserve,
|
|
273
|
+
quoteAssetReserve,
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
exports.calculateSpreadReserves = calculateSpreadReserves;
|
|
277
|
+
/**
|
|
278
|
+
* Helper function calculating constant product curve output. Agnostic to whether input asset is quote or base
|
|
279
|
+
*
|
|
280
|
+
* @param inputAssetReserve
|
|
281
|
+
* @param swapAmount
|
|
282
|
+
* @param swapDirection
|
|
283
|
+
* @param invariant
|
|
284
|
+
* @returns newInputAssetReserve and newOutputAssetReserve after swap. : Precision AMM_RESERVE_PRECISION
|
|
285
|
+
*/
|
|
286
|
+
function calculateSwapOutput(inputAssetReserve, swapAmount, swapDirection, invariant) {
|
|
287
|
+
let newInputAssetReserve;
|
|
288
|
+
if (swapDirection === types_1.SwapDirection.ADD) {
|
|
289
|
+
newInputAssetReserve = inputAssetReserve.add(swapAmount);
|
|
290
|
+
}
|
|
291
|
+
else {
|
|
292
|
+
newInputAssetReserve = inputAssetReserve.sub(swapAmount);
|
|
293
|
+
}
|
|
294
|
+
const newOutputAssetReserve = invariant.div(newInputAssetReserve);
|
|
295
|
+
return [newInputAssetReserve, newOutputAssetReserve];
|
|
296
|
+
}
|
|
297
|
+
exports.calculateSwapOutput = calculateSwapOutput;
|
|
298
|
+
/**
|
|
299
|
+
* Translate long/shorting quote/base asset into amm operation
|
|
300
|
+
*
|
|
301
|
+
* @param inputAssetType
|
|
302
|
+
* @param positionDirection
|
|
303
|
+
*/
|
|
304
|
+
function getSwapDirection(inputAssetType, positionDirection) {
|
|
305
|
+
if (types_1.isVariant(positionDirection, 'long') && inputAssetType === 'base') {
|
|
306
|
+
return types_1.SwapDirection.REMOVE;
|
|
307
|
+
}
|
|
308
|
+
if (types_1.isVariant(positionDirection, 'short') && inputAssetType === 'quote') {
|
|
309
|
+
return types_1.SwapDirection.REMOVE;
|
|
310
|
+
}
|
|
311
|
+
return types_1.SwapDirection.ADD;
|
|
312
|
+
}
|
|
313
|
+
exports.getSwapDirection = getSwapDirection;
|
|
314
|
+
/**
|
|
315
|
+
* Helper function calculating terminal price of amm
|
|
316
|
+
*
|
|
317
|
+
* @param market
|
|
318
|
+
* @returns cost : Precision MARK_PRICE_PRECISION
|
|
319
|
+
*/
|
|
320
|
+
function calculateTerminalPrice(market) {
|
|
321
|
+
const directionToClose = market.amm.netBaseAssetAmount.gt(numericConstants_1.ZERO)
|
|
322
|
+
? types_1.PositionDirection.SHORT
|
|
323
|
+
: types_1.PositionDirection.LONG;
|
|
324
|
+
const [newQuoteAssetReserve, newBaseAssetReserve] = calculateAmmReservesAfterSwap(market.amm, 'base', market.amm.netBaseAssetAmount.abs(), getSwapDirection('base', directionToClose));
|
|
325
|
+
const terminalPrice = newQuoteAssetReserve
|
|
326
|
+
.mul(numericConstants_1.MARK_PRICE_PRECISION)
|
|
327
|
+
.mul(market.amm.pegMultiplier)
|
|
328
|
+
.div(numericConstants_1.PEG_PRECISION)
|
|
329
|
+
.div(newBaseAssetReserve);
|
|
330
|
+
return terminalPrice;
|
|
331
|
+
}
|
|
332
|
+
exports.calculateTerminalPrice = calculateTerminalPrice;
|
|
333
|
+
function calculateMaxBaseAssetAmountToTrade(amm, limit_price, direction, oraclePriceData) {
|
|
334
|
+
const invariant = amm.sqrtK.mul(amm.sqrtK);
|
|
335
|
+
const newBaseAssetReserveSquared = invariant
|
|
336
|
+
.mul(numericConstants_1.MARK_PRICE_PRECISION)
|
|
337
|
+
.mul(amm.pegMultiplier)
|
|
338
|
+
.div(limit_price)
|
|
339
|
+
.div(numericConstants_1.PEG_PRECISION);
|
|
340
|
+
const newBaseAssetReserve = __1.squareRootBN(newBaseAssetReserveSquared);
|
|
341
|
+
const baseAssetReserveBefore = calculateSpreadReserves(amm, direction, oraclePriceData).baseAssetReserve;
|
|
342
|
+
if (newBaseAssetReserve.gt(baseAssetReserveBefore)) {
|
|
343
|
+
return [
|
|
344
|
+
newBaseAssetReserve.sub(baseAssetReserveBefore),
|
|
345
|
+
types_1.PositionDirection.SHORT,
|
|
346
|
+
];
|
|
347
|
+
}
|
|
348
|
+
else if (newBaseAssetReserve.lt(baseAssetReserveBefore)) {
|
|
349
|
+
return [
|
|
350
|
+
baseAssetReserveBefore.sub(newBaseAssetReserve),
|
|
351
|
+
types_1.PositionDirection.LONG,
|
|
352
|
+
];
|
|
353
|
+
}
|
|
354
|
+
else {
|
|
355
|
+
console.log('tradeSize Too Small');
|
|
356
|
+
return [new anchor_1.BN(0), types_1.PositionDirection.LONG];
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
exports.calculateMaxBaseAssetAmountToTrade = calculateMaxBaseAssetAmountToTrade;
|
|
360
|
+
function calculateQuoteAssetAmountSwapped(quoteAssetReserves, pegMultiplier, swapDirection) {
|
|
361
|
+
let quoteAssetAmount = quoteAssetReserves
|
|
362
|
+
.mul(pegMultiplier)
|
|
363
|
+
.div(numericConstants_1.AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO);
|
|
364
|
+
if (types_1.isVariant(swapDirection, 'remove')) {
|
|
365
|
+
quoteAssetAmount = quoteAssetAmount.add(numericConstants_1.ONE);
|
|
366
|
+
}
|
|
367
|
+
return quoteAssetAmount;
|
|
368
|
+
}
|
|
369
|
+
exports.calculateQuoteAssetAmountSwapped = calculateQuoteAssetAmountSwapped;
|
|
@@ -0,0 +1,42 @@
|
|
|
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
|
+
if (order.auctionDuration === 0) {
|
|
8
|
+
return true;
|
|
9
|
+
}
|
|
10
|
+
return new _1.BN(slot).sub(order.slot).gt(new _1.BN(order.auctionDuration));
|
|
11
|
+
}
|
|
12
|
+
exports.isAuctionComplete = isAuctionComplete;
|
|
13
|
+
function getAuctionPrice(order, slot) {
|
|
14
|
+
const slotsElapsed = new _1.BN(slot).sub(order.slot);
|
|
15
|
+
const deltaDenominator = new _1.BN(order.auctionDuration);
|
|
16
|
+
const deltaNumerator = _1.BN.min(slotsElapsed, deltaDenominator);
|
|
17
|
+
if (deltaDenominator.eq(_1.ZERO)) {
|
|
18
|
+
return order.auctionEndPrice;
|
|
19
|
+
}
|
|
20
|
+
let priceDelta;
|
|
21
|
+
if (types_1.isVariant(order.direction, 'long')) {
|
|
22
|
+
priceDelta = order.auctionEndPrice
|
|
23
|
+
.sub(order.auctionStartPrice)
|
|
24
|
+
.mul(deltaNumerator)
|
|
25
|
+
.div(deltaDenominator);
|
|
26
|
+
}
|
|
27
|
+
else {
|
|
28
|
+
priceDelta = order.auctionStartPrice
|
|
29
|
+
.sub(order.auctionEndPrice)
|
|
30
|
+
.mul(deltaNumerator)
|
|
31
|
+
.div(deltaDenominator);
|
|
32
|
+
}
|
|
33
|
+
let price;
|
|
34
|
+
if (types_1.isVariant(order.direction, 'long')) {
|
|
35
|
+
price = order.auctionStartPrice.add(priceDelta);
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
price = order.auctionStartPrice.sub(priceDelta);
|
|
39
|
+
}
|
|
40
|
+
return price;
|
|
41
|
+
}
|
|
42
|
+
exports.getAuctionPrice = getAuctionPrice;
|
|
@@ -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 = 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) && 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 = 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;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.convertToNumber = void 0;
|
|
4
|
+
const numericConstants_1 = require("../constants/numericConstants");
|
|
5
|
+
const convertToNumber = (bigNumber, precision = numericConstants_1.MARK_PRICE_PRECISION) => {
|
|
6
|
+
if (!bigNumber)
|
|
7
|
+
return 0;
|
|
8
|
+
return (bigNumber.div(precision).toNumber() +
|
|
9
|
+
bigNumber.mod(precision).toNumber() / precision.toNumber());
|
|
10
|
+
};
|
|
11
|
+
exports.convertToNumber = convertToNumber;
|