@drift-labs/sdk 0.2.0-master.0 → 0.2.0-master.11
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 +8 -5
- package/lib/admin.js +43 -11
- package/lib/clearingHouse.d.ts +28 -18
- package/lib/clearingHouse.js +366 -143
- 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 +2 -0
- package/lib/constants/numericConstants.js +3 -1
- package/lib/factory/bigNum.d.ts +8 -2
- package/lib/factory/bigNum.js +14 -6
- package/lib/idl/clearing_house.json +805 -202
- 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.d.ts +6 -1
- package/lib/math/amm.js +124 -41
- package/lib/math/auction.js +4 -1
- package/lib/math/orders.d.ts +2 -2
- package/lib/math/orders.js +18 -11
- package/lib/math/position.js +3 -1
- package/lib/math/repeg.js +1 -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.d.ts +1 -2
- package/lib/orders.js +6 -85
- 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 +137 -14
- package/lib/types.js +53 -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/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/admin.ts +66 -14
- package/src/assert/assert.js +9 -0
- package/src/clearingHouse.ts +558 -230
- package/src/clearingHouseUser.ts +12 -23
- package/src/config.ts +1 -1
- package/src/constants/banks.ts +9 -2
- package/src/constants/numericConstants.ts +2 -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 +364 -0
- package/src/factory/bigNum.ts +26 -9
- package/src/factory/oracleClient.js +20 -0
- package/src/idl/clearing_house.json +805 -202
- package/src/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
- package/src/index.js +100 -0
- package/src/index.ts +3 -2
- package/src/math/amm.js +369 -0
- package/src/math/amm.ts +207 -52
- package/src/math/auction.js +42 -0
- package/src/math/auction.ts +5 -1
- 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/orders.ts +17 -13
- package/src/math/position.js +140 -0
- package/src/math/position.ts +5 -1
- package/src/math/repeg.js +128 -0
- package/src/math/repeg.ts +2 -1
- 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.js +134 -0
- package/src/orders.ts +7 -131
- package/src/slot/SlotSubscriber.js +39 -0
- package/src/slot/SlotSubscriber.ts +11 -1
- package/src/token/index.js +38 -0
- package/src/{mockUSDCFaucet.ts → tokenFaucet.ts} +48 -59
- package/src/tx/retryTxSender.js +188 -0
- 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 +114 -0
- package/src/types.ts +132 -16
- package/src/userName.js +20 -0
- package/src/util/computeUnits.ts +1 -1
- 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/orders.js
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.calculateAmountToTradeForTriggerLimit = exports.calculateAmountToTradeForLimit = exports.calculateBaseAssetAmountMarketCanExecute = exports.calculateNewStateAfterOrder = void 0;
|
|
4
|
+
const types_1 = require("./types");
|
|
5
|
+
const _1 = require(".");
|
|
6
|
+
const market_1 = require("./math/market");
|
|
7
|
+
const numericConstants_1 = require("./constants/numericConstants");
|
|
8
|
+
const amm_1 = require("./math/amm");
|
|
9
|
+
const position_1 = require("./math/position");
|
|
10
|
+
function calculateNewStateAfterOrder(userAccount, userPosition, market, order) {
|
|
11
|
+
if (types_1.isVariant(order.status, 'init')) {
|
|
12
|
+
return null;
|
|
13
|
+
}
|
|
14
|
+
const baseAssetAmountToTrade = calculateBaseAssetAmountMarketCanExecute(market, order);
|
|
15
|
+
if (baseAssetAmountToTrade.lt(market.amm.baseAssetAmountStepSize)) {
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
const userAccountAfter = Object.assign({}, userAccount);
|
|
19
|
+
const userPositionAfter = Object.assign({}, userPosition);
|
|
20
|
+
const currentPositionDirection = position_1.positionCurrentDirection(userPosition);
|
|
21
|
+
const increasePosition = userPosition.baseAssetAmount.eq(numericConstants_1.ZERO) ||
|
|
22
|
+
isSameDirection(order.direction, currentPositionDirection);
|
|
23
|
+
if (increasePosition) {
|
|
24
|
+
const marketAfter = market_1.calculateNewMarketAfterTrade(baseAssetAmountToTrade, order.direction, market);
|
|
25
|
+
const { quoteAssetAmountSwapped, baseAssetAmountSwapped } = calculateAmountSwapped(market, marketAfter);
|
|
26
|
+
userPositionAfter.baseAssetAmount = userPositionAfter.baseAssetAmount.add(baseAssetAmountSwapped);
|
|
27
|
+
userPositionAfter.quoteAssetAmount = userPositionAfter.quoteAssetAmount.add(quoteAssetAmountSwapped);
|
|
28
|
+
return [userAccountAfter, userPositionAfter, marketAfter];
|
|
29
|
+
}
|
|
30
|
+
else {
|
|
31
|
+
const reversePosition = baseAssetAmountToTrade.gt(userPosition.baseAssetAmount.abs());
|
|
32
|
+
if (reversePosition) {
|
|
33
|
+
const intermediateMarket = market_1.calculateNewMarketAfterTrade(userPosition.baseAssetAmount, position_1.findDirectionToClose(userPosition), market);
|
|
34
|
+
const { quoteAssetAmountSwapped: baseAssetValue } = calculateAmountSwapped(market, intermediateMarket);
|
|
35
|
+
let pnl;
|
|
36
|
+
if (types_1.isVariant(currentPositionDirection, 'long')) {
|
|
37
|
+
pnl = baseAssetValue.sub(userPosition.quoteAssetAmount);
|
|
38
|
+
}
|
|
39
|
+
else {
|
|
40
|
+
pnl = userPosition.quoteAssetAmount.sub(baseAssetValue);
|
|
41
|
+
}
|
|
42
|
+
userAccountAfter.collateral = userAccountAfter.collateral.add(pnl);
|
|
43
|
+
const baseAssetAmountLeft = baseAssetAmountToTrade.sub(userPosition.baseAssetAmount.abs());
|
|
44
|
+
const marketAfter = market_1.calculateNewMarketAfterTrade(baseAssetAmountLeft, order.direction, intermediateMarket);
|
|
45
|
+
const { quoteAssetAmountSwapped, baseAssetAmountSwapped } = calculateAmountSwapped(intermediateMarket, marketAfter);
|
|
46
|
+
userPositionAfter.quoteAssetAmount = quoteAssetAmountSwapped;
|
|
47
|
+
userPositionAfter.baseAssetAmount = baseAssetAmountSwapped;
|
|
48
|
+
return [userAccountAfter, userPositionAfter, marketAfter];
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
const marketAfter = market_1.calculateNewMarketAfterTrade(baseAssetAmountToTrade, order.direction, market);
|
|
52
|
+
const { quoteAssetAmountSwapped: baseAssetValue, baseAssetAmountSwapped, } = calculateAmountSwapped(market, marketAfter);
|
|
53
|
+
const costBasisRealized = userPosition.quoteAssetAmount
|
|
54
|
+
.mul(baseAssetAmountSwapped.abs())
|
|
55
|
+
.div(userPosition.baseAssetAmount.abs());
|
|
56
|
+
let pnl;
|
|
57
|
+
if (types_1.isVariant(currentPositionDirection, 'long')) {
|
|
58
|
+
pnl = baseAssetValue.sub(costBasisRealized);
|
|
59
|
+
}
|
|
60
|
+
else {
|
|
61
|
+
pnl = costBasisRealized.sub(baseAssetValue);
|
|
62
|
+
}
|
|
63
|
+
userAccountAfter.collateral = userAccountAfter.collateral.add(pnl);
|
|
64
|
+
userPositionAfter.baseAssetAmount = userPositionAfter.baseAssetAmount.add(baseAssetAmountSwapped);
|
|
65
|
+
userPositionAfter.quoteAssetAmount =
|
|
66
|
+
userPositionAfter.quoteAssetAmount.sub(costBasisRealized);
|
|
67
|
+
return [userAccountAfter, userPositionAfter, marketAfter];
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
exports.calculateNewStateAfterOrder = calculateNewStateAfterOrder;
|
|
72
|
+
function calculateAmountSwapped(marketBefore, marketAfter) {
|
|
73
|
+
return {
|
|
74
|
+
quoteAssetAmountSwapped: marketBefore.amm.quoteAssetReserve
|
|
75
|
+
.sub(marketAfter.amm.quoteAssetReserve)
|
|
76
|
+
.abs()
|
|
77
|
+
.mul(marketBefore.amm.pegMultiplier)
|
|
78
|
+
.div(numericConstants_1.PEG_PRECISION)
|
|
79
|
+
.div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO),
|
|
80
|
+
baseAssetAmountSwapped: marketBefore.amm.baseAssetReserve.sub(marketAfter.amm.baseAssetReserve),
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
function calculateBaseAssetAmountMarketCanExecute(market, order, oraclePriceData) {
|
|
84
|
+
if (types_1.isVariant(order.orderType, 'limit')) {
|
|
85
|
+
return calculateAmountToTradeForLimit(market, order, oraclePriceData);
|
|
86
|
+
}
|
|
87
|
+
else if (types_1.isVariant(order.orderType, 'triggerLimit')) {
|
|
88
|
+
return calculateAmountToTradeForTriggerLimit(market, order);
|
|
89
|
+
}
|
|
90
|
+
else if (types_1.isVariant(order.orderType, 'market')) {
|
|
91
|
+
return numericConstants_1.ZERO;
|
|
92
|
+
}
|
|
93
|
+
else {
|
|
94
|
+
return calculateAmountToTradeForTriggerMarket(market, order);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
exports.calculateBaseAssetAmountMarketCanExecute = calculateBaseAssetAmountMarketCanExecute;
|
|
98
|
+
function calculateAmountToTradeForLimit(market, order, oraclePriceData) {
|
|
99
|
+
let limitPrice = order.price;
|
|
100
|
+
if (!order.oraclePriceOffset.eq(numericConstants_1.ZERO)) {
|
|
101
|
+
if (!oraclePriceData) {
|
|
102
|
+
throw Error('Cant calculate limit price for oracle offset oracle without OraclePriceData');
|
|
103
|
+
}
|
|
104
|
+
limitPrice = oraclePriceData.price.add(order.oraclePriceOffset);
|
|
105
|
+
}
|
|
106
|
+
const [maxAmountToTrade, direction] = amm_1.calculateMaxBaseAssetAmountToTrade(market.amm, limitPrice, order.direction);
|
|
107
|
+
const baseAssetAmount = _1.standardizeBaseAssetAmount(maxAmountToTrade, market.amm.baseAssetAmountStepSize);
|
|
108
|
+
// Check that directions are the same
|
|
109
|
+
const sameDirection = isSameDirection(direction, order.direction);
|
|
110
|
+
if (!sameDirection) {
|
|
111
|
+
return numericConstants_1.ZERO;
|
|
112
|
+
}
|
|
113
|
+
return baseAssetAmount.gt(order.baseAssetAmount)
|
|
114
|
+
? order.baseAssetAmount
|
|
115
|
+
: baseAssetAmount;
|
|
116
|
+
}
|
|
117
|
+
exports.calculateAmountToTradeForLimit = calculateAmountToTradeForLimit;
|
|
118
|
+
function calculateAmountToTradeForTriggerLimit(market, order) {
|
|
119
|
+
if (!order.triggered) {
|
|
120
|
+
return numericConstants_1.ZERO;
|
|
121
|
+
}
|
|
122
|
+
return calculateAmountToTradeForLimit(market, order);
|
|
123
|
+
}
|
|
124
|
+
exports.calculateAmountToTradeForTriggerLimit = calculateAmountToTradeForTriggerLimit;
|
|
125
|
+
function isSameDirection(firstDirection, secondDirection) {
|
|
126
|
+
return ((types_1.isVariant(firstDirection, 'long') && types_1.isVariant(secondDirection, 'long')) ||
|
|
127
|
+
(types_1.isVariant(firstDirection, 'short') && types_1.isVariant(secondDirection, 'short')));
|
|
128
|
+
}
|
|
129
|
+
function calculateAmountToTradeForTriggerMarket(market, order) {
|
|
130
|
+
if (!order.triggered) {
|
|
131
|
+
return numericConstants_1.ZERO;
|
|
132
|
+
}
|
|
133
|
+
return order.baseAssetAmount;
|
|
134
|
+
}
|
package/src/orders.ts
CHANGED
|
@@ -3,27 +3,13 @@ import {
|
|
|
3
3
|
MarketAccount,
|
|
4
4
|
Order,
|
|
5
5
|
PositionDirection,
|
|
6
|
-
SwapDirection,
|
|
7
6
|
UserAccount,
|
|
8
7
|
UserPosition,
|
|
9
8
|
} from './types';
|
|
10
|
-
import {
|
|
11
|
-
|
|
12
|
-
calculateAmmReservesAfterSwap,
|
|
13
|
-
calculateBaseAssetValue,
|
|
14
|
-
calculateSpreadReserves,
|
|
15
|
-
ClearingHouseUser,
|
|
16
|
-
isOrderRiskIncreasingInSameDirection,
|
|
17
|
-
standardizeBaseAssetAmount,
|
|
18
|
-
TEN_THOUSAND,
|
|
19
|
-
} from '.';
|
|
20
|
-
import {
|
|
21
|
-
calculateMarkPrice,
|
|
22
|
-
calculateNewMarketAfterTrade,
|
|
23
|
-
} from './math/market';
|
|
9
|
+
import { BN, standardizeBaseAssetAmount } from '.';
|
|
10
|
+
import { calculateNewMarketAfterTrade } from './math/market';
|
|
24
11
|
import {
|
|
25
12
|
AMM_TO_QUOTE_PRECISION_RATIO,
|
|
26
|
-
TWO,
|
|
27
13
|
PEG_PRECISION,
|
|
28
14
|
ZERO,
|
|
29
15
|
} from './constants/numericConstants';
|
|
@@ -182,7 +168,6 @@ export function calculateBaseAssetAmountMarketCanExecute(
|
|
|
182
168
|
} else if (isVariant(order.orderType, 'triggerLimit')) {
|
|
183
169
|
return calculateAmountToTradeForTriggerLimit(market, order);
|
|
184
170
|
} else if (isVariant(order.orderType, 'market')) {
|
|
185
|
-
// should never be a market order queued
|
|
186
171
|
return ZERO;
|
|
187
172
|
} else {
|
|
188
173
|
return calculateAmountToTradeForTriggerMarket(market, order);
|
|
@@ -201,14 +186,7 @@ export function calculateAmountToTradeForLimit(
|
|
|
201
186
|
'Cant calculate limit price for oracle offset oracle without OraclePriceData'
|
|
202
187
|
);
|
|
203
188
|
}
|
|
204
|
-
|
|
205
|
-
if (order.postOnly) {
|
|
206
|
-
limitPrice = isVariant(order.direction, 'long')
|
|
207
|
-
? BN.min(order.price, floatingPrice)
|
|
208
|
-
: BN.max(order.price, floatingPrice);
|
|
209
|
-
} else {
|
|
210
|
-
limitPrice = floatingPrice;
|
|
211
|
-
}
|
|
189
|
+
limitPrice = oraclePriceData.price.add(order.oraclePriceOffset);
|
|
212
190
|
}
|
|
213
191
|
|
|
214
192
|
const [maxAmountToTrade, direction] = calculateMaxBaseAssetAmountToTrade(
|
|
@@ -237,14 +215,8 @@ export function calculateAmountToTradeForTriggerLimit(
|
|
|
237
215
|
market: MarketAccount,
|
|
238
216
|
order: Order
|
|
239
217
|
): BN {
|
|
240
|
-
if (order.
|
|
241
|
-
|
|
242
|
-
market,
|
|
243
|
-
order
|
|
244
|
-
);
|
|
245
|
-
if (baseAssetAmount.eq(ZERO)) {
|
|
246
|
-
return ZERO;
|
|
247
|
-
}
|
|
218
|
+
if (!order.triggered) {
|
|
219
|
+
return ZERO;
|
|
248
220
|
}
|
|
249
221
|
|
|
250
222
|
return calculateAmountToTradeForLimit(market, order);
|
|
@@ -264,105 +236,9 @@ function calculateAmountToTradeForTriggerMarket(
|
|
|
264
236
|
market: MarketAccount,
|
|
265
237
|
order: Order
|
|
266
238
|
): BN {
|
|
267
|
-
|
|
268
|
-
? order.baseAssetAmount
|
|
269
|
-
: ZERO;
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
function isTriggerConditionSatisfied(
|
|
273
|
-
market: MarketAccount,
|
|
274
|
-
order: Order,
|
|
275
|
-
oraclePriceData?: OraclePriceData
|
|
276
|
-
): boolean {
|
|
277
|
-
const markPrice = calculateMarkPrice(market, oraclePriceData);
|
|
278
|
-
if (isVariant(order.triggerCondition, 'above')) {
|
|
279
|
-
return markPrice.gt(order.triggerPrice);
|
|
280
|
-
} else {
|
|
281
|
-
return markPrice.lt(order.triggerPrice);
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
export function calculateBaseAssetAmountUserCanExecute(
|
|
286
|
-
market: MarketAccount,
|
|
287
|
-
order: Order,
|
|
288
|
-
user: ClearingHouseUser,
|
|
289
|
-
oraclePriceData?: OraclePriceData
|
|
290
|
-
): BN {
|
|
291
|
-
const maxLeverage = user.getMaxLeverage(order.marketIndex, 'Initial');
|
|
292
|
-
const freeCollateral = user.getFreeCollateral();
|
|
293
|
-
let quoteAssetAmount: BN;
|
|
294
|
-
if (isOrderRiskIncreasingInSameDirection(user, order)) {
|
|
295
|
-
quoteAssetAmount = freeCollateral.mul(maxLeverage).div(TEN_THOUSAND);
|
|
296
|
-
} else {
|
|
297
|
-
const position =
|
|
298
|
-
user.getUserPosition(order.marketIndex) ||
|
|
299
|
-
user.getEmptyPosition(order.marketIndex);
|
|
300
|
-
const positionValue = calculateBaseAssetValue(
|
|
301
|
-
market,
|
|
302
|
-
position,
|
|
303
|
-
oraclePriceData
|
|
304
|
-
);
|
|
305
|
-
quoteAssetAmount = freeCollateral
|
|
306
|
-
.mul(maxLeverage)
|
|
307
|
-
.div(TEN_THOUSAND)
|
|
308
|
-
.add(positionValue.mul(TWO));
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
if (quoteAssetAmount.lte(ZERO)) {
|
|
239
|
+
if (!order.triggered) {
|
|
312
240
|
return ZERO;
|
|
313
241
|
}
|
|
314
242
|
|
|
315
|
-
|
|
316
|
-
? SwapDirection.ADD
|
|
317
|
-
: SwapDirection.REMOVE;
|
|
318
|
-
|
|
319
|
-
const useSpread = !order.postOnly;
|
|
320
|
-
let amm: Parameters<typeof calculateAmmReservesAfterSwap>[0];
|
|
321
|
-
if (useSpread) {
|
|
322
|
-
const { baseAssetReserve, quoteAssetReserve } = calculateSpreadReserves(
|
|
323
|
-
market.amm,
|
|
324
|
-
order.direction,
|
|
325
|
-
oraclePriceData
|
|
326
|
-
);
|
|
327
|
-
amm = {
|
|
328
|
-
baseAssetReserve,
|
|
329
|
-
quoteAssetReserve,
|
|
330
|
-
sqrtK: market.amm.sqrtK,
|
|
331
|
-
pegMultiplier: market.amm.pegMultiplier,
|
|
332
|
-
};
|
|
333
|
-
} else {
|
|
334
|
-
amm = market.amm;
|
|
335
|
-
}
|
|
336
|
-
|
|
337
|
-
const baseAssetReservesBefore = amm.baseAssetReserve;
|
|
338
|
-
const [_, baseAssetReservesAfter] = calculateAmmReservesAfterSwap(
|
|
339
|
-
amm,
|
|
340
|
-
'quote',
|
|
341
|
-
quoteAssetAmount,
|
|
342
|
-
swapDirection
|
|
343
|
-
);
|
|
344
|
-
|
|
345
|
-
let baseAssetAmount = baseAssetReservesBefore
|
|
346
|
-
.sub(baseAssetReservesAfter)
|
|
347
|
-
.abs();
|
|
348
|
-
if (order.reduceOnly) {
|
|
349
|
-
const position =
|
|
350
|
-
user.getUserPosition(order.marketIndex) ||
|
|
351
|
-
user.getEmptyPosition(order.marketIndex);
|
|
352
|
-
if (
|
|
353
|
-
isVariant(order.direction, 'long') &&
|
|
354
|
-
position.baseAssetAmount.gte(ZERO)
|
|
355
|
-
) {
|
|
356
|
-
baseAssetAmount = ZERO;
|
|
357
|
-
} else if (
|
|
358
|
-
isVariant(order.direction, 'short') &&
|
|
359
|
-
position.baseAssetAmount.lte(ZERO)
|
|
360
|
-
) {
|
|
361
|
-
baseAssetAmount = ZERO;
|
|
362
|
-
} else {
|
|
363
|
-
BN.min(baseAssetAmount, position.baseAssetAmount.abs());
|
|
364
|
-
}
|
|
365
|
-
}
|
|
366
|
-
|
|
367
|
-
return baseAssetAmount;
|
|
243
|
+
return order.baseAssetAmount;
|
|
368
244
|
}
|
|
@@ -0,0 +1,39 @@
|
|
|
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.SlotSubscriber = void 0;
|
|
13
|
+
const events_1 = require("events");
|
|
14
|
+
class SlotSubscriber {
|
|
15
|
+
constructor(connection, _config) {
|
|
16
|
+
this.connection = connection;
|
|
17
|
+
this.eventEmitter = new events_1.EventEmitter();
|
|
18
|
+
}
|
|
19
|
+
subscribe() {
|
|
20
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
21
|
+
this.currentSlot = yield this.connection.getSlot('confirmed');
|
|
22
|
+
this.subscriptionId = this.connection.onSlotChange((slotInfo) => {
|
|
23
|
+
this.currentSlot = slotInfo.slot;
|
|
24
|
+
this.eventEmitter.emit('newSlot', slotInfo.slot);
|
|
25
|
+
});
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
getSlot() {
|
|
29
|
+
return this.currentSlot;
|
|
30
|
+
}
|
|
31
|
+
unsubscribe() {
|
|
32
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
33
|
+
if (this.subscriptionId) {
|
|
34
|
+
yield this.connection.removeSlotChangeListener(this.subscriptionId);
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
exports.SlotSubscriber = SlotSubscriber;
|
|
@@ -1,22 +1,32 @@
|
|
|
1
1
|
import { Connection } from '@solana/web3.js';
|
|
2
|
+
import { EventEmitter } from 'events';
|
|
3
|
+
import StrictEventEmitter from 'strict-event-emitter-types/types/src';
|
|
2
4
|
|
|
3
5
|
// eslint-disable-next-line @typescript-eslint/ban-types
|
|
4
6
|
type SlotSubscriberConfig = {}; // for future customization
|
|
5
7
|
|
|
8
|
+
export interface SlotSubscriberEvents {
|
|
9
|
+
newSlot: (newSlot: number) => void;
|
|
10
|
+
}
|
|
11
|
+
|
|
6
12
|
export class SlotSubscriber {
|
|
7
13
|
currentSlot: number;
|
|
8
14
|
subscriptionId: number;
|
|
15
|
+
eventEmitter: StrictEventEmitter<EventEmitter, SlotSubscriberEvents>;
|
|
9
16
|
|
|
10
17
|
public constructor(
|
|
11
18
|
private connection: Connection,
|
|
12
19
|
_config?: SlotSubscriberConfig
|
|
13
|
-
) {
|
|
20
|
+
) {
|
|
21
|
+
this.eventEmitter = new EventEmitter();
|
|
22
|
+
}
|
|
14
23
|
|
|
15
24
|
public async subscribe(): Promise<void> {
|
|
16
25
|
this.currentSlot = await this.connection.getSlot('confirmed');
|
|
17
26
|
|
|
18
27
|
this.subscriptionId = this.connection.onSlotChange((slotInfo) => {
|
|
19
28
|
this.currentSlot = slotInfo.slot;
|
|
29
|
+
this.eventEmitter.emit('newSlot', slotInfo.slot);
|
|
20
30
|
});
|
|
21
31
|
}
|
|
22
32
|
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.parseTokenAccount = void 0;
|
|
4
|
+
const spl_token_1 = require("@solana/spl-token");
|
|
5
|
+
const web3_js_1 = require("@solana/web3.js");
|
|
6
|
+
function parseTokenAccount(data) {
|
|
7
|
+
const accountInfo = spl_token_1.AccountLayout.decode(data);
|
|
8
|
+
accountInfo.mint = new web3_js_1.PublicKey(accountInfo.mint);
|
|
9
|
+
accountInfo.owner = new web3_js_1.PublicKey(accountInfo.owner);
|
|
10
|
+
accountInfo.amount = spl_token_1.u64.fromBuffer(accountInfo.amount);
|
|
11
|
+
if (accountInfo.delegateOption === 0) {
|
|
12
|
+
accountInfo.delegate = null;
|
|
13
|
+
// eslint-disable-next-line new-cap
|
|
14
|
+
accountInfo.delegatedAmount = new spl_token_1.u64(0);
|
|
15
|
+
}
|
|
16
|
+
else {
|
|
17
|
+
accountInfo.delegate = new web3_js_1.PublicKey(accountInfo.delegate);
|
|
18
|
+
accountInfo.delegatedAmount = spl_token_1.u64.fromBuffer(accountInfo.delegatedAmount);
|
|
19
|
+
}
|
|
20
|
+
accountInfo.isInitialized = accountInfo.state !== 0;
|
|
21
|
+
accountInfo.isFrozen = accountInfo.state === 2;
|
|
22
|
+
if (accountInfo.isNativeOption === 1) {
|
|
23
|
+
accountInfo.rentExemptReserve = spl_token_1.u64.fromBuffer(accountInfo.isNative);
|
|
24
|
+
accountInfo.isNative = true;
|
|
25
|
+
}
|
|
26
|
+
else {
|
|
27
|
+
accountInfo.rentExemptReserve = null;
|
|
28
|
+
accountInfo.isNative = false;
|
|
29
|
+
}
|
|
30
|
+
if (accountInfo.closeAuthorityOption === 0) {
|
|
31
|
+
accountInfo.closeAuthority = null;
|
|
32
|
+
}
|
|
33
|
+
else {
|
|
34
|
+
accountInfo.closeAuthority = new web3_js_1.PublicKey(accountInfo.closeAuthority);
|
|
35
|
+
}
|
|
36
|
+
return accountInfo;
|
|
37
|
+
}
|
|
38
|
+
exports.parseTokenAccount = parseTokenAccount;
|
|
@@ -3,7 +3,6 @@ import { AnchorProvider, Idl, Program } from '@project-serum/anchor';
|
|
|
3
3
|
import {
|
|
4
4
|
AccountInfo,
|
|
5
5
|
ASSOCIATED_TOKEN_PROGRAM_ID,
|
|
6
|
-
MintLayout,
|
|
7
6
|
Token,
|
|
8
7
|
TOKEN_PROGRAM_ID,
|
|
9
8
|
} from '@solana/spl-token';
|
|
@@ -11,27 +10,28 @@ import {
|
|
|
11
10
|
ConfirmOptions,
|
|
12
11
|
Connection,
|
|
13
12
|
PublicKey,
|
|
14
|
-
SystemProgram,
|
|
15
13
|
SYSVAR_RENT_PUBKEY,
|
|
16
14
|
Transaction,
|
|
17
15
|
TransactionInstruction,
|
|
18
16
|
TransactionSignature,
|
|
19
17
|
} from '@solana/web3.js';
|
|
20
18
|
import { BN } from '.';
|
|
21
|
-
import
|
|
19
|
+
import tokenFaucet from './idl/token_faucet.json';
|
|
22
20
|
import { IWallet } from './types';
|
|
23
21
|
|
|
24
|
-
export class
|
|
22
|
+
export class TokenFaucet {
|
|
25
23
|
connection: Connection;
|
|
26
24
|
wallet: IWallet;
|
|
27
25
|
public program: Program;
|
|
28
26
|
provider: AnchorProvider;
|
|
27
|
+
mint: PublicKey;
|
|
29
28
|
opts?: ConfirmOptions;
|
|
30
29
|
|
|
31
30
|
public constructor(
|
|
32
31
|
connection: Connection,
|
|
33
32
|
wallet: IWallet,
|
|
34
33
|
programId: PublicKey,
|
|
34
|
+
mint: PublicKey,
|
|
35
35
|
opts?: ConfirmOptions
|
|
36
36
|
) {
|
|
37
37
|
this.connection = connection;
|
|
@@ -39,78 +39,56 @@ export class MockUSDCFaucet {
|
|
|
39
39
|
this.opts = opts || AnchorProvider.defaultOptions();
|
|
40
40
|
const provider = new AnchorProvider(connection, wallet, this.opts);
|
|
41
41
|
this.provider = provider;
|
|
42
|
-
this.program = new Program(
|
|
42
|
+
this.program = new Program(tokenFaucet as Idl, programId, provider);
|
|
43
|
+
this.mint = mint;
|
|
43
44
|
}
|
|
44
45
|
|
|
45
|
-
public async
|
|
46
|
+
public async getFaucetConfigPublicKeyAndNonce(): Promise<
|
|
46
47
|
[PublicKey, number]
|
|
47
48
|
> {
|
|
48
49
|
return anchor.web3.PublicKey.findProgramAddress(
|
|
49
|
-
[
|
|
50
|
+
[
|
|
51
|
+
Buffer.from(anchor.utils.bytes.utf8.encode('faucet_config')),
|
|
52
|
+
this.mint.toBuffer(),
|
|
53
|
+
],
|
|
50
54
|
this.program.programId
|
|
51
55
|
);
|
|
52
56
|
}
|
|
53
57
|
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
58
|
+
public async getMintAuthority(): Promise<PublicKey> {
|
|
59
|
+
return (
|
|
60
|
+
await anchor.web3.PublicKey.findProgramAddress(
|
|
61
|
+
[
|
|
62
|
+
Buffer.from(anchor.utils.bytes.utf8.encode('mint_authority')),
|
|
63
|
+
this.mint.toBuffer(),
|
|
64
|
+
],
|
|
65
|
+
this.program.programId
|
|
66
|
+
)
|
|
61
67
|
)[0];
|
|
62
|
-
return this.mockUSDCFaucetStatePublicKey;
|
|
63
68
|
}
|
|
64
69
|
|
|
65
|
-
public async
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
);
|
|
69
|
-
if (stateAccountRPCResponse.value !== null) {
|
|
70
|
-
throw new Error('Faucet already initialized');
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
const fakeUSDCMint = anchor.web3.Keypair.generate();
|
|
74
|
-
const createUSDCMintAccountIx = SystemProgram.createAccount({
|
|
75
|
-
fromPubkey: this.wallet.publicKey,
|
|
76
|
-
newAccountPubkey: fakeUSDCMint.publicKey,
|
|
77
|
-
lamports: await Token.getMinBalanceRentForExemptMint(this.connection),
|
|
78
|
-
space: MintLayout.span,
|
|
79
|
-
programId: TOKEN_PROGRAM_ID,
|
|
80
|
-
});
|
|
81
|
-
|
|
82
|
-
const [mintAuthority, _mintAuthorityNonce] =
|
|
83
|
-
await PublicKey.findProgramAddress(
|
|
84
|
-
[fakeUSDCMint.publicKey.toBuffer()],
|
|
85
|
-
this.program.programId
|
|
86
|
-
);
|
|
87
|
-
|
|
88
|
-
const initUSDCMintIx = Token.createInitMintInstruction(
|
|
89
|
-
TOKEN_PROGRAM_ID,
|
|
90
|
-
fakeUSDCMint.publicKey,
|
|
91
|
-
6,
|
|
92
|
-
mintAuthority,
|
|
93
|
-
null
|
|
94
|
-
);
|
|
70
|
+
public async getFaucetConfigPublicKey(): Promise<PublicKey> {
|
|
71
|
+
return (await this.getFaucetConfigPublicKeyAndNonce())[0];
|
|
72
|
+
}
|
|
95
73
|
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
74
|
+
public async initialize(): Promise<TransactionSignature> {
|
|
75
|
+
const [faucetConfigPublicKey] =
|
|
76
|
+
await this.getFaucetConfigPublicKeyAndNonce();
|
|
77
|
+
return await this.program.rpc.initialize({
|
|
99
78
|
accounts: {
|
|
100
|
-
|
|
79
|
+
faucetConfig: faucetConfigPublicKey,
|
|
101
80
|
admin: this.wallet.publicKey,
|
|
102
|
-
mintAccount:
|
|
81
|
+
mintAccount: this.mint,
|
|
103
82
|
rent: SYSVAR_RENT_PUBKEY,
|
|
104
83
|
systemProgram: anchor.web3.SystemProgram.programId,
|
|
84
|
+
tokenProgram: TOKEN_PROGRAM_ID,
|
|
105
85
|
},
|
|
106
|
-
instructions: [createUSDCMintAccountIx, initUSDCMintIx],
|
|
107
|
-
signers: [fakeUSDCMint],
|
|
108
86
|
});
|
|
109
87
|
}
|
|
110
88
|
|
|
111
89
|
public async fetchState(): Promise<any> {
|
|
112
|
-
return await this.program.account.
|
|
113
|
-
await this.
|
|
90
|
+
return await this.program.account.faucetConfig.fetch(
|
|
91
|
+
await this.getFaucetConfigPublicKey()
|
|
114
92
|
);
|
|
115
93
|
}
|
|
116
94
|
|
|
@@ -118,18 +96,29 @@ export class MockUSDCFaucet {
|
|
|
118
96
|
userTokenAccount: PublicKey,
|
|
119
97
|
amount: BN
|
|
120
98
|
): Promise<TransactionSignature> {
|
|
121
|
-
const state: any = await this.fetchState();
|
|
122
99
|
return await this.program.rpc.mintToUser(amount, {
|
|
123
100
|
accounts: {
|
|
124
|
-
|
|
125
|
-
mintAccount:
|
|
101
|
+
faucetConfig: await this.getFaucetConfigPublicKey(),
|
|
102
|
+
mintAccount: this.mint,
|
|
126
103
|
userTokenAccount,
|
|
127
|
-
mintAuthority:
|
|
104
|
+
mintAuthority: await this.getMintAuthority(),
|
|
128
105
|
tokenProgram: TOKEN_PROGRAM_ID,
|
|
129
106
|
},
|
|
130
107
|
});
|
|
131
108
|
}
|
|
132
109
|
|
|
110
|
+
public async transferMintAuthority(): Promise<TransactionSignature> {
|
|
111
|
+
return await this.program.rpc.transferMintAuthority({
|
|
112
|
+
accounts: {
|
|
113
|
+
faucetConfig: await this.getFaucetConfigPublicKey(),
|
|
114
|
+
mintAccount: this.mint,
|
|
115
|
+
mintAuthority: await this.getMintAuthority(),
|
|
116
|
+
tokenProgram: TOKEN_PROGRAM_ID,
|
|
117
|
+
admin: this.wallet.publicKey,
|
|
118
|
+
},
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
|
|
133
122
|
public async createAssociatedTokenAccountAndMintTo(
|
|
134
123
|
userPublicKey: PublicKey,
|
|
135
124
|
amount: BN
|
|
@@ -166,7 +155,7 @@ export class MockUSDCFaucet {
|
|
|
166
155
|
|
|
167
156
|
const mintToIx = await this.program.instruction.mintToUser(amount, {
|
|
168
157
|
accounts: {
|
|
169
|
-
|
|
158
|
+
faucetConfig: await this.getFaucetConfigPublicKey(),
|
|
170
159
|
mintAccount: state.mint,
|
|
171
160
|
userTokenAccount: associateTokenPublicKey,
|
|
172
161
|
mintAuthority: state.mintAuthority,
|