@drift-labs/sdk 0.2.0-temp.0 → 0.2.0-temp.1
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/admin.d.ts +7 -5
- package/lib/admin.js +34 -11
- package/lib/clearingHouse.d.ts +23 -9
- package/lib/clearingHouse.js +335 -95
- package/lib/clearingHouseUser.d.ts +2 -2
- package/lib/clearingHouseUser.js +8 -17
- package/lib/config.js +1 -1
- package/lib/constants/banks.js +9 -2
- package/lib/constants/numericConstants.d.ts +1 -0
- package/lib/constants/numericConstants.js +2 -1
- package/lib/idl/clearing_house.json +689 -153
- package/lib/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
- package/lib/index.d.ts +3 -2
- package/lib/index.js +7 -2
- package/lib/math/amm.js +7 -35
- package/lib/math/auction.js +4 -1
- package/lib/math/orders.d.ts +2 -2
- package/lib/math/orders.js +19 -2
- package/lib/math/position.js +3 -1
- package/lib/math/trade.d.ts +1 -1
- package/lib/math/trade.js +7 -10
- package/lib/orderParams.d.ts +14 -5
- package/lib/orderParams.js +8 -96
- package/lib/orders.js +1 -1
- package/lib/slot/SlotSubscriber.d.ts +7 -0
- package/lib/slot/SlotSubscriber.js +3 -0
- package/lib/{mockUSDCFaucet.d.ts → tokenFaucet.d.ts} +7 -5
- package/lib/{mockUSDCFaucet.js → tokenFaucet.js} +41 -40
- package/lib/tx/utils.js +1 -1
- package/lib/types.d.ts +132 -14
- package/lib/types.js +52 -1
- package/lib/util/computeUnits.js +1 -1
- package/package.json +3 -3
- package/src/accounts/bulkAccountLoader.js +197 -0
- package/src/accounts/bulkUserSubscription.js +33 -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/admin.js +517 -0
- package/src/admin.ts +53 -14
- package/src/assert/assert.js +9 -0
- package/src/clearingHouse.ts +510 -131
- package/src/clearingHouseConfig.js +2 -0
- package/src/clearingHouseUser.ts +12 -23
- package/src/clearingHouseUserConfig.js +2 -0
- package/src/config.js +67 -0
- package/src/config.ts +1 -1
- package/src/constants/banks.js +42 -0
- package/src/constants/banks.ts +9 -2
- package/src/constants/markets.js +42 -0
- package/src/constants/numericConstants.js +41 -0
- package/src/constants/numericConstants.ts +1 -0
- 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 +390 -0
- package/src/factory/oracleClient.js +20 -0
- package/src/idl/clearing_house.json +689 -153
- package/src/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
- package/src/index.js +69 -0
- package/src/index.ts +3 -2
- package/src/math/amm.js +369 -0
- package/src/math/amm.ts +19 -49
- package/src/math/auction.js +42 -0
- package/src/math/auction.ts +5 -1
- package/src/math/conversion.js +11 -0
- package/src/math/funding.js +248 -0
- package/src/math/oracles.js +26 -0
- package/src/math/orders.ts +17 -3
- package/src/math/position.ts +5 -1
- package/src/math/repeg.js +128 -0
- package/src/math/state.js +15 -0
- package/src/math/trade.js +253 -0
- package/src/math/trade.ts +23 -25
- package/src/math/utils.js +0 -1
- package/src/mockUSDCFaucet.js +280 -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/orderParams.ts +20 -141
- package/src/orders.ts +2 -1
- package/src/slot/SlotSubscriber.js +39 -0
- package/src/slot/SlotSubscriber.ts +11 -1
- package/src/token/index.js +38 -0
- package/src/tokenFaucet.js +189 -0
- package/src/{mockUSDCFaucet.ts → tokenFaucet.ts} +48 -59
- package/src/tx/types.js +2 -0
- package/src/tx/utils.js +17 -0
- package/src/tx/utils.ts +1 -1
- package/src/types.js +125 -0
- package/src/types.ts +128 -15
- package/src/userName.js +20 -0
- package/src/util/computeUnits.js +21 -11
- package/src/util/computeUnits.ts +1 -1
- package/src/util/getTokenAddress.js +9 -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.map +0 -1
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.calculateTargetPriceTrade = exports.calculateTradeAcquiredAmounts = exports.calculateTradeSlippage = void 0;
|
|
4
|
+
const types_1 = require("../types");
|
|
5
|
+
const anchor_1 = require("@project-serum/anchor");
|
|
6
|
+
const assert_1 = require("../assert/assert");
|
|
7
|
+
const numericConstants_1 = require("../constants/numericConstants");
|
|
8
|
+
const market_1 = require("./market");
|
|
9
|
+
const amm_1 = require("./amm");
|
|
10
|
+
const utils_1 = require("./utils");
|
|
11
|
+
const types_2 = require("../types");
|
|
12
|
+
const MAXPCT = new anchor_1.BN(1000); //percentage units are [0,1000] => [0,1]
|
|
13
|
+
/**
|
|
14
|
+
* Calculates avg/max slippage (price impact) for candidate trade
|
|
15
|
+
* @param direction
|
|
16
|
+
* @param amount
|
|
17
|
+
* @param market
|
|
18
|
+
* @param inputAssetType which asset is being traded
|
|
19
|
+
* @param useSpread whether to consider spread with calculating slippage
|
|
20
|
+
* @return [pctAvgSlippage, pctMaxSlippage, entryPrice, newPrice]
|
|
21
|
+
*
|
|
22
|
+
* 'pctAvgSlippage' => the percentage change to entryPrice (average est slippage in execution) : Precision MARK_PRICE_PRECISION
|
|
23
|
+
*
|
|
24
|
+
* 'pctMaxSlippage' => the percentage change to maxPrice (highest est slippage in execution) : Precision MARK_PRICE_PRECISION
|
|
25
|
+
*
|
|
26
|
+
* 'entryPrice' => the average price of the trade : Precision MARK_PRICE_PRECISION
|
|
27
|
+
*
|
|
28
|
+
* 'newPrice' => the price of the asset after the trade : Precision MARK_PRICE_PRECISION
|
|
29
|
+
*/
|
|
30
|
+
function calculateTradeSlippage(direction, amount, market, inputAssetType = 'quote', oraclePriceData, useSpread = true) {
|
|
31
|
+
let oldPrice;
|
|
32
|
+
if (useSpread && market.amm.baseSpread > 0) {
|
|
33
|
+
if (types_2.isVariant(direction, 'long')) {
|
|
34
|
+
oldPrice = market_1.calculateAskPrice(market, oraclePriceData);
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
oldPrice = market_1.calculateBidPrice(market, oraclePriceData);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
else {
|
|
41
|
+
oldPrice = market_1.calculateMarkPrice(market, oraclePriceData);
|
|
42
|
+
}
|
|
43
|
+
if (amount.eq(numericConstants_1.ZERO)) {
|
|
44
|
+
return [numericConstants_1.ZERO, numericConstants_1.ZERO, oldPrice, oldPrice];
|
|
45
|
+
}
|
|
46
|
+
const [acquiredBaseReserve, acquiredQuoteReserve, acquiredQuoteAssetAmount] = calculateTradeAcquiredAmounts(direction, amount, market, inputAssetType, oraclePriceData, useSpread);
|
|
47
|
+
const entryPrice = acquiredQuoteAssetAmount
|
|
48
|
+
.mul(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
|
|
49
|
+
.mul(numericConstants_1.MARK_PRICE_PRECISION)
|
|
50
|
+
.div(acquiredBaseReserve.abs());
|
|
51
|
+
let amm;
|
|
52
|
+
if (useSpread && market.amm.baseSpread > 0) {
|
|
53
|
+
const { baseAssetReserve, quoteAssetReserve, sqrtK, newPeg } = amm_1.calculateUpdatedAMMSpreadReserves(market.amm, direction, oraclePriceData);
|
|
54
|
+
amm = {
|
|
55
|
+
baseAssetReserve,
|
|
56
|
+
quoteAssetReserve,
|
|
57
|
+
sqrtK: sqrtK,
|
|
58
|
+
pegMultiplier: newPeg,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
else {
|
|
62
|
+
amm = market.amm;
|
|
63
|
+
}
|
|
64
|
+
const newPrice = amm_1.calculatePrice(amm.baseAssetReserve.sub(acquiredBaseReserve), amm.quoteAssetReserve.sub(acquiredQuoteReserve), amm.pegMultiplier);
|
|
65
|
+
if (direction == types_1.PositionDirection.SHORT) {
|
|
66
|
+
assert_1.assert(newPrice.lte(oldPrice));
|
|
67
|
+
}
|
|
68
|
+
else {
|
|
69
|
+
assert_1.assert(oldPrice.lte(newPrice));
|
|
70
|
+
}
|
|
71
|
+
const pctMaxSlippage = newPrice
|
|
72
|
+
.sub(oldPrice)
|
|
73
|
+
.mul(numericConstants_1.MARK_PRICE_PRECISION)
|
|
74
|
+
.div(oldPrice)
|
|
75
|
+
.abs();
|
|
76
|
+
const pctAvgSlippage = entryPrice
|
|
77
|
+
.sub(oldPrice)
|
|
78
|
+
.mul(numericConstants_1.MARK_PRICE_PRECISION)
|
|
79
|
+
.div(oldPrice)
|
|
80
|
+
.abs();
|
|
81
|
+
return [pctAvgSlippage, pctMaxSlippage, entryPrice, newPrice];
|
|
82
|
+
}
|
|
83
|
+
exports.calculateTradeSlippage = calculateTradeSlippage;
|
|
84
|
+
/**
|
|
85
|
+
* Calculates acquired amounts for trade executed
|
|
86
|
+
* @param direction
|
|
87
|
+
* @param amount
|
|
88
|
+
* @param market
|
|
89
|
+
* @param inputAssetType
|
|
90
|
+
* @param useSpread
|
|
91
|
+
* @return
|
|
92
|
+
* | 'acquiredBase' => positive/negative change in user's base : BN AMM_RESERVE_PRECISION
|
|
93
|
+
* | 'acquiredQuote' => positive/negative change in user's quote : BN TODO-PRECISION
|
|
94
|
+
*/
|
|
95
|
+
function calculateTradeAcquiredAmounts(direction, amount, market, inputAssetType = 'quote', oraclePriceData, useSpread = true) {
|
|
96
|
+
if (amount.eq(numericConstants_1.ZERO)) {
|
|
97
|
+
return [numericConstants_1.ZERO, numericConstants_1.ZERO, numericConstants_1.ZERO];
|
|
98
|
+
}
|
|
99
|
+
const swapDirection = amm_1.getSwapDirection(inputAssetType, direction);
|
|
100
|
+
let amm;
|
|
101
|
+
if (useSpread && market.amm.baseSpread > 0) {
|
|
102
|
+
const { baseAssetReserve, quoteAssetReserve, sqrtK, newPeg } = amm_1.calculateUpdatedAMMSpreadReserves(market.amm, direction, oraclePriceData);
|
|
103
|
+
amm = {
|
|
104
|
+
baseAssetReserve,
|
|
105
|
+
quoteAssetReserve,
|
|
106
|
+
sqrtK: sqrtK,
|
|
107
|
+
pegMultiplier: newPeg,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
else {
|
|
111
|
+
amm = market.amm;
|
|
112
|
+
}
|
|
113
|
+
const [newQuoteAssetReserve, newBaseAssetReserve] = amm_1.calculateAmmReservesAfterSwap(amm, inputAssetType, amount, swapDirection);
|
|
114
|
+
const acquiredBase = amm.baseAssetReserve.sub(newBaseAssetReserve);
|
|
115
|
+
const acquiredQuote = amm.quoteAssetReserve.sub(newQuoteAssetReserve);
|
|
116
|
+
const acquiredQuoteAssetamount = amm_1.calculateQuoteAssetAmountSwapped(acquiredQuote.abs(), amm.pegMultiplier, swapDirection);
|
|
117
|
+
return [acquiredBase, acquiredQuote, acquiredQuoteAssetamount];
|
|
118
|
+
}
|
|
119
|
+
exports.calculateTradeAcquiredAmounts = calculateTradeAcquiredAmounts;
|
|
120
|
+
/**
|
|
121
|
+
* calculateTargetPriceTrade
|
|
122
|
+
* simple function for finding arbitraging trades
|
|
123
|
+
* @param market
|
|
124
|
+
* @param targetPrice
|
|
125
|
+
* @param pct optional default is 100% gap filling, can set smaller.
|
|
126
|
+
* @param outputAssetType which asset to trade.
|
|
127
|
+
* @param useSpread whether or not to consider the spread when calculating the trade size
|
|
128
|
+
* @returns trade direction/size in order to push price to a targetPrice,
|
|
129
|
+
*
|
|
130
|
+
* [
|
|
131
|
+
* direction => direction of trade required, PositionDirection
|
|
132
|
+
* tradeSize => size of trade required, TODO-PRECISION
|
|
133
|
+
* entryPrice => the entry price for the trade, MARK_PRICE_PRECISION
|
|
134
|
+
* targetPrice => the target price MARK_PRICE_PRECISION
|
|
135
|
+
* ]
|
|
136
|
+
*/
|
|
137
|
+
function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAssetType = 'quote', oraclePriceData, useSpread = true) {
|
|
138
|
+
assert_1.assert(market.amm.baseAssetReserve.gt(numericConstants_1.ZERO));
|
|
139
|
+
assert_1.assert(targetPrice.gt(numericConstants_1.ZERO));
|
|
140
|
+
assert_1.assert(pct.lte(MAXPCT) && pct.gt(numericConstants_1.ZERO));
|
|
141
|
+
const markPriceBefore = market_1.calculateMarkPrice(market, oraclePriceData);
|
|
142
|
+
const bidPriceBefore = market_1.calculateBidPrice(market, oraclePriceData);
|
|
143
|
+
const askPriceBefore = market_1.calculateAskPrice(market, oraclePriceData);
|
|
144
|
+
let direction;
|
|
145
|
+
if (targetPrice.gt(markPriceBefore)) {
|
|
146
|
+
const priceGap = targetPrice.sub(markPriceBefore);
|
|
147
|
+
const priceGapScaled = priceGap.mul(pct).div(MAXPCT);
|
|
148
|
+
targetPrice = markPriceBefore.add(priceGapScaled);
|
|
149
|
+
direction = types_1.PositionDirection.LONG;
|
|
150
|
+
}
|
|
151
|
+
else {
|
|
152
|
+
const priceGap = markPriceBefore.sub(targetPrice);
|
|
153
|
+
const priceGapScaled = priceGap.mul(pct).div(MAXPCT);
|
|
154
|
+
targetPrice = markPriceBefore.sub(priceGapScaled);
|
|
155
|
+
direction = types_1.PositionDirection.SHORT;
|
|
156
|
+
}
|
|
157
|
+
let tradeSize;
|
|
158
|
+
let baseSize;
|
|
159
|
+
let baseAssetReserveBefore;
|
|
160
|
+
let quoteAssetReserveBefore;
|
|
161
|
+
let peg = market.amm.pegMultiplier;
|
|
162
|
+
if (useSpread && market.amm.baseSpread > 0) {
|
|
163
|
+
const { baseAssetReserve, quoteAssetReserve, newPeg } = amm_1.calculateUpdatedAMMSpreadReserves(market.amm, direction, oraclePriceData);
|
|
164
|
+
baseAssetReserveBefore = baseAssetReserve;
|
|
165
|
+
quoteAssetReserveBefore = quoteAssetReserve;
|
|
166
|
+
peg = newPeg;
|
|
167
|
+
}
|
|
168
|
+
else {
|
|
169
|
+
baseAssetReserveBefore = market.amm.baseAssetReserve;
|
|
170
|
+
quoteAssetReserveBefore = market.amm.quoteAssetReserve;
|
|
171
|
+
}
|
|
172
|
+
const invariant = market.amm.sqrtK.mul(market.amm.sqrtK);
|
|
173
|
+
const k = invariant.mul(numericConstants_1.MARK_PRICE_PRECISION);
|
|
174
|
+
let baseAssetReserveAfter;
|
|
175
|
+
let quoteAssetReserveAfter;
|
|
176
|
+
const biasModifier = new anchor_1.BN(1);
|
|
177
|
+
let markPriceAfter;
|
|
178
|
+
if (useSpread &&
|
|
179
|
+
targetPrice.lt(askPriceBefore) &&
|
|
180
|
+
targetPrice.gt(bidPriceBefore)) {
|
|
181
|
+
// no trade, market is at target
|
|
182
|
+
if (markPriceBefore.gt(targetPrice)) {
|
|
183
|
+
direction = types_1.PositionDirection.SHORT;
|
|
184
|
+
}
|
|
185
|
+
else {
|
|
186
|
+
direction = types_1.PositionDirection.LONG;
|
|
187
|
+
}
|
|
188
|
+
tradeSize = numericConstants_1.ZERO;
|
|
189
|
+
return [direction, tradeSize, targetPrice, targetPrice];
|
|
190
|
+
}
|
|
191
|
+
else if (markPriceBefore.gt(targetPrice)) {
|
|
192
|
+
// overestimate y2
|
|
193
|
+
baseAssetReserveAfter = utils_1.squareRootBN(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).sub(biasModifier)).sub(new anchor_1.BN(1));
|
|
194
|
+
quoteAssetReserveAfter = k
|
|
195
|
+
.div(numericConstants_1.MARK_PRICE_PRECISION)
|
|
196
|
+
.div(baseAssetReserveAfter);
|
|
197
|
+
markPriceAfter = amm_1.calculatePrice(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
|
|
198
|
+
direction = types_1.PositionDirection.SHORT;
|
|
199
|
+
tradeSize = quoteAssetReserveBefore
|
|
200
|
+
.sub(quoteAssetReserveAfter)
|
|
201
|
+
.mul(peg)
|
|
202
|
+
.div(numericConstants_1.PEG_PRECISION)
|
|
203
|
+
.div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO);
|
|
204
|
+
baseSize = baseAssetReserveAfter.sub(baseAssetReserveBefore);
|
|
205
|
+
}
|
|
206
|
+
else if (markPriceBefore.lt(targetPrice)) {
|
|
207
|
+
// underestimate y2
|
|
208
|
+
baseAssetReserveAfter = utils_1.squareRootBN(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).add(biasModifier)).add(new anchor_1.BN(1));
|
|
209
|
+
quoteAssetReserveAfter = k
|
|
210
|
+
.div(numericConstants_1.MARK_PRICE_PRECISION)
|
|
211
|
+
.div(baseAssetReserveAfter);
|
|
212
|
+
markPriceAfter = amm_1.calculatePrice(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
|
|
213
|
+
direction = types_1.PositionDirection.LONG;
|
|
214
|
+
tradeSize = quoteAssetReserveAfter
|
|
215
|
+
.sub(quoteAssetReserveBefore)
|
|
216
|
+
.mul(peg)
|
|
217
|
+
.div(numericConstants_1.PEG_PRECISION)
|
|
218
|
+
.div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO);
|
|
219
|
+
baseSize = baseAssetReserveBefore.sub(baseAssetReserveAfter);
|
|
220
|
+
}
|
|
221
|
+
else {
|
|
222
|
+
// no trade, market is at target
|
|
223
|
+
direction = types_1.PositionDirection.LONG;
|
|
224
|
+
tradeSize = numericConstants_1.ZERO;
|
|
225
|
+
return [direction, tradeSize, targetPrice, targetPrice];
|
|
226
|
+
}
|
|
227
|
+
let tp1 = targetPrice;
|
|
228
|
+
let tp2 = markPriceAfter;
|
|
229
|
+
let originalDiff = targetPrice.sub(markPriceBefore);
|
|
230
|
+
if (direction == types_1.PositionDirection.SHORT) {
|
|
231
|
+
tp1 = markPriceAfter;
|
|
232
|
+
tp2 = targetPrice;
|
|
233
|
+
originalDiff = markPriceBefore.sub(targetPrice);
|
|
234
|
+
}
|
|
235
|
+
const entryPrice = tradeSize
|
|
236
|
+
.mul(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
|
|
237
|
+
.mul(numericConstants_1.MARK_PRICE_PRECISION)
|
|
238
|
+
.div(baseSize.abs());
|
|
239
|
+
assert_1.assert(tp1.sub(tp2).lte(originalDiff), 'Target Price Calculation incorrect');
|
|
240
|
+
assert_1.assert(tp2.lte(tp1) || tp2.sub(tp1).abs() < 100000, 'Target Price Calculation incorrect' +
|
|
241
|
+
tp2.toString() +
|
|
242
|
+
'>=' +
|
|
243
|
+
tp1.toString() +
|
|
244
|
+
'err: ' +
|
|
245
|
+
tp2.sub(tp1).abs().toString());
|
|
246
|
+
if (outputAssetType == 'quote') {
|
|
247
|
+
return [direction, tradeSize, entryPrice, targetPrice];
|
|
248
|
+
}
|
|
249
|
+
else {
|
|
250
|
+
return [direction, baseSize, entryPrice, targetPrice];
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
exports.calculateTargetPriceTrade = calculateTargetPriceTrade;
|
package/src/math/trade.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { MarketAccount, PositionDirection
|
|
1
|
+
import { MarketAccount, PositionDirection } from '../types';
|
|
2
2
|
import { BN } from '@project-serum/anchor';
|
|
3
3
|
import { assert } from '../assert/assert';
|
|
4
4
|
import {
|
|
@@ -78,28 +78,20 @@ export function calculateTradeSlippage(
|
|
|
78
78
|
if (amount.eq(ZERO)) {
|
|
79
79
|
return [ZERO, ZERO, oldPrice, oldPrice];
|
|
80
80
|
}
|
|
81
|
-
const [
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
const swapDirection = isVariant(direction, 'long')
|
|
91
|
-
? SwapDirection.REMOVE
|
|
92
|
-
: SwapDirection.ADD;
|
|
93
|
-
const quoteAssetAmountAcquired = calculateQuoteAssetAmountSwapped(
|
|
94
|
-
acquiredQuote.abs(),
|
|
95
|
-
market.amm.pegMultiplier,
|
|
96
|
-
swapDirection
|
|
97
|
-
);
|
|
81
|
+
const [acquiredBaseReserve, acquiredQuoteReserve, acquiredQuoteAssetAmount] =
|
|
82
|
+
calculateTradeAcquiredAmounts(
|
|
83
|
+
direction,
|
|
84
|
+
amount,
|
|
85
|
+
market,
|
|
86
|
+
inputAssetType,
|
|
87
|
+
oraclePriceData,
|
|
88
|
+
useSpread
|
|
89
|
+
);
|
|
98
90
|
|
|
99
|
-
const entryPrice =
|
|
91
|
+
const entryPrice = acquiredQuoteAssetAmount
|
|
100
92
|
.mul(AMM_TO_QUOTE_PRECISION_RATIO)
|
|
101
93
|
.mul(MARK_PRICE_PRECISION)
|
|
102
|
-
.div(
|
|
94
|
+
.div(acquiredBaseReserve.abs());
|
|
103
95
|
|
|
104
96
|
let amm: Parameters<typeof calculateAmmReservesAfterSwap>[0];
|
|
105
97
|
if (useSpread && market.amm.baseSpread > 0) {
|
|
@@ -116,8 +108,8 @@ export function calculateTradeSlippage(
|
|
|
116
108
|
}
|
|
117
109
|
|
|
118
110
|
const newPrice = calculatePrice(
|
|
119
|
-
amm.baseAssetReserve.sub(
|
|
120
|
-
amm.quoteAssetReserve.sub(
|
|
111
|
+
amm.baseAssetReserve.sub(acquiredBaseReserve),
|
|
112
|
+
amm.quoteAssetReserve.sub(acquiredQuoteReserve),
|
|
121
113
|
amm.pegMultiplier
|
|
122
114
|
);
|
|
123
115
|
|
|
@@ -159,9 +151,9 @@ export function calculateTradeAcquiredAmounts(
|
|
|
159
151
|
inputAssetType: AssetType = 'quote',
|
|
160
152
|
oraclePriceData: OraclePriceData,
|
|
161
153
|
useSpread = true
|
|
162
|
-
): [BN, BN] {
|
|
154
|
+
): [BN, BN, BN] {
|
|
163
155
|
if (amount.eq(ZERO)) {
|
|
164
|
-
return [ZERO, ZERO];
|
|
156
|
+
return [ZERO, ZERO, ZERO];
|
|
165
157
|
}
|
|
166
158
|
|
|
167
159
|
const swapDirection = getSwapDirection(inputAssetType, direction);
|
|
@@ -185,7 +177,13 @@ export function calculateTradeAcquiredAmounts(
|
|
|
185
177
|
|
|
186
178
|
const acquiredBase = amm.baseAssetReserve.sub(newBaseAssetReserve);
|
|
187
179
|
const acquiredQuote = amm.quoteAssetReserve.sub(newQuoteAssetReserve);
|
|
188
|
-
|
|
180
|
+
const acquiredQuoteAssetamount = calculateQuoteAssetAmountSwapped(
|
|
181
|
+
acquiredQuote.abs(),
|
|
182
|
+
amm.pegMultiplier,
|
|
183
|
+
swapDirection
|
|
184
|
+
);
|
|
185
|
+
|
|
186
|
+
return [acquiredBase, acquiredQuote, acquiredQuoteAssetamount];
|
|
189
187
|
}
|
|
190
188
|
|
|
191
189
|
/**
|
package/src/math/utils.js
CHANGED
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
var __createBinding =
|
|
3
|
+
(this && this.__createBinding) ||
|
|
4
|
+
(Object.create
|
|
5
|
+
? function (o, m, k, k2) {
|
|
6
|
+
if (k2 === undefined) k2 = k;
|
|
7
|
+
Object.defineProperty(o, k2, {
|
|
8
|
+
enumerable: true,
|
|
9
|
+
get: function () {
|
|
10
|
+
return m[k];
|
|
11
|
+
},
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
: function (o, m, k, k2) {
|
|
15
|
+
if (k2 === undefined) k2 = k;
|
|
16
|
+
o[k2] = m[k];
|
|
17
|
+
});
|
|
18
|
+
var __setModuleDefault =
|
|
19
|
+
(this && this.__setModuleDefault) ||
|
|
20
|
+
(Object.create
|
|
21
|
+
? function (o, v) {
|
|
22
|
+
Object.defineProperty(o, 'default', { enumerable: true, value: v });
|
|
23
|
+
}
|
|
24
|
+
: function (o, v) {
|
|
25
|
+
o['default'] = v;
|
|
26
|
+
});
|
|
27
|
+
var __importStar =
|
|
28
|
+
(this && this.__importStar) ||
|
|
29
|
+
function (mod) {
|
|
30
|
+
if (mod && mod.__esModule) return mod;
|
|
31
|
+
var result = {};
|
|
32
|
+
if (mod != null)
|
|
33
|
+
for (var k in mod)
|
|
34
|
+
if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k))
|
|
35
|
+
__createBinding(result, mod, k);
|
|
36
|
+
__setModuleDefault(result, mod);
|
|
37
|
+
return result;
|
|
38
|
+
};
|
|
39
|
+
var __awaiter =
|
|
40
|
+
(this && this.__awaiter) ||
|
|
41
|
+
function (thisArg, _arguments, P, generator) {
|
|
42
|
+
function adopt(value) {
|
|
43
|
+
return value instanceof P
|
|
44
|
+
? value
|
|
45
|
+
: new P(function (resolve) {
|
|
46
|
+
resolve(value);
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
50
|
+
function fulfilled(value) {
|
|
51
|
+
try {
|
|
52
|
+
step(generator.next(value));
|
|
53
|
+
} catch (e) {
|
|
54
|
+
reject(e);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function rejected(value) {
|
|
58
|
+
try {
|
|
59
|
+
step(generator['throw'](value));
|
|
60
|
+
} catch (e) {
|
|
61
|
+
reject(e);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
function step(result) {
|
|
65
|
+
result.done
|
|
66
|
+
? resolve(result.value)
|
|
67
|
+
: adopt(result.value).then(fulfilled, rejected);
|
|
68
|
+
}
|
|
69
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
70
|
+
});
|
|
71
|
+
};
|
|
72
|
+
var __importDefault =
|
|
73
|
+
(this && this.__importDefault) ||
|
|
74
|
+
function (mod) {
|
|
75
|
+
return mod && mod.__esModule ? mod : { default: mod };
|
|
76
|
+
};
|
|
77
|
+
Object.defineProperty(exports, '__esModule', { value: true });
|
|
78
|
+
exports.MockUSDCFaucet = void 0;
|
|
79
|
+
const anchor = __importStar(require('@project-serum/anchor'));
|
|
80
|
+
const anchor_1 = require('@project-serum/anchor');
|
|
81
|
+
const spl_token_1 = require('@solana/spl-token');
|
|
82
|
+
const web3_js_1 = require('@solana/web3.js');
|
|
83
|
+
const mock_usdc_faucet_json_1 = __importDefault(
|
|
84
|
+
require('./idl/token_faucet.json')
|
|
85
|
+
);
|
|
86
|
+
class MockUSDCFaucet {
|
|
87
|
+
constructor(connection, wallet, programId, opts) {
|
|
88
|
+
this.connection = connection;
|
|
89
|
+
this.wallet = wallet;
|
|
90
|
+
this.opts = opts || anchor_1.AnchorProvider.defaultOptions();
|
|
91
|
+
const provider = new anchor_1.AnchorProvider(connection, wallet, this.opts);
|
|
92
|
+
this.provider = provider;
|
|
93
|
+
this.program = new anchor_1.Program(
|
|
94
|
+
mock_usdc_faucet_json_1.default,
|
|
95
|
+
programId,
|
|
96
|
+
provider
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
getMockUSDCFaucetStatePublicKeyAndNonce() {
|
|
100
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
101
|
+
return anchor.web3.PublicKey.findProgramAddress(
|
|
102
|
+
[Buffer.from(anchor.utils.bytes.utf8.encode('mock_usdc_faucet'))],
|
|
103
|
+
this.program.programId
|
|
104
|
+
);
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
getMockUSDCFaucetStatePublicKey() {
|
|
108
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
109
|
+
if (this.mockUSDCFaucetStatePublicKey) {
|
|
110
|
+
return this.mockUSDCFaucetStatePublicKey;
|
|
111
|
+
}
|
|
112
|
+
this.mockUSDCFaucetStatePublicKey =
|
|
113
|
+
(yield this.getMockUSDCFaucetStatePublicKeyAndNonce())[0];
|
|
114
|
+
return this.mockUSDCFaucetStatePublicKey;
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
initialize() {
|
|
118
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
119
|
+
const stateAccountRPCResponse =
|
|
120
|
+
yield this.connection.getParsedAccountInfo(
|
|
121
|
+
yield this.getMockUSDCFaucetStatePublicKey()
|
|
122
|
+
);
|
|
123
|
+
if (stateAccountRPCResponse.value !== null) {
|
|
124
|
+
throw new Error('Faucet already initialized');
|
|
125
|
+
}
|
|
126
|
+
const fakeUSDCMint = anchor.web3.Keypair.generate();
|
|
127
|
+
const createUSDCMintAccountIx = web3_js_1.SystemProgram.createAccount({
|
|
128
|
+
fromPubkey: this.wallet.publicKey,
|
|
129
|
+
newAccountPubkey: fakeUSDCMint.publicKey,
|
|
130
|
+
lamports: yield spl_token_1.Token.getMinBalanceRentForExemptMint(
|
|
131
|
+
this.connection
|
|
132
|
+
),
|
|
133
|
+
space: spl_token_1.MintLayout.span,
|
|
134
|
+
programId: spl_token_1.TOKEN_PROGRAM_ID,
|
|
135
|
+
});
|
|
136
|
+
const [mintAuthority, _mintAuthorityNonce] =
|
|
137
|
+
yield web3_js_1.PublicKey.findProgramAddress(
|
|
138
|
+
[fakeUSDCMint.publicKey.toBuffer()],
|
|
139
|
+
this.program.programId
|
|
140
|
+
);
|
|
141
|
+
const initUSDCMintIx = spl_token_1.Token.createInitMintInstruction(
|
|
142
|
+
spl_token_1.TOKEN_PROGRAM_ID,
|
|
143
|
+
fakeUSDCMint.publicKey,
|
|
144
|
+
6,
|
|
145
|
+
mintAuthority,
|
|
146
|
+
null
|
|
147
|
+
);
|
|
148
|
+
const [mockUSDCFaucetStatePublicKey, mockUSDCFaucetStateNonce] =
|
|
149
|
+
yield this.getMockUSDCFaucetStatePublicKeyAndNonce();
|
|
150
|
+
return yield this.program.rpc.initialize(mockUSDCFaucetStateNonce, {
|
|
151
|
+
accounts: {
|
|
152
|
+
mockUsdcFaucetState: mockUSDCFaucetStatePublicKey,
|
|
153
|
+
admin: this.wallet.publicKey,
|
|
154
|
+
mintAccount: fakeUSDCMint.publicKey,
|
|
155
|
+
rent: web3_js_1.SYSVAR_RENT_PUBKEY,
|
|
156
|
+
systemProgram: anchor.web3.SystemProgram.programId,
|
|
157
|
+
},
|
|
158
|
+
instructions: [createUSDCMintAccountIx, initUSDCMintIx],
|
|
159
|
+
signers: [fakeUSDCMint],
|
|
160
|
+
});
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
fetchState() {
|
|
164
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
165
|
+
return yield this.program.account.mockUsdcFaucetState.fetch(
|
|
166
|
+
yield this.getMockUSDCFaucetStatePublicKey()
|
|
167
|
+
);
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
mintToUser(userTokenAccount, amount) {
|
|
171
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
172
|
+
const state = yield this.fetchState();
|
|
173
|
+
return yield this.program.rpc.mintToUser(amount, {
|
|
174
|
+
accounts: {
|
|
175
|
+
mockUsdcFaucetState: yield this.getMockUSDCFaucetStatePublicKey(),
|
|
176
|
+
mintAccount: state.mint,
|
|
177
|
+
userTokenAccount,
|
|
178
|
+
mintAuthority: state.mintAuthority,
|
|
179
|
+
tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
|
|
180
|
+
},
|
|
181
|
+
});
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
createAssociatedTokenAccountAndMintTo(userPublicKey, amount) {
|
|
185
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
186
|
+
const [associatedTokenPublicKey, createAssociatedAccountIx, mintToTx] =
|
|
187
|
+
yield this.createAssociatedTokenAccountAndMintToInstructions(
|
|
188
|
+
userPublicKey,
|
|
189
|
+
amount
|
|
190
|
+
);
|
|
191
|
+
const tx = new web3_js_1.Transaction()
|
|
192
|
+
.add(createAssociatedAccountIx)
|
|
193
|
+
.add(mintToTx);
|
|
194
|
+
const txSig = yield this.program.provider.sendAndConfirm(
|
|
195
|
+
tx,
|
|
196
|
+
[],
|
|
197
|
+
this.opts
|
|
198
|
+
);
|
|
199
|
+
return [associatedTokenPublicKey, txSig];
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
createAssociatedTokenAccountAndMintToInstructions(userPublicKey, amount) {
|
|
203
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
204
|
+
const state = yield this.fetchState();
|
|
205
|
+
const associateTokenPublicKey =
|
|
206
|
+
yield this.getAssosciatedMockUSDMintAddress({
|
|
207
|
+
userPubKey: userPublicKey,
|
|
208
|
+
});
|
|
209
|
+
const createAssociatedAccountIx =
|
|
210
|
+
spl_token_1.Token.createAssociatedTokenAccountInstruction(
|
|
211
|
+
spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID,
|
|
212
|
+
spl_token_1.TOKEN_PROGRAM_ID,
|
|
213
|
+
state.mint,
|
|
214
|
+
associateTokenPublicKey,
|
|
215
|
+
userPublicKey,
|
|
216
|
+
this.wallet.publicKey
|
|
217
|
+
);
|
|
218
|
+
const mintToIx = yield this.program.instruction.mintToUser(amount, {
|
|
219
|
+
accounts: {
|
|
220
|
+
mockUsdcFaucetState: yield this.getMockUSDCFaucetStatePublicKey(),
|
|
221
|
+
mintAccount: state.mint,
|
|
222
|
+
userTokenAccount: associateTokenPublicKey,
|
|
223
|
+
mintAuthority: state.mintAuthority,
|
|
224
|
+
tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
|
|
225
|
+
},
|
|
226
|
+
});
|
|
227
|
+
return [associateTokenPublicKey, createAssociatedAccountIx, mintToIx];
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
getAssosciatedMockUSDMintAddress(props) {
|
|
231
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
232
|
+
const state = yield this.fetchState();
|
|
233
|
+
return spl_token_1.Token.getAssociatedTokenAddress(
|
|
234
|
+
spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID,
|
|
235
|
+
spl_token_1.TOKEN_PROGRAM_ID,
|
|
236
|
+
state.mint,
|
|
237
|
+
props.userPubKey
|
|
238
|
+
);
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
getTokenAccountInfo(props) {
|
|
242
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
243
|
+
const assosciatedKey = yield this.getAssosciatedMockUSDMintAddress(props);
|
|
244
|
+
const state = yield this.fetchState();
|
|
245
|
+
const token = new spl_token_1.Token(
|
|
246
|
+
this.connection,
|
|
247
|
+
state.mint,
|
|
248
|
+
spl_token_1.TOKEN_PROGRAM_ID,
|
|
249
|
+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
250
|
+
// @ts-ignore
|
|
251
|
+
this.provider.payer
|
|
252
|
+
);
|
|
253
|
+
return yield token.getAccountInfo(assosciatedKey);
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
subscribeToTokenAccount(props) {
|
|
257
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
258
|
+
try {
|
|
259
|
+
const tokenAccountKey = yield this.getAssosciatedMockUSDMintAddress(
|
|
260
|
+
props
|
|
261
|
+
);
|
|
262
|
+
props.callback(yield this.getTokenAccountInfo(props));
|
|
263
|
+
// Couldn't find a way to do it using anchor framework subscription, someone on serum discord recommended this way
|
|
264
|
+
this.connection.onAccountChange(
|
|
265
|
+
tokenAccountKey,
|
|
266
|
+
(
|
|
267
|
+
_accountInfo /* accountInfo is a buffer which we don't know how to deserialize */
|
|
268
|
+
) =>
|
|
269
|
+
__awaiter(this, void 0, void 0, function* () {
|
|
270
|
+
props.callback(yield this.getTokenAccountInfo(props));
|
|
271
|
+
})
|
|
272
|
+
);
|
|
273
|
+
return true;
|
|
274
|
+
} catch (e) {
|
|
275
|
+
return false;
|
|
276
|
+
}
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
exports.MockUSDCFaucet = MockUSDCFaucet;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.OracleClientCache = void 0;
|
|
4
|
+
const oracleClient_1 = require("../factory/oracleClient");
|
|
5
|
+
class OracleClientCache {
|
|
6
|
+
constructor() {
|
|
7
|
+
this.cache = new Map();
|
|
8
|
+
}
|
|
9
|
+
get(oracleSource, connection) {
|
|
10
|
+
const key = Object.keys(oracleSource)[0];
|
|
11
|
+
if (this.cache.has(key)) {
|
|
12
|
+
return this.cache.get(key);
|
|
13
|
+
}
|
|
14
|
+
const client = oracleClient_1.getOracleClient(oracleSource, connection);
|
|
15
|
+
this.cache.set(key, client);
|
|
16
|
+
return client;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
exports.OracleClientCache = OracleClientCache;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
+
});
|
|
10
|
+
};
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.convertPythPrice = exports.PythClient = void 0;
|
|
13
|
+
const client_1 = require("@pythnetwork/client");
|
|
14
|
+
const anchor_1 = require("@project-serum/anchor");
|
|
15
|
+
const numericConstants_1 = require("../constants/numericConstants");
|
|
16
|
+
class PythClient {
|
|
17
|
+
constructor(connection) {
|
|
18
|
+
this.connection = connection;
|
|
19
|
+
}
|
|
20
|
+
getOraclePriceData(pricePublicKey) {
|
|
21
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
22
|
+
const accountInfo = yield this.connection.getAccountInfo(pricePublicKey);
|
|
23
|
+
return this.getOraclePriceDataFromBuffer(accountInfo.data);
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
getOraclePriceDataFromBuffer(buffer) {
|
|
27
|
+
const priceData = client_1.parsePriceData(buffer);
|
|
28
|
+
return {
|
|
29
|
+
price: convertPythPrice(priceData.aggregate.price, priceData.exponent),
|
|
30
|
+
slot: new anchor_1.BN(priceData.lastSlot.toString()),
|
|
31
|
+
confidence: convertPythPrice(priceData.confidence, priceData.exponent),
|
|
32
|
+
twap: convertPythPrice(priceData.twap.value, priceData.exponent),
|
|
33
|
+
twapConfidence: convertPythPrice(priceData.twac.value, priceData.exponent),
|
|
34
|
+
hasSufficientNumberOfDataPoints: true,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
exports.PythClient = PythClient;
|
|
39
|
+
function convertPythPrice(price, exponent) {
|
|
40
|
+
exponent = Math.abs(exponent);
|
|
41
|
+
const pythPrecision = numericConstants_1.TEN.pow(new anchor_1.BN(exponent).abs());
|
|
42
|
+
return new anchor_1.BN(price * Math.pow(10, exponent))
|
|
43
|
+
.mul(numericConstants_1.MARK_PRICE_PRECISION)
|
|
44
|
+
.div(pythPrecision);
|
|
45
|
+
}
|
|
46
|
+
exports.convertPythPrice = convertPythPrice;
|