@drift-labs/sdk 0.1.30-master.4 → 0.1.33
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/accounts/bulkAccountLoader.d.ts +1 -0
- package/lib/accounts/bulkAccountLoader.js +7 -0
- package/lib/constants/markets.js +23 -1
- package/lib/idl/clearing_house.json +17 -0
- package/lib/math/funding.js +4 -2
- package/lib/math/orders.js +4 -3
- package/lib/orders.js +24 -2
- package/lib/tx/retryTxSender.d.ts +1 -0
- package/lib/tx/retryTxSender.js +9 -0
- package/package.json +1 -1
- package/src/accounts/bulkAccountLoader.ts +8 -0
- package/src/assert/assert.js +10 -0
- package/src/assert/assert.js.map +1 -0
- package/src/constants/markets.ts +23 -1
- package/src/idl/clearing_house.json +17 -0
- package/src/math/conversion.js +16 -0
- package/src/math/conversion.js.map +1 -0
- package/src/math/funding.js +223 -0
- package/src/math/funding.js.map +1 -0
- package/src/math/funding.ts +10 -3
- package/src/math/insuranceFund.js +23 -0
- package/src/math/insuranceFund.js.map +1 -0
- package/src/math/orders.ts +6 -3
- package/src/math/position.js +121 -0
- package/src/math/position.js.map +1 -0
- package/src/math/utils.js +27 -0
- package/src/math/utils.js.map +1 -0
- package/src/oracles/switchboardClient.js +60 -0
- package/src/oracles/switchboardClient.js.map +1 -0
- package/src/orders.ts +23 -2
- package/src/token/index.js +39 -0
- package/src/token/index.js.map +1 -0
- package/src/tx/defaultTxSender.js +13 -0
- package/src/tx/defaultTxSender.js.map +1 -0
- package/src/tx/retryTxSender.ts +12 -0
- package/src/tx/types.js +3 -0
- package/src/tx/types.js.map +1 -0
- package/src/tx/utils.js +9 -0
- package/src/tx/utils.js.map +1 -0
- package/src/util/computeUnits.js +17 -0
- package/src/util/computeUnits.js.map +1 -0
- package/src/util/tps.js +17 -0
- package/src/util/tps.js.map +1 -0
|
@@ -210,5 +210,12 @@ class BulkAccountLoader {
|
|
|
210
210
|
console.log(msg);
|
|
211
211
|
}
|
|
212
212
|
}
|
|
213
|
+
updatePollingFrequency(pollingFrequency) {
|
|
214
|
+
this.stopPolling();
|
|
215
|
+
this.pollingFrequency = pollingFrequency;
|
|
216
|
+
if (this.accountsToLoad.size > 0) {
|
|
217
|
+
this.startPolling();
|
|
218
|
+
}
|
|
219
|
+
}
|
|
213
220
|
}
|
|
214
221
|
exports.BulkAccountLoader = BulkAccountLoader;
|
package/lib/constants/markets.js
CHANGED
|
@@ -190,7 +190,7 @@ exports.Markets = [
|
|
|
190
190
|
},
|
|
191
191
|
{
|
|
192
192
|
fullName: 'Serum',
|
|
193
|
-
category: ['
|
|
193
|
+
category: ['Solana', 'Exchange'],
|
|
194
194
|
symbol: 'SRM-PERP',
|
|
195
195
|
baseAssetSymbol: 'SRM',
|
|
196
196
|
marketIndex: new __1.BN(17),
|
|
@@ -199,4 +199,26 @@ exports.Markets = [
|
|
|
199
199
|
launchTs: 1649877367000,
|
|
200
200
|
oracleSource: __1.OracleSource.PYTH,
|
|
201
201
|
},
|
|
202
|
+
{
|
|
203
|
+
fullName: 'StepN',
|
|
204
|
+
category: ['Solana', 'Shoe'],
|
|
205
|
+
symbol: 'GMT-PERP',
|
|
206
|
+
baseAssetSymbol: 'GMT',
|
|
207
|
+
marketIndex: new __1.BN(18),
|
|
208
|
+
devnetPublicKey: '7GBoA2oGXMTepYjFgrdHyYVGcPs4FWskUF7S1dGzQsY9',
|
|
209
|
+
mainnetPublicKey: '81kbdwDfTNsg4d5D1BxE9FHEdxEMk8xCJUj5ujjWQyvd',
|
|
210
|
+
launchTs: 1650507526000,
|
|
211
|
+
oracleSource: __1.OracleSource.SWITCHBOARD,
|
|
212
|
+
},
|
|
213
|
+
{
|
|
214
|
+
fullName: 'Curve DAO Token',
|
|
215
|
+
category: ['Exchange'],
|
|
216
|
+
symbol: 'CRV-PERP',
|
|
217
|
+
baseAssetSymbol: 'CRV',
|
|
218
|
+
marketIndex: new __1.BN(19),
|
|
219
|
+
devnetPublicKey: 'AuEiE5XG5kD1NFoKgEPrWuN9CdT44A3K7yGDuiUPvh9S',
|
|
220
|
+
mainnetPublicKey: '61NzdQ9y6KhMhWxyJ8kXEe25NxdixVL1YUnGYLDMaUxH',
|
|
221
|
+
launchTs: 1651017354000,
|
|
222
|
+
oracleSource: __1.OracleSource.SWITCHBOARD,
|
|
223
|
+
},
|
|
202
224
|
];
|
|
@@ -3832,6 +3832,23 @@
|
|
|
3832
3832
|
]
|
|
3833
3833
|
}
|
|
3834
3834
|
},
|
|
3835
|
+
{
|
|
3836
|
+
"name": "MarginType",
|
|
3837
|
+
"type": {
|
|
3838
|
+
"kind": "enum",
|
|
3839
|
+
"variants": [
|
|
3840
|
+
{
|
|
3841
|
+
"name": "Init"
|
|
3842
|
+
},
|
|
3843
|
+
{
|
|
3844
|
+
"name": "Partial"
|
|
3845
|
+
},
|
|
3846
|
+
{
|
|
3847
|
+
"name": "Maint"
|
|
3848
|
+
}
|
|
3849
|
+
]
|
|
3850
|
+
}
|
|
3851
|
+
},
|
|
3835
3852
|
{
|
|
3836
3853
|
"name": "LiquidationType",
|
|
3837
3854
|
"type": {
|
package/lib/math/funding.js
CHANGED
|
@@ -39,7 +39,7 @@ function calculateAllEstimatedFundingRate(market, oraclePriceData, periodAdjustm
|
|
|
39
39
|
const lastMarkTwapWithMantissa = market.amm.lastMarkPriceTwap;
|
|
40
40
|
const lastMarkPriceTwapTs = market.amm.lastMarkPriceTwapTs;
|
|
41
41
|
const timeSinceLastMarkChange = now.sub(lastMarkPriceTwapTs);
|
|
42
|
-
const markTwapTimeSinceLastUpdate = anchor_1.BN.max(secondsInHour, secondsInHour.sub(timeSinceLastMarkChange));
|
|
42
|
+
const markTwapTimeSinceLastUpdate = anchor_1.BN.max(secondsInHour, anchor_1.BN.max(numericConstants_1.ZERO, secondsInHour.sub(timeSinceLastMarkChange)));
|
|
43
43
|
const baseAssetPriceWithMantissa = (0, market_1.calculateMarkPrice)(market);
|
|
44
44
|
const markTwapWithMantissa = markTwapTimeSinceLastUpdate
|
|
45
45
|
.mul(lastMarkTwapWithMantissa)
|
|
@@ -49,6 +49,7 @@ function calculateAllEstimatedFundingRate(market, oraclePriceData, periodAdjustm
|
|
|
49
49
|
// note: oracle twap depends on `when the chord is struck` (market is trade)
|
|
50
50
|
const lastOracleTwapWithMantissa = market.amm.lastOraclePriceTwap;
|
|
51
51
|
const lastOraclePriceTwapTs = market.amm.lastOraclePriceTwapTs;
|
|
52
|
+
const oracleInvalidDuration = anchor_1.BN.max(numericConstants_1.ZERO, lastMarkPriceTwapTs.sub(lastOraclePriceTwapTs));
|
|
52
53
|
const timeSinceLastOracleTwapUpdate = now.sub(lastOraclePriceTwapTs);
|
|
53
54
|
const oracleTwapTimeSinceLastUpdate = anchor_1.BN.max(secondsInHour, secondsInHour.sub(timeSinceLastOracleTwapUpdate));
|
|
54
55
|
const oraclePrice = oraclePriceData.price;
|
|
@@ -64,7 +65,8 @@ function calculateAllEstimatedFundingRate(market, oraclePriceData, periodAdjustm
|
|
|
64
65
|
oracleTwapWithMantissa = oracleTwapTimeSinceLastUpdate
|
|
65
66
|
.mul(lastOracleTwapWithMantissa)
|
|
66
67
|
.add(timeSinceLastMarkChange.mul(oraclePrice))
|
|
67
|
-
.
|
|
68
|
+
.add(oracleInvalidDuration.mul(lastMarkTwapWithMantissa))
|
|
69
|
+
.div(timeSinceLastMarkChange.add(oracleTwapTimeSinceLastUpdate).add(oracleInvalidDuration));
|
|
68
70
|
}
|
|
69
71
|
const twapSpread = lastMarkTwapWithMantissa.sub(lastOracleTwapWithMantissa);
|
|
70
72
|
const twapSpreadPct = twapSpread
|
package/lib/math/orders.js
CHANGED
|
@@ -59,14 +59,15 @@ function isOrderReduceOnly(user, order) {
|
|
|
59
59
|
const position = user.getUserPosition(order.marketIndex) ||
|
|
60
60
|
user.getEmptyPosition(order.marketIndex);
|
|
61
61
|
// if position is long and order is long
|
|
62
|
-
if (position.baseAssetAmount.
|
|
62
|
+
if (position.baseAssetAmount.gte(numericConstants_1.ZERO) &&
|
|
63
|
+
(0, types_1.isVariant)(order.direction, 'long')) {
|
|
63
64
|
return false;
|
|
64
65
|
}
|
|
65
66
|
// if position is short and order is short
|
|
66
|
-
if (position.baseAssetAmount.
|
|
67
|
+
if (position.baseAssetAmount.lte(numericConstants_1.ZERO) &&
|
|
67
68
|
(0, types_1.isVariant)(order.direction, 'short')) {
|
|
68
69
|
return false;
|
|
69
70
|
}
|
|
70
|
-
return
|
|
71
|
+
return true;
|
|
71
72
|
}
|
|
72
73
|
exports.isOrderReduceOnly = isOrderReduceOnly;
|
package/lib/orders.js
CHANGED
|
@@ -102,7 +102,15 @@ function calculateAmountToTradeForLimit(market, order, oraclePriceData) {
|
|
|
102
102
|
if (!oraclePriceData) {
|
|
103
103
|
throw Error('Cant calculate limit price for oracle offset oracle without OraclePriceData');
|
|
104
104
|
}
|
|
105
|
-
|
|
105
|
+
const floatingPrice = oraclePriceData.price.add(order.oraclePriceOffset);
|
|
106
|
+
if (order.postOnly) {
|
|
107
|
+
limitPrice = (0, types_1.isVariant)(order.direction, 'long')
|
|
108
|
+
? _1.BN.min(order.price, floatingPrice)
|
|
109
|
+
: _1.BN.max(order.price, floatingPrice);
|
|
110
|
+
}
|
|
111
|
+
else {
|
|
112
|
+
limitPrice = floatingPrice;
|
|
113
|
+
}
|
|
106
114
|
}
|
|
107
115
|
const [maxAmountToTrade, direction] = (0, amm_1.calculateMaxBaseAssetAmountToTrade)(market.amm, limitPrice);
|
|
108
116
|
// Check that directions are the same
|
|
@@ -166,6 +174,20 @@ function calculateBaseAssetAmountUserCanExecute(market, order, user) {
|
|
|
166
174
|
const [_, baseAssetReservesAfter] = (0, _1.calculateAmmReservesAfterSwap)(market.amm, 'quote', quoteAssetAmount, (0, types_1.isVariant)(order.direction, 'long')
|
|
167
175
|
? types_1.SwapDirection.ADD
|
|
168
176
|
: types_1.SwapDirection.REMOVE);
|
|
169
|
-
|
|
177
|
+
let baseAssetAmount = baseAssetReservesBefore.sub(baseAssetReservesAfter).abs();
|
|
178
|
+
if (order.reduceOnly) {
|
|
179
|
+
const position = user.getUserPosition(order.marketIndex) ||
|
|
180
|
+
user.getEmptyPosition(order.marketIndex);
|
|
181
|
+
if ((0, types_1.isVariant)(order.direction, 'long') && position.baseAssetAmount.gte(numericConstants_1.ZERO)) {
|
|
182
|
+
baseAssetAmount = numericConstants_1.ZERO;
|
|
183
|
+
}
|
|
184
|
+
else if ((0, types_1.isVariant)(order.direction, 'short') && position.baseAssetAmount.lte(numericConstants_1.ZERO)) {
|
|
185
|
+
baseAssetAmount = numericConstants_1.ZERO;
|
|
186
|
+
}
|
|
187
|
+
else {
|
|
188
|
+
_1.BN.min(baseAssetAmount, position.baseAssetAmount.abs());
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
return baseAssetAmount;
|
|
170
192
|
}
|
|
171
193
|
exports.calculateBaseAssetAmountUserCanExecute = calculateBaseAssetAmountUserCanExecute;
|
|
@@ -18,5 +18,6 @@ export declare class RetryTxSender implements TxSender {
|
|
|
18
18
|
sleep(reference: ResolveReference): Promise<void>;
|
|
19
19
|
promiseTimeout<T>(promises: Promise<T>[], timeoutMs: number): Promise<T | null>;
|
|
20
20
|
sendToAdditionalConnections(rawTx: Buffer, opts: ConfirmOptions): void;
|
|
21
|
+
addAdditionalConnection(newConnection: Connection): void;
|
|
21
22
|
}
|
|
22
23
|
export {};
|
package/lib/tx/retryTxSender.js
CHANGED
|
@@ -173,5 +173,14 @@ class RetryTxSender {
|
|
|
173
173
|
});
|
|
174
174
|
});
|
|
175
175
|
}
|
|
176
|
+
addAdditionalConnection(newConnection) {
|
|
177
|
+
const alreadyUsingConnection = this.additionalConnections.filter((connection) => {
|
|
178
|
+
// @ts-ignore
|
|
179
|
+
return connection._rpcEndpoint === newConnection.rpcEndpoint;
|
|
180
|
+
}).length > 0;
|
|
181
|
+
if (!alreadyUsingConnection) {
|
|
182
|
+
this.additionalConnections.push(newConnection);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
176
185
|
}
|
|
177
186
|
exports.RetryTxSender = RetryTxSender;
|
package/package.json
CHANGED
|
@@ -257,4 +257,12 @@ export class BulkAccountLoader {
|
|
|
257
257
|
console.log(msg);
|
|
258
258
|
}
|
|
259
259
|
}
|
|
260
|
+
|
|
261
|
+
public updatePollingFrequency(pollingFrequency: number): void {
|
|
262
|
+
this.stopPolling();
|
|
263
|
+
this.pollingFrequency = pollingFrequency;
|
|
264
|
+
if (this.accountsToLoad.size > 0) {
|
|
265
|
+
this.startPolling();
|
|
266
|
+
}
|
|
267
|
+
}
|
|
260
268
|
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.assert = void 0;
|
|
4
|
+
function assert(condition, error) {
|
|
5
|
+
if (!condition) {
|
|
6
|
+
throw new Error(error || 'Unspecified AssertionError');
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
exports.assert = assert;
|
|
10
|
+
//# sourceMappingURL=assert.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"assert.js","sourceRoot":"","sources":["assert.ts"],"names":[],"mappings":";;;AAAA,SAAgB,MAAM,CAAC,SAAkB,EAAE,KAAc;IACxD,IAAI,CAAC,SAAS,EAAE;QACf,MAAM,IAAI,KAAK,CAAC,KAAK,IAAI,4BAA4B,CAAC,CAAC;KACvD;AACF,CAAC;AAJD,wBAIC"}
|
package/src/constants/markets.ts
CHANGED
|
@@ -200,7 +200,7 @@ export const Markets: MarketConfig[] = [
|
|
|
200
200
|
},
|
|
201
201
|
{
|
|
202
202
|
fullName: 'Serum',
|
|
203
|
-
category: ['
|
|
203
|
+
category: ['Solana', 'Exchange'],
|
|
204
204
|
symbol: 'SRM-PERP',
|
|
205
205
|
baseAssetSymbol: 'SRM',
|
|
206
206
|
marketIndex: new BN(17),
|
|
@@ -209,4 +209,26 @@ export const Markets: MarketConfig[] = [
|
|
|
209
209
|
launchTs: 1649877367000,
|
|
210
210
|
oracleSource: OracleSource.PYTH,
|
|
211
211
|
},
|
|
212
|
+
{
|
|
213
|
+
fullName: 'StepN',
|
|
214
|
+
category: ['Solana', 'Shoe'],
|
|
215
|
+
symbol: 'GMT-PERP',
|
|
216
|
+
baseAssetSymbol: 'GMT',
|
|
217
|
+
marketIndex: new BN(18),
|
|
218
|
+
devnetPublicKey: '7GBoA2oGXMTepYjFgrdHyYVGcPs4FWskUF7S1dGzQsY9',
|
|
219
|
+
mainnetPublicKey: '81kbdwDfTNsg4d5D1BxE9FHEdxEMk8xCJUj5ujjWQyvd',
|
|
220
|
+
launchTs: 1650507526000,
|
|
221
|
+
oracleSource: OracleSource.SWITCHBOARD,
|
|
222
|
+
},
|
|
223
|
+
{
|
|
224
|
+
fullName: 'Curve DAO Token',
|
|
225
|
+
category: ['Exchange'],
|
|
226
|
+
symbol: 'CRV-PERP',
|
|
227
|
+
baseAssetSymbol: 'CRV',
|
|
228
|
+
marketIndex: new BN(19),
|
|
229
|
+
devnetPublicKey: 'AuEiE5XG5kD1NFoKgEPrWuN9CdT44A3K7yGDuiUPvh9S',
|
|
230
|
+
mainnetPublicKey: '61NzdQ9y6KhMhWxyJ8kXEe25NxdixVL1YUnGYLDMaUxH',
|
|
231
|
+
launchTs: 1651017354000,
|
|
232
|
+
oracleSource: OracleSource.SWITCHBOARD,
|
|
233
|
+
},
|
|
212
234
|
];
|
|
@@ -3832,6 +3832,23 @@
|
|
|
3832
3832
|
]
|
|
3833
3833
|
}
|
|
3834
3834
|
},
|
|
3835
|
+
{
|
|
3836
|
+
"name": "MarginType",
|
|
3837
|
+
"type": {
|
|
3838
|
+
"kind": "enum",
|
|
3839
|
+
"variants": [
|
|
3840
|
+
{
|
|
3841
|
+
"name": "Init"
|
|
3842
|
+
},
|
|
3843
|
+
{
|
|
3844
|
+
"name": "Partial"
|
|
3845
|
+
},
|
|
3846
|
+
{
|
|
3847
|
+
"name": "Maint"
|
|
3848
|
+
}
|
|
3849
|
+
]
|
|
3850
|
+
}
|
|
3851
|
+
},
|
|
3835
3852
|
{
|
|
3836
3853
|
"name": "LiquidationType",
|
|
3837
3854
|
"type": {
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.convertBaseAssetAmountToNumber = 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;
|
|
12
|
+
const convertBaseAssetAmountToNumber = (baseAssetAmount) => {
|
|
13
|
+
return (0, exports.convertToNumber)(baseAssetAmount, numericConstants_1.MARK_PRICE_PRECISION.mul(numericConstants_1.PEG_PRECISION));
|
|
14
|
+
};
|
|
15
|
+
exports.convertBaseAssetAmountToNumber = convertBaseAssetAmountToNumber;
|
|
16
|
+
//# sourceMappingURL=conversion.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"conversion.js","sourceRoot":"","sources":["conversion.ts"],"names":[],"mappings":";;;AACA,oEAGuC;AAEhC,MAAM,eAAe,GAAG,CAC9B,SAAa,EACb,YAAgB,uCAAoB,EACnC,EAAE;IACH,IAAI,CAAC,SAAS;QAAE,OAAO,CAAC,CAAC;IACzB,OAAO,CACN,SAAS,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,QAAQ,EAAE;QACnC,SAAS,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,QAAQ,EAAE,GAAG,SAAS,CAAC,QAAQ,EAAE,CAC1D,CAAC;AACH,CAAC,CAAC;AATW,QAAA,eAAe,mBAS1B;AAEK,MAAM,8BAA8B,GAAG,CAAC,eAAmB,EAAE,EAAE;IACrE,OAAO,IAAA,uBAAe,EACrB,eAAe,EACf,uCAAoB,CAAC,GAAG,CAAC,gCAAa,CAAC,CACvC,CAAC;AACH,CAAC,CAAC;AALW,QAAA,8BAA8B,kCAKzC"}
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.calculateFundingPool = exports.calculateLongShortFundingRateAndLiveTwaps = exports.calculateLongShortFundingRate = exports.calculateEstimatedFundingRate = exports.calculateAllEstimatedFundingRate = void 0;
|
|
4
|
+
const anchor_1 = require("@project-serum/anchor");
|
|
5
|
+
const numericConstants_1 = require("../constants/numericConstants");
|
|
6
|
+
const market_1 = require("./market");
|
|
7
|
+
/**
|
|
8
|
+
*
|
|
9
|
+
* @param market
|
|
10
|
+
* @param oraclePriceData
|
|
11
|
+
* @param periodAdjustment
|
|
12
|
+
* @returns Estimated funding rate. : Precision //TODO-PRECISION
|
|
13
|
+
*/
|
|
14
|
+
async function calculateAllEstimatedFundingRate(market, oraclePriceData, periodAdjustment = new anchor_1.BN(1)) {
|
|
15
|
+
// periodAdjustment
|
|
16
|
+
// 1: hourly
|
|
17
|
+
// 24: daily
|
|
18
|
+
// 24 * 365.25: annualized
|
|
19
|
+
const secondsInHour = new anchor_1.BN(3600);
|
|
20
|
+
const hoursInDay = new anchor_1.BN(24);
|
|
21
|
+
if (!market.initialized) {
|
|
22
|
+
return [numericConstants_1.ZERO, numericConstants_1.ZERO, numericConstants_1.ZERO, numericConstants_1.ZERO, numericConstants_1.ZERO];
|
|
23
|
+
}
|
|
24
|
+
const payFreq = new anchor_1.BN(market.amm.fundingPeriod);
|
|
25
|
+
// todo: sufficiently differs from blockchain timestamp?
|
|
26
|
+
const now = new anchor_1.BN((Date.now() / 1000).toFixed(0));
|
|
27
|
+
const timeSinceLastUpdate = now.sub(market.amm.lastFundingRateTs);
|
|
28
|
+
// calculate real-time mark twap
|
|
29
|
+
const lastMarkTwapWithMantissa = market.amm.lastMarkPriceTwap;
|
|
30
|
+
const lastMarkPriceTwapTs = market.amm.lastMarkPriceTwapTs;
|
|
31
|
+
const timeSinceLastMarkChange = now.sub(lastMarkPriceTwapTs);
|
|
32
|
+
const markTwapTimeSinceLastUpdate = anchor_1.BN.max(secondsInHour, secondsInHour.sub(timeSinceLastMarkChange));
|
|
33
|
+
const baseAssetPriceWithMantissa = (0, market_1.calculateMarkPrice)(market);
|
|
34
|
+
const markTwapWithMantissa = markTwapTimeSinceLastUpdate
|
|
35
|
+
.mul(lastMarkTwapWithMantissa)
|
|
36
|
+
.add(timeSinceLastMarkChange.mul(baseAssetPriceWithMantissa))
|
|
37
|
+
.div(timeSinceLastMarkChange.add(markTwapTimeSinceLastUpdate));
|
|
38
|
+
// calculate real-time (predicted) oracle twap
|
|
39
|
+
// note: oracle twap depends on `when the chord is struck` (market is trade)
|
|
40
|
+
const lastOracleTwapWithMantissa = market.amm.lastOraclePriceTwap;
|
|
41
|
+
const lastOraclePriceTwapTs = market.amm.lastOraclePriceTwapTs;
|
|
42
|
+
const timeSinceLastOracleTwapUpdate = now.sub(lastOraclePriceTwapTs);
|
|
43
|
+
const oracleTwapTimeSinceLastUpdate = anchor_1.BN.max(secondsInHour, secondsInHour.sub(timeSinceLastOracleTwapUpdate));
|
|
44
|
+
const oraclePrice = oraclePriceData.price;
|
|
45
|
+
let oracleTwapWithMantissa = lastOracleTwapWithMantissa;
|
|
46
|
+
const oracleLiveVsTwap = oraclePrice
|
|
47
|
+
.sub(lastOracleTwapWithMantissa)
|
|
48
|
+
.abs()
|
|
49
|
+
.mul(numericConstants_1.MARK_PRICE_PRECISION)
|
|
50
|
+
.mul(new anchor_1.BN(100))
|
|
51
|
+
.div(lastOracleTwapWithMantissa);
|
|
52
|
+
// verify pyth live input is within 10% of last twap for live update
|
|
53
|
+
if (oracleLiveVsTwap.lte(numericConstants_1.MARK_PRICE_PRECISION.mul(new anchor_1.BN(10)))) {
|
|
54
|
+
oracleTwapWithMantissa = oracleTwapTimeSinceLastUpdate
|
|
55
|
+
.mul(lastOracleTwapWithMantissa)
|
|
56
|
+
.add(timeSinceLastMarkChange.mul(oraclePrice))
|
|
57
|
+
.div(timeSinceLastOracleTwapUpdate.add(oracleTwapTimeSinceLastUpdate));
|
|
58
|
+
}
|
|
59
|
+
const twapSpread = lastMarkTwapWithMantissa.sub(lastOracleTwapWithMantissa);
|
|
60
|
+
const twapSpreadPct = twapSpread
|
|
61
|
+
.mul(numericConstants_1.MARK_PRICE_PRECISION)
|
|
62
|
+
.mul(new anchor_1.BN(100))
|
|
63
|
+
.div(oracleTwapWithMantissa);
|
|
64
|
+
const lowerboundEst = twapSpreadPct
|
|
65
|
+
.mul(payFreq)
|
|
66
|
+
.mul(anchor_1.BN.min(secondsInHour, timeSinceLastUpdate))
|
|
67
|
+
.mul(periodAdjustment)
|
|
68
|
+
.div(secondsInHour)
|
|
69
|
+
.div(secondsInHour)
|
|
70
|
+
.div(hoursInDay);
|
|
71
|
+
const interpEst = twapSpreadPct.mul(periodAdjustment).div(hoursInDay);
|
|
72
|
+
const interpRateQuote = twapSpreadPct
|
|
73
|
+
.mul(periodAdjustment)
|
|
74
|
+
.div(hoursInDay)
|
|
75
|
+
.div(numericConstants_1.MARK_PRICE_PRECISION.div(numericConstants_1.QUOTE_PRECISION));
|
|
76
|
+
let feePoolSize = calculateFundingPool(market);
|
|
77
|
+
if (interpRateQuote.lt(new anchor_1.BN(0))) {
|
|
78
|
+
feePoolSize = feePoolSize.mul(new anchor_1.BN(-1));
|
|
79
|
+
}
|
|
80
|
+
let cappedAltEst;
|
|
81
|
+
let largerSide;
|
|
82
|
+
let smallerSide;
|
|
83
|
+
if (market.baseAssetAmountLong.gt(market.baseAssetAmountShort.abs())) {
|
|
84
|
+
largerSide = market.baseAssetAmountLong.abs();
|
|
85
|
+
smallerSide = market.baseAssetAmountShort.abs();
|
|
86
|
+
if (twapSpread.gt(new anchor_1.BN(0))) {
|
|
87
|
+
return [
|
|
88
|
+
markTwapWithMantissa,
|
|
89
|
+
oracleTwapWithMantissa,
|
|
90
|
+
lowerboundEst,
|
|
91
|
+
interpEst,
|
|
92
|
+
interpEst,
|
|
93
|
+
];
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
else if (market.baseAssetAmountLong.lt(market.baseAssetAmountShort.abs())) {
|
|
97
|
+
largerSide = market.baseAssetAmountShort.abs();
|
|
98
|
+
smallerSide = market.baseAssetAmountLong.abs();
|
|
99
|
+
if (twapSpread.lt(new anchor_1.BN(0))) {
|
|
100
|
+
return [
|
|
101
|
+
markTwapWithMantissa,
|
|
102
|
+
oracleTwapWithMantissa,
|
|
103
|
+
lowerboundEst,
|
|
104
|
+
interpEst,
|
|
105
|
+
interpEst,
|
|
106
|
+
];
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
else {
|
|
110
|
+
return [
|
|
111
|
+
markTwapWithMantissa,
|
|
112
|
+
oracleTwapWithMantissa,
|
|
113
|
+
lowerboundEst,
|
|
114
|
+
interpEst,
|
|
115
|
+
interpEst,
|
|
116
|
+
];
|
|
117
|
+
}
|
|
118
|
+
if (largerSide.gt(numericConstants_1.ZERO)) {
|
|
119
|
+
// funding smaller flow
|
|
120
|
+
cappedAltEst = smallerSide.mul(twapSpread).div(hoursInDay);
|
|
121
|
+
const feePoolTopOff = feePoolSize
|
|
122
|
+
.mul(numericConstants_1.MARK_PRICE_PRECISION.div(numericConstants_1.QUOTE_PRECISION))
|
|
123
|
+
.mul(numericConstants_1.AMM_RESERVE_PRECISION);
|
|
124
|
+
cappedAltEst = cappedAltEst.add(feePoolTopOff).div(largerSide);
|
|
125
|
+
cappedAltEst = cappedAltEst
|
|
126
|
+
.mul(numericConstants_1.MARK_PRICE_PRECISION)
|
|
127
|
+
.mul(new anchor_1.BN(100))
|
|
128
|
+
.div(oracleTwapWithMantissa)
|
|
129
|
+
.mul(periodAdjustment);
|
|
130
|
+
if (cappedAltEst.abs().gte(interpEst.abs())) {
|
|
131
|
+
cappedAltEst = interpEst;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
else {
|
|
135
|
+
cappedAltEst = interpEst;
|
|
136
|
+
}
|
|
137
|
+
return [
|
|
138
|
+
markTwapWithMantissa,
|
|
139
|
+
oracleTwapWithMantissa,
|
|
140
|
+
lowerboundEst,
|
|
141
|
+
cappedAltEst,
|
|
142
|
+
interpEst,
|
|
143
|
+
];
|
|
144
|
+
}
|
|
145
|
+
exports.calculateAllEstimatedFundingRate = calculateAllEstimatedFundingRate;
|
|
146
|
+
/**
|
|
147
|
+
*
|
|
148
|
+
* @param market
|
|
149
|
+
* @param oraclePriceData
|
|
150
|
+
* @param periodAdjustment
|
|
151
|
+
* @param estimationMethod
|
|
152
|
+
* @returns Estimated funding rate. : Precision //TODO-PRECISION
|
|
153
|
+
*/
|
|
154
|
+
async function calculateEstimatedFundingRate(market, oraclePriceData, periodAdjustment = new anchor_1.BN(1), estimationMethod) {
|
|
155
|
+
const [_1, _2, lowerboundEst, cappedAltEst, interpEst] = await calculateAllEstimatedFundingRate(market, oraclePriceData, periodAdjustment);
|
|
156
|
+
if (estimationMethod == 'lowerbound') {
|
|
157
|
+
//assuming remaining funding period has no gap
|
|
158
|
+
return lowerboundEst;
|
|
159
|
+
}
|
|
160
|
+
else if (estimationMethod == 'capped') {
|
|
161
|
+
return cappedAltEst;
|
|
162
|
+
}
|
|
163
|
+
else {
|
|
164
|
+
return interpEst;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
exports.calculateEstimatedFundingRate = calculateEstimatedFundingRate;
|
|
168
|
+
/**
|
|
169
|
+
*
|
|
170
|
+
* @param market
|
|
171
|
+
* @param oraclePriceData
|
|
172
|
+
* @param periodAdjustment
|
|
173
|
+
* @returns Estimated funding rate. : Precision //TODO-PRECISION
|
|
174
|
+
*/
|
|
175
|
+
async function calculateLongShortFundingRate(market, oraclePriceData, periodAdjustment = new anchor_1.BN(1)) {
|
|
176
|
+
const [_1, _2, _, cappedAltEst, interpEst] = await calculateAllEstimatedFundingRate(market, oraclePriceData, periodAdjustment);
|
|
177
|
+
if (market.baseAssetAmountLong.gt(market.baseAssetAmountShort)) {
|
|
178
|
+
return [cappedAltEst, interpEst];
|
|
179
|
+
}
|
|
180
|
+
else if (market.baseAssetAmountLong.lt(market.baseAssetAmountShort)) {
|
|
181
|
+
return [interpEst, cappedAltEst];
|
|
182
|
+
}
|
|
183
|
+
else {
|
|
184
|
+
return [interpEst, interpEst];
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
exports.calculateLongShortFundingRate = calculateLongShortFundingRate;
|
|
188
|
+
/**
|
|
189
|
+
*
|
|
190
|
+
* @param market
|
|
191
|
+
* @param oraclePriceData
|
|
192
|
+
* @param periodAdjustment
|
|
193
|
+
* @returns Estimated funding rate. : Precision //TODO-PRECISION
|
|
194
|
+
*/
|
|
195
|
+
async function calculateLongShortFundingRateAndLiveTwaps(market, oraclePriceData, periodAdjustment = new anchor_1.BN(1)) {
|
|
196
|
+
const [markTwapLive, oracleTwapLive, _2, cappedAltEst, interpEst] = await calculateAllEstimatedFundingRate(market, oraclePriceData, periodAdjustment);
|
|
197
|
+
if (market.baseAssetAmountLong.gt(market.baseAssetAmountShort.abs())) {
|
|
198
|
+
return [markTwapLive, oracleTwapLive, cappedAltEst, interpEst];
|
|
199
|
+
}
|
|
200
|
+
else if (market.baseAssetAmountLong.lt(market.baseAssetAmountShort.abs())) {
|
|
201
|
+
return [markTwapLive, oracleTwapLive, interpEst, cappedAltEst];
|
|
202
|
+
}
|
|
203
|
+
else {
|
|
204
|
+
return [markTwapLive, oracleTwapLive, interpEst, interpEst];
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
exports.calculateLongShortFundingRateAndLiveTwaps = calculateLongShortFundingRateAndLiveTwaps;
|
|
208
|
+
/**
|
|
209
|
+
*
|
|
210
|
+
* @param market
|
|
211
|
+
* @returns Estimated fee pool size
|
|
212
|
+
*/
|
|
213
|
+
function calculateFundingPool(market) {
|
|
214
|
+
// todo
|
|
215
|
+
const totalFeeLB = market.amm.totalFee.div(new anchor_1.BN(2));
|
|
216
|
+
const feePool = anchor_1.BN.max(numericConstants_1.ZERO, market.amm.totalFeeMinusDistributions
|
|
217
|
+
.sub(totalFeeLB)
|
|
218
|
+
.mul(new anchor_1.BN(2))
|
|
219
|
+
.div(new anchor_1.BN(3)));
|
|
220
|
+
return feePool;
|
|
221
|
+
}
|
|
222
|
+
exports.calculateFundingPool = calculateFundingPool;
|
|
223
|
+
//# sourceMappingURL=funding.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"funding.js","sourceRoot":"","sources":["funding.ts"],"names":[],"mappings":";;;AAAA,kDAA2C;AAC3C,oEAKuC;AAEvC,qCAA8C;AAG9C;;;;;;GAMG;AACI,KAAK,UAAU,gCAAgC,CACrD,MAAc,EACd,eAAgC,EAChC,mBAAuB,IAAI,WAAE,CAAC,CAAC,CAAC;IAEhC,mBAAmB;IACnB,aAAa;IACb,aAAa;IACb,2BAA2B;IAC3B,MAAM,aAAa,GAAG,IAAI,WAAE,CAAC,IAAI,CAAC,CAAC;IACnC,MAAM,UAAU,GAAG,IAAI,WAAE,CAAC,EAAE,CAAC,CAAC;IAE9B,IAAI,CAAC,MAAM,CAAC,WAAW,EAAE;QACxB,OAAO,CAAC,uBAAI,EAAE,uBAAI,EAAE,uBAAI,EAAE,uBAAI,EAAE,uBAAI,CAAC,CAAC;KACtC;IAED,MAAM,OAAO,GAAG,IAAI,WAAE,CAAC,MAAM,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;IAEjD,wDAAwD;IACxD,MAAM,GAAG,GAAG,IAAI,WAAE,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IACnD,MAAM,mBAAmB,GAAG,GAAG,CAAC,GAAG,CAAC,MAAM,C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,CAAC;KAC/D;SAAM;QACN,OAAO,CAAC,YAAY,EAAE,cAAc,EAAE,SAAS,EAAE,SAAS,CAAC,CAAC;KAC5D;AACF,CAAC;AAnBD,8FAmBC;AAED;;;;GAIG;AACH,SAAgB,oBAAoB,CAAC,MAAc;IAClD,OAAO;IACP,MAAM,UAAU,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,WAAE,CAAC,CAAC,CAAC,CAAC,CAAC;IACtD,MAAM,OAAO,GAAG,WAAE,CAAC,GAAG,CACrB,uBAAI,EACJ,MAAM,CAAC,GAAG,CAAC,0BAA0B;SACnC,GAAG,CAAC,UAAU,CAAC;SACf,GAAG,CAAC,IAAI,WAAE,CAAC,CAAC,CAAC,CAAC;SACd,GAAG,CAAC,IAAI,WAAE,CAAC,CAAC,CAAC,CAAC,CAChB,CAAC;IACF,OAAO,OAAO,CAAC;AAChB,CAAC;AAXD,oDAWC"}
|
package/src/math/funding.ts
CHANGED
|
@@ -43,9 +43,13 @@ export async function calculateAllEstimatedFundingRate(
|
|
|
43
43
|
const lastMarkPriceTwapTs = market.amm.lastMarkPriceTwapTs;
|
|
44
44
|
|
|
45
45
|
const timeSinceLastMarkChange = now.sub(lastMarkPriceTwapTs);
|
|
46
|
-
const markTwapTimeSinceLastUpdate =
|
|
46
|
+
const markTwapTimeSinceLastUpdate =
|
|
47
|
+
BN.max(
|
|
47
48
|
secondsInHour,
|
|
48
|
-
|
|
49
|
+
BN.max(
|
|
50
|
+
ZERO,
|
|
51
|
+
secondsInHour.sub(timeSinceLastMarkChange)
|
|
52
|
+
)
|
|
49
53
|
);
|
|
50
54
|
const baseAssetPriceWithMantissa = calculateMarkPrice(market);
|
|
51
55
|
|
|
@@ -59,6 +63,8 @@ export async function calculateAllEstimatedFundingRate(
|
|
|
59
63
|
const lastOracleTwapWithMantissa = market.amm.lastOraclePriceTwap;
|
|
60
64
|
const lastOraclePriceTwapTs = market.amm.lastOraclePriceTwapTs;
|
|
61
65
|
|
|
66
|
+
const oracleInvalidDuration = BN.max(ZERO, lastMarkPriceTwapTs.sub(lastOraclePriceTwapTs));
|
|
67
|
+
|
|
62
68
|
const timeSinceLastOracleTwapUpdate = now.sub(lastOraclePriceTwapTs);
|
|
63
69
|
const oracleTwapTimeSinceLastUpdate = BN.max(
|
|
64
70
|
secondsInHour,
|
|
@@ -80,7 +86,8 @@ export async function calculateAllEstimatedFundingRate(
|
|
|
80
86
|
oracleTwapWithMantissa = oracleTwapTimeSinceLastUpdate
|
|
81
87
|
.mul(lastOracleTwapWithMantissa)
|
|
82
88
|
.add(timeSinceLastMarkChange.mul(oraclePrice))
|
|
83
|
-
.
|
|
89
|
+
.add(oracleInvalidDuration.mul(lastMarkTwapWithMantissa))
|
|
90
|
+
.div(timeSinceLastMarkChange.add(oracleTwapTimeSinceLastUpdate).add(oracleInvalidDuration));
|
|
84
91
|
}
|
|
85
92
|
|
|
86
93
|
const twapSpread = lastMarkTwapWithMantissa.sub(lastOracleTwapWithMantissa);
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.calculateInsuranceFundSize = void 0;
|
|
4
|
+
const __1 = require("../");
|
|
5
|
+
/**
|
|
6
|
+
* In the case of a levered loss, the exchange first pays out undistributed fees and then the insurance fund.
|
|
7
|
+
* Thus the de facto size of the insurance fund is the amount in the insurance vault plus the sum of each markets
|
|
8
|
+
* undistributed fees.
|
|
9
|
+
*
|
|
10
|
+
* @param connection
|
|
11
|
+
* @param state
|
|
12
|
+
* @param marketsAccount
|
|
13
|
+
* @returns Precision : QUOTE_ASSET_PRECISION
|
|
14
|
+
*/
|
|
15
|
+
async function calculateInsuranceFundSize(connection, state, marketsAccount) {
|
|
16
|
+
const insuranceVaultPublicKey = state.insuranceVault;
|
|
17
|
+
const insuranceVaultAmount = new __1.BN((await connection.getTokenAccountBalance(insuranceVaultPublicKey)).value.amount);
|
|
18
|
+
return marketsAccount.markets.reduce((insuranceVaultAmount, market) => {
|
|
19
|
+
return insuranceVaultAmount.add(market.amm.totalFee.div(new __1.BN(2)));
|
|
20
|
+
}, insuranceVaultAmount);
|
|
21
|
+
}
|
|
22
|
+
exports.calculateInsuranceFundSize = calculateInsuranceFundSize;
|
|
23
|
+
//# sourceMappingURL=insuranceFund.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"insuranceFund.js","sourceRoot":"","sources":["insuranceFund.ts"],"names":[],"mappings":";;;AACA,2BAAyB;AAGzB;;;;;;;;;GASG;AACI,KAAK,UAAU,0BAA0B,CAC/C,UAAsB,EACtB,KAAmB,EACnB,cAA8B;IAE9B,MAAM,uBAAuB,GAAG,KAAK,CAAC,cAAc,CAAC;IACrD,MAAM,oBAAoB,GAAG,IAAI,MAAE,CAClC,CACC,MAAM,UAAU,CAAC,sBAAsB,CAAC,uBAAuB,CAAC,CAChE,CAAC,KAAK,CAAC,MAAM,CACd,CAAC;IACF,OAAO,cAAc,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,oBAAoB,EAAE,MAAM,EAAE,EAAE;QACrE,OAAO,oBAAoB,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,MAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACrE,CAAC,EAAE,oBAAoB,CAAC,CAAC;AAC1B,CAAC;AAdD,gEAcC"}
|
package/src/math/orders.ts
CHANGED
|
@@ -89,17 +89,20 @@ export function isOrderReduceOnly(
|
|
|
89
89
|
user.getEmptyPosition(order.marketIndex);
|
|
90
90
|
|
|
91
91
|
// if position is long and order is long
|
|
92
|
-
if (
|
|
92
|
+
if (
|
|
93
|
+
position.baseAssetAmount.gte(ZERO) &&
|
|
94
|
+
isVariant(order.direction, 'long')
|
|
95
|
+
) {
|
|
93
96
|
return false;
|
|
94
97
|
}
|
|
95
98
|
|
|
96
99
|
// if position is short and order is short
|
|
97
100
|
if (
|
|
98
|
-
position.baseAssetAmount.
|
|
101
|
+
position.baseAssetAmount.lte(ZERO) &&
|
|
99
102
|
isVariant(order.direction, 'short')
|
|
100
103
|
) {
|
|
101
104
|
return false;
|
|
102
105
|
}
|
|
103
106
|
|
|
104
|
-
return
|
|
107
|
+
return true;
|
|
105
108
|
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.isEmptyPosition = exports.positionCurrentDirection = exports.findDirectionToClose = exports.calculateEntryPrice = exports.calculatePositionFundingPNL = exports.calculatePositionPNL = exports.calculateBaseAssetValue = void 0;
|
|
4
|
+
const __1 = require("../");
|
|
5
|
+
const numericConstants_1 = require("../constants/numericConstants");
|
|
6
|
+
const types_1 = require("../types");
|
|
7
|
+
const amm_1 = require("./amm");
|
|
8
|
+
/**
|
|
9
|
+
* calculateBaseAssetValue
|
|
10
|
+
* = market value of closing entire position
|
|
11
|
+
* @param market
|
|
12
|
+
* @param userPosition
|
|
13
|
+
* @returns Base Asset Value. : Precision QUOTE_PRECISION
|
|
14
|
+
*/
|
|
15
|
+
function calculateBaseAssetValue(market, userPosition) {
|
|
16
|
+
if (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
|
|
17
|
+
return numericConstants_1.ZERO;
|
|
18
|
+
}
|
|
19
|
+
const directionToClose = findDirectionToClose(userPosition);
|
|
20
|
+
const [newQuoteAssetReserve, _] = (0, amm_1.calculateAmmReservesAfterSwap)(market.amm, 'base', userPosition.baseAssetAmount.abs(), (0, amm_1.getSwapDirection)('base', directionToClose));
|
|
21
|
+
switch (directionToClose) {
|
|
22
|
+
case types_1.PositionDirection.SHORT:
|
|
23
|
+
return market.amm.quoteAssetReserve
|
|
24
|
+
.sub(newQuoteAssetReserve)
|
|
25
|
+
.mul(market.amm.pegMultiplier)
|
|
26
|
+
.div(numericConstants_1.AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO);
|
|
27
|
+
case types_1.PositionDirection.LONG:
|
|
28
|
+
return newQuoteAssetReserve
|
|
29
|
+
.sub(market.amm.quoteAssetReserve)
|
|
30
|
+
.mul(market.amm.pegMultiplier)
|
|
31
|
+
.div(numericConstants_1.AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO)
|
|
32
|
+
.add(numericConstants_1.ONE);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
exports.calculateBaseAssetValue = calculateBaseAssetValue;
|
|
36
|
+
/**
|
|
37
|
+
* calculatePositionPNL
|
|
38
|
+
* = BaseAssetAmount * (Avg Exit Price - Avg Entry Price)
|
|
39
|
+
* @param market
|
|
40
|
+
* @param marketPosition
|
|
41
|
+
* @param withFunding (adds unrealized funding payment pnl to result)
|
|
42
|
+
* @returns BaseAssetAmount : Precision QUOTE_PRECISION
|
|
43
|
+
*/
|
|
44
|
+
function calculatePositionPNL(market, marketPosition, withFunding = false) {
|
|
45
|
+
if (marketPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
|
|
46
|
+
return numericConstants_1.ZERO;
|
|
47
|
+
}
|
|
48
|
+
const baseAssetValue = calculateBaseAssetValue(market, marketPosition);
|
|
49
|
+
let pnl;
|
|
50
|
+
if (marketPosition.baseAssetAmount.gt(numericConstants_1.ZERO)) {
|
|
51
|
+
pnl = baseAssetValue.sub(marketPosition.quoteAssetAmount);
|
|
52
|
+
}
|
|
53
|
+
else {
|
|
54
|
+
pnl = marketPosition.quoteAssetAmount.sub(baseAssetValue);
|
|
55
|
+
}
|
|
56
|
+
if (withFunding) {
|
|
57
|
+
const fundingRatePnL = calculatePositionFundingPNL(market, marketPosition).div(numericConstants_1.PRICE_TO_QUOTE_PRECISION);
|
|
58
|
+
pnl = pnl.add(fundingRatePnL);
|
|
59
|
+
}
|
|
60
|
+
return pnl;
|
|
61
|
+
}
|
|
62
|
+
exports.calculatePositionPNL = calculatePositionPNL;
|
|
63
|
+
/**
|
|
64
|
+
*
|
|
65
|
+
* @param market
|
|
66
|
+
* @param marketPosition
|
|
67
|
+
* @returns // TODO-PRECISION
|
|
68
|
+
*/
|
|
69
|
+
function calculatePositionFundingPNL(market, marketPosition) {
|
|
70
|
+
if (marketPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
|
|
71
|
+
return numericConstants_1.ZERO;
|
|
72
|
+
}
|
|
73
|
+
let ammCumulativeFundingRate;
|
|
74
|
+
if (marketPosition.baseAssetAmount.gt(numericConstants_1.ZERO)) {
|
|
75
|
+
ammCumulativeFundingRate = market.amm.cumulativeFundingRateLong;
|
|
76
|
+
}
|
|
77
|
+
else {
|
|
78
|
+
ammCumulativeFundingRate = market.amm.cumulativeFundingRateShort;
|
|
79
|
+
}
|
|
80
|
+
const perPositionFundingRate = ammCumulativeFundingRate
|
|
81
|
+
.sub(marketPosition.lastCumulativeFundingRate)
|
|
82
|
+
.mul(marketPosition.baseAssetAmount)
|
|
83
|
+
.div(numericConstants_1.AMM_RESERVE_PRECISION)
|
|
84
|
+
.div(numericConstants_1.FUNDING_PAYMENT_PRECISION)
|
|
85
|
+
.mul(new __1.BN(-1));
|
|
86
|
+
return perPositionFundingRate;
|
|
87
|
+
}
|
|
88
|
+
exports.calculatePositionFundingPNL = calculatePositionFundingPNL;
|
|
89
|
+
/**
|
|
90
|
+
*
|
|
91
|
+
* @param userPosition
|
|
92
|
+
* @returns Precision: MARK_PRICE_PRECISION (10^10)
|
|
93
|
+
*/
|
|
94
|
+
function calculateEntryPrice(userPosition) {
|
|
95
|
+
if (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
|
|
96
|
+
return numericConstants_1.ZERO;
|
|
97
|
+
}
|
|
98
|
+
return userPosition.quoteAssetAmount
|
|
99
|
+
.mul(numericConstants_1.MARK_PRICE_PRECISION)
|
|
100
|
+
.mul(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
|
|
101
|
+
.div(userPosition.baseAssetAmount)
|
|
102
|
+
.abs();
|
|
103
|
+
}
|
|
104
|
+
exports.calculateEntryPrice = calculateEntryPrice;
|
|
105
|
+
function findDirectionToClose(userPosition) {
|
|
106
|
+
return userPosition.baseAssetAmount.gt(numericConstants_1.ZERO)
|
|
107
|
+
? types_1.PositionDirection.SHORT
|
|
108
|
+
: types_1.PositionDirection.LONG;
|
|
109
|
+
}
|
|
110
|
+
exports.findDirectionToClose = findDirectionToClose;
|
|
111
|
+
function positionCurrentDirection(userPosition) {
|
|
112
|
+
return userPosition.baseAssetAmount.gte(numericConstants_1.ZERO)
|
|
113
|
+
? types_1.PositionDirection.LONG
|
|
114
|
+
: types_1.PositionDirection.SHORT;
|
|
115
|
+
}
|
|
116
|
+
exports.positionCurrentDirection = positionCurrentDirection;
|
|
117
|
+
function isEmptyPosition(userPosition) {
|
|
118
|
+
return (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO) && userPosition.openOrders.eq(numericConstants_1.ZERO));
|
|
119
|
+
}
|
|
120
|
+
exports.isEmptyPosition = isEmptyPosition;
|
|
121
|
+
//# sourceMappingURL=position.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"position.js","sourceRoot":"","sources":["position.ts"],"names":[],"mappings":";;;AAAA,2BAAyB;AACzB,oEASuC;AACvC,oCAAmE;AACnE,+BAAwE;AAExE;;;;;;GAMG;AACH,SAAgB,uBAAuB,CACtC,MAAc,EACd,YAA0B;IAE1B,IAAI,YAAY,CAAC,eAAe,CAAC,EAAE,CAAC,uBAAI,CAAC,EAAE;QAC1C,OAAO,uBAAI,CAAC;KACZ;IAED,MAAM,gBAAgB,GAAG,oBAAoB,CAAC,YAAY,CAAC,CAAC;IAE5D,MAAM,CAAC,oBAAoB,EAAE,CAAC,CAAC,GAAG,IAAA,mCAA6B,EAC9D,MAAM,CAAC,GAAG,EACV,MAAM,EACN,YAAY,CAAC,eAAe,CAAC,GAAG,EAAE,EAClC,IAAA,sBAAgB,EAAC,MAAM,EAAE,gBAAgB,CAAC,CAC1C,CAAC;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AiB,CAAC,IAAI,CAAC;AAC3B,CAAC;AAND,oDAMC;AAED,SAAgB,wBAAwB,CACvC,YAA0B;IAE1B,OAAO,YAAY,CAAC,eAAe,CAAC,GAAG,CAAC,uBAAI,CAAC;QAC5C,CAAC,CAAC,yBAAiB,CAAC,IAAI;QACxB,CAAC,CAAC,yBAAiB,CAAC,KAAK,CAAC;AAC5B,CAAC;AAND,4DAMC;AAED,SAAgB,eAAe,CAAC,YAA0B;IACzD,OAAO,CACN,YAAY,CAAC,eAAe,CAAC,EAAE,CAAC,uBAAI,CAAC,IAAI,YAAY,CAAC,UAAU,CAAC,EAAE,CAAC,uBAAI,CAAC,CACzE,CAAC;AACH,CAAC;AAJD,0CAIC"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.squareRootBN = void 0;
|
|
4
|
+
const __1 = require("../");
|
|
5
|
+
const squareRootBN = (n, closeness = new __1.BN(1)) => {
|
|
6
|
+
// Assuming the sqrt of n as n only
|
|
7
|
+
let x = n;
|
|
8
|
+
// The closed guess will be stored in the root
|
|
9
|
+
let root;
|
|
10
|
+
// To count the number of iterations
|
|
11
|
+
let count = 0;
|
|
12
|
+
const TWO = new __1.BN(2);
|
|
13
|
+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
14
|
+
while (count < Number.MAX_SAFE_INTEGER) {
|
|
15
|
+
count++;
|
|
16
|
+
// Calculate more closed x
|
|
17
|
+
root = x.add(n.div(x)).div(TWO);
|
|
18
|
+
// Check for closeness
|
|
19
|
+
if (x.sub(root).abs().lte(closeness))
|
|
20
|
+
break;
|
|
21
|
+
// Update root
|
|
22
|
+
x = root;
|
|
23
|
+
}
|
|
24
|
+
return root;
|
|
25
|
+
};
|
|
26
|
+
exports.squareRootBN = squareRootBN;
|
|
27
|
+
//# sourceMappingURL=utils.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils.js","sourceRoot":"","sources":["utils.ts"],"names":[],"mappings":";;;AAAA,2BAAyB;AAElB,MAAM,YAAY,GAAG,CAAC,CAAC,EAAE,SAAS,GAAG,IAAI,MAAE,CAAC,CAAC,CAAC,EAAE,EAAE;IACxD,mCAAmC;IACnC,IAAI,CAAC,GAAG,CAAC,CAAC;IAEV,8CAA8C;IAC9C,IAAI,IAAI,CAAC;IAET,oCAAoC;IACpC,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,MAAM,GAAG,GAAG,IAAI,MAAE,CAAC,CAAC,CAAC,CAAC;IAEtB,6DAA6D;IAC7D,OAAO,KAAK,GAAG,MAAM,CAAC,gBAAgB,EAAE;QACvC,KAAK,EAAE,CAAC;QAER,0BAA0B;QAC1B,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAEhC,sBAAsB;QACtB,IAAI,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,SAAS,CAAC;YAAE,MAAM;QAE5C,cAAc;QACd,CAAC,GAAG,IAAI,CAAC;KACT;IAED,OAAO,IAAI,CAAC;AACb,CAAC,CAAC;AA1BW,QAAA,YAAY,gBA0BvB"}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.SwitchboardClient = void 0;
|
|
7
|
+
const switchboard_v2_1 = require("@switchboard-xyz/switchboard-v2");
|
|
8
|
+
const web3_js_1 = require("@solana/web3.js");
|
|
9
|
+
const anchor_1 = require("@project-serum/anchor");
|
|
10
|
+
const numericConstants_1 = require("../constants/numericConstants");
|
|
11
|
+
const wallet_1 = require("../wallet");
|
|
12
|
+
const switchboard_v2_json_1 = __importDefault(require("../idl/switchboard_v2.json"));
|
|
13
|
+
// cache switchboard program for every client object since itll always be the same
|
|
14
|
+
const programMap = new Map();
|
|
15
|
+
class SwitchboardClient {
|
|
16
|
+
constructor(connection, env) {
|
|
17
|
+
this.connection = connection;
|
|
18
|
+
this.env = env;
|
|
19
|
+
}
|
|
20
|
+
async getOraclePriceData(pricePublicKey) {
|
|
21
|
+
const accountInfo = await this.connection.getAccountInfo(pricePublicKey);
|
|
22
|
+
return this.getOraclePriceDataFromBuffer(accountInfo.data);
|
|
23
|
+
}
|
|
24
|
+
async getOraclePriceDataFromBuffer(buffer) {
|
|
25
|
+
const program = await this.getProgram();
|
|
26
|
+
const aggregatorAccountData = program.account.aggregatorAccountData.coder.accounts.decode('AggregatorAccountData', buffer);
|
|
27
|
+
const price = convertSwitchboardDecimal(aggregatorAccountData.latestConfirmedRound.result);
|
|
28
|
+
const confidence = convertSwitchboardDecimal(aggregatorAccountData.latestConfirmedRound
|
|
29
|
+
.stdDeviation);
|
|
30
|
+
const slot = aggregatorAccountData.latestConfirmedRound.roundOpenSlot;
|
|
31
|
+
return {
|
|
32
|
+
price,
|
|
33
|
+
slot,
|
|
34
|
+
confidence,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
async getProgram() {
|
|
38
|
+
if (programMap.has(this.env)) {
|
|
39
|
+
return programMap.get(this.env);
|
|
40
|
+
}
|
|
41
|
+
const program = await getSwitchboardProgram(this.env, this.connection);
|
|
42
|
+
programMap.set(this.env, program);
|
|
43
|
+
return program;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
exports.SwitchboardClient = SwitchboardClient;
|
|
47
|
+
async function getSwitchboardProgram(env, connection) {
|
|
48
|
+
const DEFAULT_KEYPAIR = web3_js_1.Keypair.fromSeed(new Uint8Array(32).fill(1));
|
|
49
|
+
const programId = (0, switchboard_v2_1.getSwitchboardPid)(env);
|
|
50
|
+
const wallet = new wallet_1.Wallet(DEFAULT_KEYPAIR);
|
|
51
|
+
const provider = new anchor_1.Provider(connection, wallet, {});
|
|
52
|
+
return new anchor_1.Program(switchboard_v2_json_1.default, programId, provider);
|
|
53
|
+
}
|
|
54
|
+
function convertSwitchboardDecimal(switchboardDecimal) {
|
|
55
|
+
const switchboardPrecision = numericConstants_1.TEN.pow(new anchor_1.BN(switchboardDecimal.scale));
|
|
56
|
+
return switchboardDecimal.mantissa
|
|
57
|
+
.mul(numericConstants_1.MARK_PRICE_PRECISION)
|
|
58
|
+
.div(switchboardPrecision);
|
|
59
|
+
}
|
|
60
|
+
//# sourceMappingURL=switchboardClient.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"switchboardClient.js","sourceRoot":"","sources":["switchboardClient.ts"],"names":[],"mappings":";;;;;;AAAA,oEAGyC;AACzC,6CAAiE;AAEjE,kDAAmE;AACnE,oEAA0E;AAE1E,sCAAmC;AACnC,qFAA0D;AAE1D,kFAAkF;AAClF,MAAM,UAAU,GAAG,IAAI,GAAG,EAAmB,CAAC;AAE9C,MAAa,iBAAiB;IAI7B,YAAmB,UAAsB,EAAE,GAAa;QACvD,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;IAChB,CAAC;IAEM,KAAK,CAAC,kBAAkB,CAC9B,cAAyB;QAEzB,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC;QACzE,OAAO,IAAI,CAAC,4BAA4B,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;IAC5D,CAAC;IAEM,KAAK,CAAC,4BAA4B,CACxC,MAAc;QAEd,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,UAAU,EAAE,CAAC;QAExC,MAAM,qBAAqB,GAC1B,OAAO,CAAC,OAAO,CAAC,qBAAqB,CAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,CAC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BAAsC;IACxE,MAAM,oBAAoB,GAAG,sBAAG,CAAC,GAAG,CAAC,IAAI,WAAE,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC,CAAC;IACvE,OAAO,kBAAkB,CAAC,QAAQ;SAChC,GAAG,CAAC,uCAAoB,CAAC;SACzB,GAAG,CAAC,oBAAoB,CAAC,CAAC;AAC7B,CAAC"}
|
package/src/orders.ts
CHANGED
|
@@ -199,7 +199,14 @@ export function calculateAmountToTradeForLimit(
|
|
|
199
199
|
'Cant calculate limit price for oracle offset oracle without OraclePriceData'
|
|
200
200
|
);
|
|
201
201
|
}
|
|
202
|
-
|
|
202
|
+
const floatingPrice = oraclePriceData.price.add(order.oraclePriceOffset);
|
|
203
|
+
if (order.postOnly) {
|
|
204
|
+
limitPrice = isVariant(order.direction, 'long')
|
|
205
|
+
? BN.min(order.price, floatingPrice)
|
|
206
|
+
: BN.max(order.price, floatingPrice);
|
|
207
|
+
} else {
|
|
208
|
+
limitPrice = floatingPrice;
|
|
209
|
+
}
|
|
203
210
|
}
|
|
204
211
|
|
|
205
212
|
const [maxAmountToTrade, direction] = calculateMaxBaseAssetAmountToTrade(
|
|
@@ -298,5 +305,19 @@ export function calculateBaseAssetAmountUserCanExecute(
|
|
|
298
305
|
: SwapDirection.REMOVE
|
|
299
306
|
);
|
|
300
307
|
|
|
301
|
-
|
|
308
|
+
let baseAssetAmount = baseAssetReservesBefore.sub(baseAssetReservesAfter).abs();
|
|
309
|
+
if (order.reduceOnly) {
|
|
310
|
+
const position =
|
|
311
|
+
user.getUserPosition(order.marketIndex) ||
|
|
312
|
+
user.getEmptyPosition(order.marketIndex);
|
|
313
|
+
if (isVariant(order.direction, 'long') && position.baseAssetAmount.gte(ZERO)) {
|
|
314
|
+
baseAssetAmount = ZERO;
|
|
315
|
+
} else if (isVariant(order.direction, 'short') && position.baseAssetAmount.lte(ZERO)) {
|
|
316
|
+
baseAssetAmount = ZERO;
|
|
317
|
+
} else {
|
|
318
|
+
BN.min(baseAssetAmount, position.baseAssetAmount.abs());
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
return baseAssetAmount;
|
|
302
323
|
}
|
|
@@ -0,0 +1,39 @@
|
|
|
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;
|
|
39
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":";;;AAAA,iDAAoE;AACpE,6CAA4C;AAE5C,SAAgB,iBAAiB,CAAC,IAAY;IAC7C,MAAM,WAAW,GAAG,yBAAa,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAC/C,WAAW,CAAC,IAAI,GAAG,IAAI,mBAAS,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;IACnD,WAAW,CAAC,KAAK,GAAG,IAAI,mBAAS,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;IACrD,WAAW,CAAC,MAAM,GAAG,eAAG,CAAC,UAAU,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;IAExD,IAAI,WAAW,CAAC,cAAc,KAAK,CAAC,EAAE;QACrC,WAAW,CAAC,QAAQ,GAAG,IAAI,CAAC;QAC5B,mCAAmC;QACnC,WAAW,CAAC,eAAe,GAAG,IAAI,eAAG,CAAC,CAAC,CAAC,CAAC;KACzC;SAAM;QACN,WAAW,CAAC,QAAQ,GAAG,IAAI,mBAAS,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;QAC3D,WAAW,CAAC,eAAe,GAAG,eAAG,CAAC,UAAU,CAAC,WAAW,CAAC,eAAe,CAAC,CAAC;KAC1E;IAED,WAAW,CAAC,aAAa,GAAG,WAAW,CAAC,KAAK,KAAK,CAAC,CAAC;IACpD,WAAW,CAAC,QAAQ,GAAG,WAAW,CAAC,KAAK,KAAK,CAAC,CAAC;IAE/C,IAAI,WAAW,CAAC,cAAc,KAAK,CAAC,EAAE;QACrC,WAAW,CAAC,iBAAiB,GAAG,eAAG,CAAC,UAAU,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;QACrE,WAAW,CAAC,QAAQ,GAAG,IAAI,CAAC;KAC5B;SAAM;QACN,WAAW,CAAC,iBAAiB,GAAG,IAAI,CAAC;QACrC,WAAW,CAAC,QAAQ,GAAG,KAAK,CAAC;KAC7B;IAED,IAAI,WAAW,CAAC,oBAAoB,KAAK,CAAC,EAAE;QAC3C,WAAW,CAAC,cAAc,GAAG,IAAI,CAAC;KAClC;SAAM;QACN,WAAW,CAAC,cAAc,GAAG,IAAI,mBAAS,CAAC,WAAW,CAAC,cAAc,CAAC,CAAC;KACvE;IAED,OAAO,WAAW,CAAC;AACpB,CAAC;AAjCD,8CAiCC"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DefaultTxSender = void 0;
|
|
4
|
+
class DefaultTxSender {
|
|
5
|
+
constructor(provider) {
|
|
6
|
+
this.provider = provider;
|
|
7
|
+
}
|
|
8
|
+
send(tx, additionalSigners, opts) {
|
|
9
|
+
return this.provider.send(tx, additionalSigners, opts);
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
exports.DefaultTxSender = DefaultTxSender;
|
|
13
|
+
//# sourceMappingURL=defaultTxSender.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"defaultTxSender.js","sourceRoot":"","sources":["defaultTxSender.ts"],"names":[],"mappings":";;;AASA,MAAa,eAAe;IAG3B,YAAmB,QAAkB;QACpC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC1B,CAAC;IAED,IAAI,CACH,EAAe,EACf,iBAAiC,EACjC,IAAqB;QAErB,OAAO,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,EAAE,iBAAiB,EAAE,IAAI,CAAC,CAAC;IACxD,CAAC;CACD;AAdD,0CAcC"}
|
package/src/tx/retryTxSender.ts
CHANGED
|
@@ -227,4 +227,16 @@ export class RetryTxSender implements TxSender {
|
|
|
227
227
|
});
|
|
228
228
|
});
|
|
229
229
|
}
|
|
230
|
+
|
|
231
|
+
public addAdditionalConnection(newConnection: Connection): void {
|
|
232
|
+
const alreadyUsingConnection =
|
|
233
|
+
this.additionalConnections.filter((connection) => {
|
|
234
|
+
// @ts-ignore
|
|
235
|
+
return connection._rpcEndpoint === newConnection.rpcEndpoint;
|
|
236
|
+
}).length > 0;
|
|
237
|
+
|
|
238
|
+
if (!alreadyUsingConnection) {
|
|
239
|
+
this.additionalConnections.push(newConnection);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
230
242
|
}
|
package/src/tx/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":""}
|
package/src/tx/utils.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.wrapInTx = void 0;
|
|
4
|
+
const web3_js_1 = require("@solana/web3.js");
|
|
5
|
+
function wrapInTx(instruction) {
|
|
6
|
+
return new web3_js_1.Transaction().add(instruction);
|
|
7
|
+
}
|
|
8
|
+
exports.wrapInTx = wrapInTx;
|
|
9
|
+
//# sourceMappingURL=utils.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils.js","sourceRoot":"","sources":["utils.ts"],"names":[],"mappings":";;;AAAA,6CAAsE;AAEtE,SAAgB,QAAQ,CAAC,WAAmC;IAC3D,OAAO,IAAI,qBAAW,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;AAC3C,CAAC;AAFD,4BAEC"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.findComputeUnitConsumption = void 0;
|
|
4
|
+
async function findComputeUnitConsumption(programId, connection, txSignature, commitment = 'confirmed') {
|
|
5
|
+
const tx = await connection.getTransaction(txSignature, { commitment });
|
|
6
|
+
const computeUnits = [];
|
|
7
|
+
const regex = new RegExp(`Program ${programId.toString()} consumed ([0-9]{0,6}) of 200000 compute units`);
|
|
8
|
+
tx.meta.logMessages.forEach((logMessage) => {
|
|
9
|
+
const match = logMessage.match(regex);
|
|
10
|
+
if (match && match[1]) {
|
|
11
|
+
computeUnits.push(match[1]);
|
|
12
|
+
}
|
|
13
|
+
});
|
|
14
|
+
return computeUnits;
|
|
15
|
+
}
|
|
16
|
+
exports.findComputeUnitConsumption = findComputeUnitConsumption;
|
|
17
|
+
//# sourceMappingURL=computeUnits.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"computeUnits.js","sourceRoot":"","sources":["computeUnits.ts"],"names":[],"mappings":";;;AAEO,KAAK,UAAU,0BAA0B,CAC/C,SAAoB,EACpB,UAAsB,EACtB,WAAmB,EACnB,aAAuB,WAAW;IAElC,MAAM,EAAE,GAAG,MAAM,UAAU,CAAC,cAAc,CAAC,WAAW,EAAE,EAAE,UAAU,EAAE,CAAC,CAAC;IACxE,MAAM,YAAY,GAAG,EAAE,CAAC;IACxB,MAAM,KAAK,GAAG,IAAI,MAAM,CACvB,WAAW,SAAS,CAAC,QAAQ,EAAE,gDAAgD,CAC/E,CAAC;IACF,EAAE,CAAC,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,UAAU,EAAE,EAAE;QAC1C,MAAM,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QACtC,IAAI,KAAK,IAAI,KAAK,CAAC,CAAC,CAAC,EAAE;YACtB,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;SAC5B;IACF,CAAC,CAAC,CAAC;IACH,OAAO,YAAY,CAAC;AACrB,CAAC;AAlBD,gEAkBC"}
|
package/src/util/tps.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.estimateTps = void 0;
|
|
4
|
+
async function estimateTps(programId, connection, failed) {
|
|
5
|
+
let signatures = await connection.getSignaturesForAddress(programId, undefined, 'finalized');
|
|
6
|
+
if (failed) {
|
|
7
|
+
signatures = signatures.filter((signature) => signature.err);
|
|
8
|
+
}
|
|
9
|
+
const numberOfSignatures = signatures.length;
|
|
10
|
+
if (numberOfSignatures === 0) {
|
|
11
|
+
return 0;
|
|
12
|
+
}
|
|
13
|
+
return (numberOfSignatures /
|
|
14
|
+
(signatures[0].blockTime - signatures[numberOfSignatures - 1].blockTime));
|
|
15
|
+
}
|
|
16
|
+
exports.estimateTps = estimateTps;
|
|
17
|
+
//# sourceMappingURL=tps.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tps.js","sourceRoot":"","sources":["tps.ts"],"names":[],"mappings":";;;AAEO,KAAK,UAAU,WAAW,CAChC,SAAoB,EACpB,UAAsB,EACtB,MAAe;IAEf,IAAI,UAAU,GAAG,MAAM,UAAU,CAAC,uBAAuB,CACxD,SAAS,EACT,SAAS,EACT,WAAW,CACX,CAAC;IACF,IAAI,MAAM,EAAE;QACX,UAAU,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;KAC7D;IAED,MAAM,kBAAkB,GAAG,UAAU,CAAC,MAAM,CAAC;IAE7C,IAAI,kBAAkB,KAAK,CAAC,EAAE;QAC7B,OAAO,CAAC,CAAC;KACT;IAED,OAAO,CACN,kBAAkB;QAClB,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,SAAS,GAAG,UAAU,CAAC,kBAAkB,GAAG,CAAC,CAAC,CAAC,SAAS,CAAC,CACxE,CAAC;AACH,CAAC;AAxBD,kCAwBC"}
|