@drift-labs/sdk 0.1.14 → 0.1.17-master.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/README.md CHANGED
@@ -98,7 +98,7 @@ import {
98
98
  calculateTradeSlippage,
99
99
  MARK_PRICE_PRECISION,
100
100
  QUOTE_PRECISION,
101
- } from '@drift/sdk';
101
+ } from '@drift-labs/sdk';
102
102
 
103
103
  export const getTokenAddress = (
104
104
  mintAddress: string,
@@ -180,7 +180,7 @@ const main = async () => {
180
180
  clearingHouse.getMarket(solMarketInfo.marketIndex)
181
181
  );
182
182
 
183
- const formattedPrice = convertToNumber(currentMarketPrice, QUOTE_PRECISION);
183
+ const formattedPrice = convertToNumber(currentMarketPrice, MARK_PRICE_PRECISION);
184
184
 
185
185
  console.log(`Current Market Price is $${formattedPrice}`);
186
186
 
@@ -34,7 +34,7 @@ class DefaultClearingHouseAccountSubscriber {
34
34
  this.subscriptionPromise = new Promise((res) => {
35
35
  this.subscriptionPromiseResolver = res;
36
36
  });
37
- const statePublicKey = yield addresses_1.getClearingHouseStateAccountPublicKey(this.program.programId);
37
+ const statePublicKey = yield (0, addresses_1.getClearingHouseStateAccountPublicKey)(this.program.programId);
38
38
  // create and activate main state account subscription
39
39
  this.stateAccountSubscriber = new webSocketAccountSubscriber_1.WebSocketAccountSubscriber('state', this.program, statePublicKey);
40
40
  yield this.stateAccountSubscriber.subscribe((data) => {
@@ -26,7 +26,7 @@ class DefaultUserAccountSubscriber {
26
26
  if (this.isSubscribed) {
27
27
  return true;
28
28
  }
29
- const userPublicKey = yield addresses_1.getUserAccountPublicKey(this.program.programId, this.authority);
29
+ const userPublicKey = yield (0, addresses_1.getUserAccountPublicKey)(this.program.programId, this.authority);
30
30
  this.userDataAccountSubscriber = new webSocketAccountSubscriber_1.WebSocketAccountSubscriber('user', this.program, userPublicKey);
31
31
  yield this.userDataAccountSubscriber.subscribe((data) => {
32
32
  this.eventEmitter.emit('userAccountData', data);
package/lib/admin.js CHANGED
@@ -69,7 +69,7 @@ class Admin extends clearingHouse_1.ClearingHouse {
69
69
  const tradeHistory = anchor.web3.Keypair.generate();
70
70
  const liquidationHistory = anchor.web3.Keypair.generate();
71
71
  const curveHistory = anchor.web3.Keypair.generate();
72
- const [clearingHouseStatePublicKey, clearingHouseNonce] = yield addresses_1.getClearingHouseStateAccountPublicKeyAndNonce(this.program.programId);
72
+ const [clearingHouseStatePublicKey, clearingHouseNonce] = yield (0, addresses_1.getClearingHouseStateAccountPublicKeyAndNonce)(this.program.programId);
73
73
  const initializeTx = yield this.program.transaction.initialize(clearingHouseNonce, collateralVaultNonce, insuranceVaultNonce, adminControlsPrices, {
74
74
  accounts: {
75
75
  admin: this.wallet.publicKey,
@@ -166,8 +166,8 @@ class Admin extends clearingHouse_1.ClearingHouse {
166
166
  moveAmmToPrice(marketIndex, targetPrice) {
167
167
  return __awaiter(this, void 0, void 0, function* () {
168
168
  const market = this.getMarket(marketIndex);
169
- const [direction, tradeSize, _] = trade_1.calculateTargetPriceTrade(market, targetPrice);
170
- const [newQuoteAssetAmount, newBaseAssetAmount] = amm_1.calculateAmmReservesAfterSwap(market.amm, 'quote', tradeSize, amm_1.getSwapDirection('quote', direction));
169
+ const [direction, tradeSize, _] = (0, trade_1.calculateTargetPriceTrade)(market, targetPrice);
170
+ const [newQuoteAssetAmount, newBaseAssetAmount] = (0, amm_1.calculateAmmReservesAfterSwap)(market.amm, 'quote', tradeSize, (0, amm_1.getSwapDirection)('quote', direction));
171
171
  const state = this.getStateAccount();
172
172
  return yield this.program.rpc.moveAmmPrice(newBaseAssetAmount, newQuoteAssetAmount, marketIndex, {
173
173
  accounts: {
@@ -115,7 +115,7 @@ class ClearingHouse {
115
115
  if (this.statePublicKey) {
116
116
  return this.statePublicKey;
117
117
  }
118
- this.statePublicKey = yield addresses_1.getClearingHouseStateAccountPublicKey(this.program.programId);
118
+ this.statePublicKey = yield (0, addresses_1.getClearingHouseStateAccountPublicKey)(this.program.programId);
119
119
  return this.statePublicKey;
120
120
  });
121
121
  }
@@ -174,7 +174,7 @@ class ClearingHouse {
174
174
  }
175
175
  getInitializeUserInstructions() {
176
176
  return __awaiter(this, void 0, void 0, function* () {
177
- const [userPublicKey, userAccountNonce] = yield addresses_1.getUserAccountPublicKeyAndNonce(this.program.programId, this.wallet.publicKey);
177
+ const [userPublicKey, userAccountNonce] = yield (0, addresses_1.getUserAccountPublicKeyAndNonce)(this.program.programId, this.wallet.publicKey);
178
178
  const remainingAccounts = [];
179
179
  const optionalAccounts = {
180
180
  whitelistToken: false,
@@ -213,7 +213,7 @@ class ClearingHouse {
213
213
  if (this.userAccountPublicKey) {
214
214
  return this.userAccountPublicKey;
215
215
  }
216
- this.userAccountPublicKey = yield addresses_1.getUserAccountPublicKey(this.program.programId, this.wallet.publicKey);
216
+ this.userAccountPublicKey = yield (0, addresses_1.getUserAccountPublicKey)(this.program.programId, this.wallet.publicKey);
217
217
  return this.userAccountPublicKey;
218
218
  });
219
219
  }
@@ -303,7 +303,7 @@ class ClearingHouse {
303
303
  }
304
304
  withdrawCollateral(amount, collateralAccountPublicKey) {
305
305
  return __awaiter(this, void 0, void 0, function* () {
306
- return this.txSender.send(utils_1.wrapInTx(yield this.getWithdrawCollateralIx(amount, collateralAccountPublicKey)), [], this.opts);
306
+ return this.txSender.send((0, utils_1.wrapInTx)(yield this.getWithdrawCollateralIx(amount, collateralAccountPublicKey)), [], this.opts);
307
307
  });
308
308
  }
309
309
  getWithdrawCollateralIx(amount, collateralAccountPublicKey) {
@@ -332,7 +332,7 @@ class ClearingHouse {
332
332
  }
333
333
  openPosition(direction, amount, marketIndex, limitPrice, discountToken, referrer) {
334
334
  return __awaiter(this, void 0, void 0, function* () {
335
- return yield this.txSender.send(utils_1.wrapInTx(yield this.getOpenPositionIx(direction, amount, marketIndex, limitPrice, discountToken, referrer)), [], this.opts);
335
+ return yield this.txSender.send((0, utils_1.wrapInTx)(yield this.getOpenPositionIx(direction, amount, marketIndex, limitPrice, discountToken, referrer)), [], this.opts);
336
336
  });
337
337
  }
338
338
  getOpenPositionIx(direction, amount, marketIndex, limitPrice, discountToken, referrer) {
@@ -390,7 +390,7 @@ class ClearingHouse {
390
390
  */
391
391
  closePosition(marketIndex, discountToken, referrer) {
392
392
  return __awaiter(this, void 0, void 0, function* () {
393
- return yield this.txSender.send(utils_1.wrapInTx(yield this.getClosePositionIx(marketIndex, discountToken, referrer)), [], this.opts);
393
+ return yield this.txSender.send((0, utils_1.wrapInTx)(yield this.getClosePositionIx(marketIndex, discountToken, referrer)), [], this.opts);
394
394
  });
395
395
  }
396
396
  getClosePositionIx(marketIndex, discountToken, referrer) {
@@ -438,7 +438,7 @@ class ClearingHouse {
438
438
  }
439
439
  liquidate(liquidateeUserAccountPublicKey) {
440
440
  return __awaiter(this, void 0, void 0, function* () {
441
- return this.txSender.send(utils_1.wrapInTx(yield this.getLiquidateIx(liquidateeUserAccountPublicKey)), [], this.opts);
441
+ return this.txSender.send((0, utils_1.wrapInTx)(yield this.getLiquidateIx(liquidateeUserAccountPublicKey)), [], this.opts);
442
442
  });
443
443
  }
444
444
  getLiquidateIx(liquidateeUserAccountPublicKey) {
@@ -482,7 +482,7 @@ class ClearingHouse {
482
482
  }
483
483
  updateFundingRate(oracle, marketIndex) {
484
484
  return __awaiter(this, void 0, void 0, function* () {
485
- return this.txSender.send(utils_1.wrapInTx(yield this.getUpdateFundingRateIx(oracle, marketIndex)), [], this.opts);
485
+ return this.txSender.send((0, utils_1.wrapInTx)(yield this.getUpdateFundingRateIx(oracle, marketIndex)), [], this.opts);
486
486
  });
487
487
  }
488
488
  getUpdateFundingRateIx(oracle, marketIndex) {
@@ -500,7 +500,7 @@ class ClearingHouse {
500
500
  }
501
501
  settleFundingPayment(userAccount, userPositionsAccount) {
502
502
  return __awaiter(this, void 0, void 0, function* () {
503
- return this.txSender.send(utils_1.wrapInTx(yield this.getSettleFundingPaymentIx(userAccount, userPositionsAccount)), [], this.opts);
503
+ return this.txSender.send((0, utils_1.wrapInTx)(yield this.getSettleFundingPaymentIx(userAccount, userPositionsAccount)), [], this.opts);
504
504
  });
505
505
  }
506
506
  getSettleFundingPaymentIx(userAccount, userPositionsAccount) {
@@ -1 +1 @@
1
- {"version":3,"file":"clearingHouseUser.d.ts","sourceRoot":"","sources":["../src/clearingHouseUser.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,MAAM,OAAO,CAAC;AACvB,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AACtC,OAAO,kBAAkB,MAAM,4BAA4B,CAAC;AAC5D,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAC;AAc1E,OAAO,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAE5E,OAAO,EAKN,iBAAiB,EAEjB,MAAM,GAAG,CAAC;AAGX,qBAAa,iBAAiB;IAC7B,aAAa,EAAE,aAAa,CAAC;IAC7B,SAAS,EAAE,SAAS,CAAC;IACrB,iBAAiB,EAAE,qBAAqB,CAAC;IACzC,oBAAoB,CAAC,EAAE,SAAS,CAAC;IACjC,YAAY,UAAS;IACrB,YAAY,EAAE,kBAAkB,CAAC,YAAY,EAAE,iBAAiB,CAAC,CAAC;WAEpD,IAAI,CACjB,aAAa,EAAE,aAAa,EAC5B,SAAS,EAAE,SAAS,GAClB,iBAAiB;gBASnB,aAAa,EAAE,aAAa,EAC5B,SAAS,EAAE,SAAS,EACpB,iBAAiB,EAAE,qBAAqB;IAQzC;;;OAGG;IACU,SAAS,IAAI,OAAO,CAAC,OAAO,CAAC;IAQ1C;;OAEG;IACU,aAAa,IAAI,OAAO,CAAC,IAAI,CAAC;IAI9B,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC;IAKlC,cAAc,IAAI,WAAW;IAI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
85
85
  return this.userAccountPublicKey;
86
86
  }
87
- this.userAccountPublicKey = yield addresses_1.getUserAccountPublicKey(this.clearingHouse.program.programId, this.authority);
87
+ this.userAccountPublicKey = yield (0, addresses_1.getUserAccountPublicKey)(this.clearingHouse.program.programId, this.authority);
88
88
  return this.userAccountPublicKey;
89
89
  });
90
90
  }
@@ -122,7 +122,7 @@ class ClearingHouseUser {
122
122
  .positions.filter((pos) => marketIndex ? pos.marketIndex === marketIndex : true)
123
123
  .reduce((pnl, marketPosition) => {
124
124
  const market = this.clearingHouse.getMarket(marketPosition.marketIndex);
125
- return pnl.add(_1.calculatePositionPNL(market, marketPosition, withFunding));
125
+ return pnl.add((0, _1.calculatePositionPNL)(market, marketPosition, withFunding));
126
126
  }, numericConstants_1.ZERO);
127
127
  }
128
128
  /**
@@ -134,7 +134,7 @@ class ClearingHouseUser {
134
134
  .positions.filter((pos) => marketIndex ? pos.marketIndex === marketIndex : true)
135
135
  .reduce((pnl, marketPosition) => {
136
136
  const market = this.clearingHouse.getMarket(marketPosition.marketIndex);
137
- return pnl.add(_1.calculatePositionFundingPNL(market, marketPosition));
137
+ return pnl.add((0, _1.calculatePositionFundingPNL)(market, marketPosition));
138
138
  }, numericConstants_1.ZERO);
139
139
  }
140
140
  /**
@@ -152,7 +152,7 @@ class ClearingHouseUser {
152
152
  getTotalPositionValue() {
153
153
  return this.getUserPositionsAccount().positions.reduce((positionValue, marketPosition) => {
154
154
  const market = this.clearingHouse.getMarket(marketPosition.marketIndex);
155
- return positionValue.add(_1.calculateBaseAssetValue(market, marketPosition));
155
+ return positionValue.add((0, _1.calculateBaseAssetValue)(market, marketPosition));
156
156
  }, numericConstants_1.ZERO);
157
157
  }
158
158
  /**
@@ -162,7 +162,7 @@ class ClearingHouseUser {
162
162
  getPositionValue(marketIndex) {
163
163
  const userPosition = this.getUserPosition(marketIndex) || this.getEmptyPosition(marketIndex);
164
164
  const market = this.clearingHouse.getMarket(userPosition.marketIndex);
165
- return _1.calculateBaseAssetValue(market, userPosition);
165
+ return (0, _1.calculateBaseAssetValue)(market, userPosition);
166
166
  }
167
167
  getPositionSide(currentPosition) {
168
168
  if (currentPosition.baseAssetAmount.gt(numericConstants_1.ZERO)) {
@@ -181,10 +181,10 @@ class ClearingHouseUser {
181
181
  */
182
182
  getPositionEstimatedExitPriceAndPnl(position, amountToClose) {
183
183
  const market = this.clearingHouse.getMarket(position.marketIndex);
184
- const entryPrice = position_1.calculateEntryPrice(position);
184
+ const entryPrice = (0, position_1.calculateEntryPrice)(position);
185
185
  if (amountToClose) {
186
186
  if (amountToClose.eq(numericConstants_1.ZERO)) {
187
- return [_1.calculateMarkPrice(market), numericConstants_1.ZERO];
187
+ return [(0, _1.calculateMarkPrice)(market), numericConstants_1.ZERO];
188
188
  }
189
189
  position = {
190
190
  baseAssetAmount: amountToClose,
@@ -193,7 +193,7 @@ class ClearingHouseUser {
193
193
  quoteAssetAmount: position.quoteAssetAmount,
194
194
  };
195
195
  }
196
- const baseAssetValue = _1.calculateBaseAssetValue(market, position);
196
+ const baseAssetValue = (0, _1.calculateBaseAssetValue)(market, position);
197
197
  if (position.baseAssetAmount.eq(numericConstants_1.ZERO)) {
198
198
  return [numericConstants_1.ZERO, numericConstants_1.ZERO];
199
199
  }
@@ -300,7 +300,7 @@ class ClearingHouseUser {
300
300
 
301
301
  for 10x long, BTC down $400:
302
302
  3. (10k - 4k) / (100k - 4k) = 6k/96k => .0625 */
303
- const currentPrice = _1.calculateMarkPrice(this.clearingHouse.getMarket(targetMarket.marketIndex));
303
+ const currentPrice = (0, _1.calculateMarkPrice)(this.clearingHouse.getMarket(targetMarket.marketIndex));
304
304
  const totalCollateralUSDC = this.getTotalCollateral();
305
305
  // calculate the total position value ignoring any value from the target market of the trade
306
306
  const totalCurrentPositionValueIgnoringTargetUSDC = this.getTotalPositionValueExcludingMarket(targetMarket.marketIndex);
@@ -315,7 +315,7 @@ class ClearingHouseUser {
315
315
  quoteAssetAmount: new bn_js_1.default(0),
316
316
  };
317
317
  const market = this.clearingHouse.getMarket(proposedMarketPosition.marketIndex);
318
- const proposedMarketPositionValueUSDC = _1.calculateBaseAssetValue(market, proposedMarketPosition);
318
+ const proposedMarketPositionValueUSDC = (0, _1.calculateBaseAssetValue)(market, proposedMarketPosition);
319
319
  // total position value after trade
320
320
  const targetTotalPositionValueUSDC = totalCurrentPositionValueIgnoringTargetUSDC.add(proposedMarketPositionValueUSDC);
321
321
  let totalFreeCollateralUSDC = this.getTotalCollateral().sub(this.getTotalPositionValue()
@@ -400,7 +400,7 @@ class ClearingHouseUser {
400
400
  quoteAssetAmount: new bn_js_1.default(0),
401
401
  };
402
402
  const market = this.clearingHouse.getMarket(proposedMarketPosition.marketIndex);
403
- const proposedMarketPositionValueUSDC = _1.calculateBaseAssetValue(market, proposedMarketPosition);
403
+ const proposedMarketPositionValueUSDC = (0, _1.calculateBaseAssetValue)(market, proposedMarketPosition);
404
404
  // total position value after trade
405
405
  const targetTotalPositionValueUSDC = totalCurrentPositionValueIgnoringTargetUSDC.add(proposedMarketPositionValueUSDC);
406
406
  let totalFreeCollateralUSDC = tc.sub(totalCurrentPositionValueIgnoringTargetUSDC
@@ -413,26 +413,28 @@ class ClearingHouseUser {
413
413
  }
414
414
  let priceDelt;
415
415
  if (proposedBaseAssetAmount.lt(numericConstants_1.ZERO)) {
416
- priceDelt = (tc
416
+ priceDelt = tc
417
417
  .mul(thisLev)
418
- .sub(tpv))
418
+ .sub(tpv)
419
419
  .mul(numericConstants_1.PRICE_TO_QUOTE_PRECISION)
420
420
  .div(thisLev.add(new bn_js_1.default(1)));
421
421
  }
422
422
  else {
423
- priceDelt = (tc
423
+ priceDelt = tc
424
424
  .mul(thisLev)
425
- .sub(tpv))
425
+ .sub(tpv)
426
426
  .mul(numericConstants_1.PRICE_TO_QUOTE_PRECISION)
427
427
  .div(thisLev.sub(new bn_js_1.default(1)));
428
428
  }
429
429
  let currentPrice;
430
430
  if (positionBaseSizeChange.eq(numericConstants_1.ZERO)) {
431
- currentPrice = _1.calculateMarkPrice(this.clearingHouse.getMarket(targetMarket.marketIndex));
431
+ currentPrice = (0, _1.calculateMarkPrice)(this.clearingHouse.getMarket(targetMarket.marketIndex));
432
432
  }
433
433
  else {
434
- const direction = positionBaseSizeChange.gt(numericConstants_1.ZERO) ? _1.PositionDirection.LONG : _1.PositionDirection.SHORT;
435
- currentPrice = _1.calculateTradeSlippage(direction, positionBaseSizeChange.abs(), this.clearingHouse.getMarket(targetMarket.marketIndex), 'base')[3]; // newPrice after swap
434
+ const direction = positionBaseSizeChange.gt(numericConstants_1.ZERO)
435
+ ? _1.PositionDirection.LONG
436
+ : _1.PositionDirection.SHORT;
437
+ currentPrice = (0, _1.calculateTradeSlippage)(direction, positionBaseSizeChange.abs(), this.clearingHouse.getMarket(targetMarket.marketIndex), 'base')[3]; // newPrice after swap
436
438
  }
437
439
  // if the position value after the trade is less than total collateral, there is no liq price
438
440
  if (targetTotalPositionValueUSDC.lte(totalFreeCollateralUSDC) &&
@@ -5,6 +5,7 @@ declare type Market = {
5
5
  marketIndex: BN;
6
6
  devnetPythOracle: string;
7
7
  mainnetPythOracle: string;
8
+ launchTs: number;
8
9
  };
9
10
  export declare const Markets: Market[];
10
11
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"markets.d.ts","sourceRoot":"","sources":["../../src/constants/markets.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,OAAO,CAAC;AAEvB,aAAK,MAAM,GAAG;IACb,MAAM,EAAE,MAAM,CAAC;IACf,eAAe,EAAE,MAAM,CAAC;IACxB,WAAW,EAAE,EAAE,CAAC;IAChB,gBAAgB,EAAE,MAAM,CAAC;IACzB,iBAAiB,EAAE,MAAM,CAAC;CAC1B,CAAC;AAEF,eAAO,MAAM,OAAO,EAAE,MAAM,EAyD3B,CAAC"}
1
+ {"version":3,"file":"markets.d.ts","sourceRoot":"","sources":["../../src/constants/markets.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,OAAO,CAAC;AAEvB,aAAK,MAAM,GAAG;IACb,MAAM,EAAE,MAAM,CAAC;IACf,eAAe,EAAE,MAAM,CAAC;IACxB,WAAW,EAAE,EAAE,CAAC;IAChB,gBAAgB,EAAE,MAAM,CAAC;IACzB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,QAAQ,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF,eAAO,MAAM,OAAO,EAAE,MAAM,EAyE3B,CAAC"}
@@ -12,6 +12,7 @@ exports.Markets = [
12
12
  marketIndex: new bn_js_1.default(0),
13
13
  devnetPythOracle: 'J83w4HKfqxwcq3BEMMkPFSppX3gqekLyLJBexebFVkix',
14
14
  mainnetPythOracle: 'H6ARHf6YXhGYeQfUzQNGk6rDNnLBQKrenN712K4AQJEG',
15
+ launchTs: 1635209696886,
15
16
  },
16
17
  {
17
18
  symbol: 'BTC-PERP',
@@ -19,6 +20,7 @@ exports.Markets = [
19
20
  marketIndex: new bn_js_1.default(1),
20
21
  devnetPythOracle: 'HovQMDrbAgAYPCmHVSrezcSmkMtXSSUsLDFANExrZh2J',
21
22
  mainnetPythOracle: 'GVXRSBjFk6e6J3NbVPXohDJetcTjaeeuykUpbQF8UoMU',
23
+ launchTs: 1637691088868,
22
24
  },
23
25
  {
24
26
  symbol: 'ETH-PERP',
@@ -26,6 +28,7 @@ exports.Markets = [
26
28
  marketIndex: new bn_js_1.default(2),
27
29
  devnetPythOracle: 'EdVCmQ9FSPcVe5YySXDPCRmc8aDQLKJ9xvYBMZPie1Vw',
28
30
  mainnetPythOracle: 'JBu1AL4obBcCMqKBBxhpWCNUt136ijcuMZLFvTP7iWdB',
31
+ launchTs: 1637691133472,
29
32
  },
30
33
  {
31
34
  symbol: 'LUNA-PERP',
@@ -33,6 +36,7 @@ exports.Markets = [
33
36
  marketIndex: new bn_js_1.default(3),
34
37
  devnetPythOracle: '8PugCXTAHLM9kfLSQWe2njE5pzAgUdpPk3Nx5zSm7BD3',
35
38
  mainnetPythOracle: '5bmWuR1dgP4avtGYMNKLuxumZTVKGgoN2BCMXWDNL9nY',
39
+ launchTs: 1638821738525,
36
40
  },
37
41
  {
38
42
  symbol: 'AVAX-PERP',
@@ -40,6 +44,7 @@ exports.Markets = [
40
44
  marketIndex: new bn_js_1.default(4),
41
45
  devnetPythOracle: 'FVb5h1VmHPfVb1RfqZckchq18GxRv4iKt8T4eVTQAqdz',
42
46
  mainnetPythOracle: 'Ax9ujW5B9oqcv59N8m6f1BpTBq2rGeGaBcpKjC5UYsXU',
47
+ launchTs: 1639092501080,
43
48
  },
44
49
  {
45
50
  symbol: 'BNB-PERP',
@@ -47,6 +52,7 @@ exports.Markets = [
47
52
  marketIndex: new bn_js_1.default(5),
48
53
  devnetPythOracle: 'GwzBgrXb4PG59zjce24SF2b9JXbLEjJJTBkmytuEZj1b',
49
54
  mainnetPythOracle: '4CkQJBxhU8EZ2UjhigbtdaPbpTe6mqf811fipYBFbSYN',
55
+ launchTs: 1639523193012,
50
56
  },
51
57
  {
52
58
  symbol: 'MATIC-PERP',
@@ -54,6 +60,7 @@ exports.Markets = [
54
60
  marketIndex: new bn_js_1.default(6),
55
61
  devnetPythOracle: 'FBirwuDFuRAu4iSGc7RGxN5koHB7EJM1wbCmyPuQoGur',
56
62
  mainnetPythOracle: '7KVswB9vkCgeM3SHP7aGDijvdRAHK8P5wi9JXViCrtYh',
63
+ launchTs: 1641488603564,
57
64
  },
58
65
  {
59
66
  symbol: 'ATOM-PERP',
@@ -61,5 +68,14 @@ exports.Markets = [
61
68
  marketIndex: new bn_js_1.default(7),
62
69
  devnetPythOracle: '7YAze8qFUMkBnyLVdKT4TFUUFui99EwS5gfRArMcrvFk',
63
70
  mainnetPythOracle: 'CrCpTerNqtZvqLcKqz1k13oVeXV9WkMD2zA9hBKXrsbN',
71
+ launchTs: 1641920238195,
72
+ },
73
+ {
74
+ symbol: 'DOT-PERP',
75
+ baseAssetSymbol: 'DOT',
76
+ marketIndex: new bn_js_1.default(8),
77
+ devnetPythOracle: '4dqq5VBpN4EwYb7wyywjjfknvMKu7m78j9mKZRXTj462',
78
+ mainnetPythOracle: 'EcV1X1gY2yb4KXxjVQtTHTbioum2gvmPnFk4zYAt7zne',
79
+ launchTs: 1642629253786,
64
80
  },
65
81
  ];
@@ -21,7 +21,7 @@ const getTokenAddress = (mintAddress, userPubKey) => {
21
21
  exports.getTokenAddress = getTokenAddress;
22
22
  const main = () => __awaiter(void 0, void 0, void 0, function* () {
23
23
  // Initialize Drift SDK
24
- const sdkConfig = __2.initialize({ env: 'devnet' });
24
+ const sdkConfig = (0, __2.initialize)({ env: 'devnet' });
25
25
  // Set up the Wallet and Provider
26
26
  const privateKey = process.env.BOT_PRIVATE_KEY; // stored as an array string
27
27
  const keypair = web3_js_1.Keypair.fromSecretKey(Uint8Array.from(JSON.parse(privateKey)));
@@ -35,7 +35,7 @@ const main = () => __awaiter(void 0, void 0, void 0, function* () {
35
35
  const lamportsBalance = yield connection.getBalance(wallet.publicKey);
36
36
  console.log('SOL balance:', lamportsBalance / Math.pow(10, 9));
37
37
  // Misc. other things to set up
38
- const usdcTokenAddress = yield exports.getTokenAddress(sdkConfig.USDC_MINT_ADDRESS, wallet.publicKey.toString());
38
+ const usdcTokenAddress = yield (0, exports.getTokenAddress)(sdkConfig.USDC_MINT_ADDRESS, wallet.publicKey.toString());
39
39
  // Set up the Drift Clearing House
40
40
  const clearingHousePublicKey = new web3_js_1.PublicKey(sdkConfig.CLEARING_HOUSE_PROGRAM_ID);
41
41
  const clearingHouse = __2.ClearingHouse.from(connection, provider.wallet, clearingHousePublicKey);
@@ -47,26 +47,25 @@ const main = () => __awaiter(void 0, void 0, void 0, function* () {
47
47
  if (!userAccountExists) {
48
48
  //// Create a Clearing House account by Depositing some USDC ($10,000 in this case)
49
49
  const depositAmount = new anchor_1.BN(10000).mul(__2.QUOTE_PRECISION);
50
- yield clearingHouse.initializeUserAccountAndDepositCollateral(depositAmount, yield exports.getTokenAddress(usdcTokenAddress.toString(), wallet.publicKey.toString()));
50
+ yield clearingHouse.initializeUserAccountAndDepositCollateral(depositAmount, yield (0, exports.getTokenAddress)(usdcTokenAddress.toString(), wallet.publicKey.toString()));
51
51
  }
52
52
  yield user.subscribe();
53
53
  // Get current price
54
54
  const solMarketInfo = __2.Markets.find((market) => market.baseAssetSymbol === 'SOL');
55
- const currentMarketPrice = __2.calculateMarkPrice(clearingHouse.getMarket(solMarketInfo.marketIndex));
56
- const formattedPrice = __2.convertToNumber(currentMarketPrice, __2.QUOTE_PRECISION);
55
+ const currentMarketPrice = (0, __2.calculateMarkPrice)(clearingHouse.getMarket(solMarketInfo.marketIndex));
56
+ const formattedPrice = (0, __2.convertToNumber)(currentMarketPrice, __2.QUOTE_PRECISION);
57
57
  console.log(`Current Market Price is $${formattedPrice}`);
58
58
  // Estimate the slippage for a $5000 LONG trade
59
59
  const solMarketAccount = clearingHouse.getMarket(solMarketInfo.marketIndex);
60
- const slippage = __2.convertToNumber(__2.calculateTradeSlippage(__2.PositionDirection.LONG, new anchor_1.BN(5000).mul(__2.QUOTE_PRECISION), solMarketAccount)[0], __2.MARK_PRICE_PRECISION);
60
+ const longAmount = new anchor_1.BN(5000).mul(__2.QUOTE_PRECISION);
61
+ const slippage = (0, __2.convertToNumber)((0, __2.calculateTradeSlippage)(__2.PositionDirection.LONG, longAmount, solMarketAccount)[0], __2.MARK_PRICE_PRECISION);
61
62
  console.log(`Slippage for a $5000 LONG on the SOL market would be $${slippage}`);
62
63
  // Make a $5000 LONG trade
63
- yield clearingHouse.openPosition(__2.PositionDirection.LONG, new anchor_1.BN(5000).mul(__2.QUOTE_PRECISION), solMarketInfo.marketIndex);
64
+ yield clearingHouse.openPosition(__2.PositionDirection.LONG, longAmount, solMarketInfo.marketIndex);
64
65
  console.log(`LONGED $5000 SOL`);
65
- // Make a $5000 LONG trade
66
- yield clearingHouse.openPosition(__2.PositionDirection.LONG, new anchor_1.BN(5000).mul(__2.QUOTE_PRECISION), solMarketInfo.marketIndex);
67
- console.log(`LONGED $5000 worth of SOL`);
68
66
  // Reduce the position by $2000
69
- yield clearingHouse.openPosition(__2.PositionDirection.SHORT, new anchor_1.BN(2000).mul(__2.QUOTE_PRECISION), solMarketInfo.marketIndex);
67
+ const reduceAmount = new anchor_1.BN(2000).mul(__2.QUOTE_PRECISION);
68
+ yield clearingHouse.openPosition(__2.PositionDirection.SHORT, reduceAmount, solMarketInfo.marketIndex);
70
69
  // Close the rest of the position
71
70
  yield clearingHouse.closePosition(solMarketInfo.marketIndex);
72
71
  });
package/lib/index.d.ts CHANGED
@@ -22,5 +22,6 @@ export * from './math/utils';
22
22
  export * from './config';
23
23
  export * from './constants/numericConstants';
24
24
  export * from './util/computeUnits';
25
+ export * from './util/tps';
25
26
  export { BN };
26
27
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,uBAAuB,CAAC;AAE3C,cAAc,kBAAkB,CAAC;AACjC,cAAc,cAAc,CAAC;AAC7B,cAAc,SAAS,CAAC;AACxB,cAAc,qBAAqB,CAAC;AACpC,cAAc,kDAAkD,CAAC;AACjE,cAAc,kBAAkB,CAAC;AACjC,cAAc,aAAa,CAAC;AAC5B,cAAc,SAAS,CAAC;AACxB,cAAc,qBAAqB,CAAC;AACpC,cAAc,iBAAiB,CAAC;AAChC,cAAc,mBAAmB,CAAC;AAClC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,sBAAsB,CAAC;AACrC,cAAc,eAAe,CAAC;AAC9B,cAAc,iBAAiB,CAAC;AAChC,cAAc,YAAY,CAAC;AAC3B,cAAc,cAAc,CAAC;AAC7B,cAAc,UAAU,CAAC;AACzB,cAAc,SAAS,CAAC;AACxB,cAAc,cAAc,CAAC;AAC7B,cAAc,UAAU,CAAC;AACzB,cAAc,8BAA8B,CAAC;AAC7C,cAAc,qBAAqB,CAAC;AAEpC,OAAO,EAAE,EAAE,EAAE,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,uBAAuB,CAAC;AAE3C,cAAc,kBAAkB,CAAC;AACjC,cAAc,cAAc,CAAC;AAC7B,cAAc,SAAS,CAAC;AACxB,cAAc,qBAAqB,CAAC;AACpC,cAAc,kDAAkD,CAAC;AACjE,cAAc,kBAAkB,CAAC;AACjC,cAAc,aAAa,CAAC;AAC5B,cAAc,SAAS,CAAC;AACxB,cAAc,qBAAqB,CAAC;AACpC,cAAc,iBAAiB,CAAC;AAChC,cAAc,mBAAmB,CAAC;AAClC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,sBAAsB,CAAC;AACrC,cAAc,eAAe,CAAC;AAC9B,cAAc,iBAAiB,CAAC;AAChC,cAAc,YAAY,CAAC;AAC3B,cAAc,cAAc,CAAC;AAC7B,cAAc,UAAU,CAAC;AACzB,cAAc,SAAS,CAAC;AACxB,cAAc,cAAc,CAAC;AAC7B,cAAc,UAAU,CAAC;AACzB,cAAc,8BAA8B,CAAC;AAC7C,cAAc,qBAAqB,CAAC;AACpC,cAAc,YAAY,CAAC;AAE3B,OAAO,EAAE,EAAE,EAAE,CAAC"}
package/lib/index.js CHANGED
@@ -36,3 +36,4 @@ __exportStar(require("./math/utils"), exports);
36
36
  __exportStar(require("./config"), exports);
37
37
  __exportStar(require("./constants/numericConstants"), exports);
38
38
  __exportStar(require("./util/computeUnits"), exports);
39
+ __exportStar(require("./util/tps"), exports);
package/lib/math/amm.js CHANGED
@@ -36,7 +36,7 @@ exports.calculatePrice = calculatePrice;
36
36
  * @returns quoteAssetReserve and baseAssetReserve after swap. : Precision AMM_RESERVE_PRECISION
37
37
  */
38
38
  function calculateAmmReservesAfterSwap(amm, inputAssetType, swapAmount, swapDirection) {
39
- assert_1.assert(swapAmount.gte(numericConstants_1.ZERO), 'swapAmount must be greater than 0');
39
+ (0, assert_1.assert)(swapAmount.gte(numericConstants_1.ZERO), 'swapAmount must be greater than 0');
40
40
  let newQuoteAssetReserve;
41
41
  let newBaseAssetReserve;
42
42
  if (inputAssetType === 'quote') {
@@ -105,7 +105,7 @@ function calculateAdjustKCost(market, marketIndex, numerator, denomenator) {
105
105
  marketIndex: new anchor_1.BN(marketIndex),
106
106
  quoteAssetAmount: new anchor_1.BN(0),
107
107
  };
108
- const currentValue = position_1.calculateBaseAssetValue(market, netUserPosition);
108
+ const currentValue = (0, position_1.calculateBaseAssetValue)(market, netUserPosition);
109
109
  const marketNewK = Object.assign({}, market);
110
110
  marketNewK.amm = Object.assign({}, market.amm);
111
111
  marketNewK.amm.baseAssetReserve = market.amm.baseAssetReserve
@@ -116,7 +116,7 @@ function calculateAdjustKCost(market, marketIndex, numerator, denomenator) {
116
116
  .div(denomenator);
117
117
  marketNewK.amm.sqrtK = market.amm.sqrtK.mul(numerator).div(denomenator);
118
118
  netUserPosition.quoteAssetAmount = currentValue;
119
- const cost = __1.calculatePositionPNL(marketNewK, netUserPosition);
119
+ const cost = (0, __1.calculatePositionPNL)(marketNewK, netUserPosition);
120
120
  return cost;
121
121
  }
122
122
  exports.calculateAdjustKCost = calculateAdjustKCost;
@@ -135,15 +135,15 @@ function calculateRepegCost(market, marketIndex, newPeg) {
135
135
  marketIndex: new anchor_1.BN(marketIndex),
136
136
  quoteAssetAmount: new anchor_1.BN(0),
137
137
  };
138
- const currentValue = position_1.calculateBaseAssetValue(market, netUserPosition);
138
+ const currentValue = (0, position_1.calculateBaseAssetValue)(market, netUserPosition);
139
139
  netUserPosition.quoteAssetAmount = currentValue;
140
- const prevMarketPrice = __1.calculateMarkPrice(market);
140
+ const prevMarketPrice = (0, __1.calculateMarkPrice)(market);
141
141
  const marketNewPeg = Object.assign({}, market);
142
142
  marketNewPeg.amm = Object.assign({}, market.amm);
143
143
  // const marketNewPeg = JSON.parse(JSON.stringify(market));
144
144
  marketNewPeg.amm.pegMultiplier = newPeg;
145
- console.log('Price moves from', __1.convertToNumber(prevMarketPrice), 'to', __1.convertToNumber(__1.calculateMarkPrice(marketNewPeg)));
146
- const cost = __1.calculatePositionPNL(marketNewPeg, netUserPosition);
145
+ console.log('Price moves from', (0, __1.convertToNumber)(prevMarketPrice), 'to', (0, __1.convertToNumber)((0, __1.calculateMarkPrice)(marketNewPeg)));
146
+ const cost = (0, __1.calculatePositionPNL)(marketNewPeg, netUserPosition);
147
147
  return cost;
148
148
  }
149
149
  exports.calculateRepegCost = calculateRepegCost;
@@ -10,6 +10,6 @@ const convertToNumber = (bigNumber, precision = numericConstants_1.MARK_PRICE_PR
10
10
  };
11
11
  exports.convertToNumber = convertToNumber;
12
12
  const convertBaseAssetAmountToNumber = (baseAssetAmount) => {
13
- return exports.convertToNumber(baseAssetAmount, numericConstants_1.MARK_PRICE_PRECISION.mul(numericConstants_1.PEG_PRECISION));
13
+ return (0, exports.convertToNumber)(baseAssetAmount, numericConstants_1.MARK_PRICE_PRECISION.mul(numericConstants_1.PEG_PRECISION));
14
14
  };
15
15
  exports.convertBaseAssetAmountToNumber = convertBaseAssetAmountToNumber;
@@ -22,18 +22,16 @@ export declare function calculateEstimatedFundingRate(market: Market, oraclePric
22
22
  /**
23
23
  *
24
24
  * @param market
25
- * @param pythClient
25
+ * @param oraclePriceData
26
26
  * @param periodAdjustment
27
- * @param estimationMethod
28
27
  * @returns Estimated funding rate. : Precision //TODO-PRECISION
29
28
  */
30
29
  export declare function calculateLongShortFundingRate(market: Market, oraclePriceData: PriceData, periodAdjustment?: BN): Promise<[BN, BN]>;
31
30
  /**
32
31
  *
33
32
  * @param market
34
- * @param pythClient
33
+ * @param oraclePriceData
35
34
  * @param periodAdjustment
36
- * @param estimationMethod
37
35
  * @returns Estimated funding rate. : Precision //TODO-PRECISION
38
36
  */
39
37
  export declare function calculateLongShortFundingRateAndLiveTwaps(market: Market, oraclePriceData: PriceData, periodAdjustment?: BN): Promise<[BN, BN, BN, BN]>;
@@ -1 +1 @@
1
- {"version":3,"file":"funding.d.ts","sourceRoot":"","sources":["../../src/math/funding.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,uBAAuB,CAAC;AAC3C,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAOhD,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAGlC;;;;;;GAMG;AACH,wBAAsB,gCAAgC,CACrD,MAAM,EAAE,MAAM,EACd,eAAe,EAAE,SAAS,EAC1B,gBAAgB,GAAE,EAAc,GAC9B,OAAO,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,CA0K/B;AAED;;;;;;;GAOG;AACH,wBAAsB,6BAA6B,CAClD,MAAM,EAAE,MAAM,EACd,eAAe,EAAE,SAAS,EAC1B,gBAAgB,EAAE,EAAc,EAChC,gBAAgB,EAAE,cAAc,GAAG,YAAY,GAAG,QAAQ,GACxD,OAAO,CAAC,EAAE,CAAC,CAgBb;AAED;;;;;;;GAOG;AACH,wBAAsB,6BAA6B,CAClD,MAAM,EAAE,MAAM,EACd,eAAe,EAAE,SAAS,EAC1B,gBAAgB,GAAE,EAAc,GAC9B,OAAO,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,CAenB;AAED;;;;;;;GAOG;AACH,wBAAsB,yCAAyC,CAC9D,MAAM,EAAE,MAAM,EACd,eAAe,EAAE,SAAS,EAC1B,gBAAgB,GAAE,EAAc,GAC9B,OAAO,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,CAe3B;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,MAAM,GAAG,EAAE,CAKvD"}
1
+ {"version":3,"file":"funding.d.ts","sourceRoot":"","sources":["../../src/math/funding.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,uBAAuB,CAAC;AAC3C,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAOhD,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAGlC;;;;;;GAMG;AACH,wBAAsB,gCAAgC,CACrD,MAAM,EAAE,MAAM,EACd,eAAe,EAAE,SAAS,EAC1B,gBAAgB,GAAE,EAAc,GAC9B,OAAO,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,CA0K/B;AAED;;;;;;;GAOG;AACH,wBAAsB,6BAA6B,CAClD,MAAM,EAAE,MAAM,EACd,eAAe,EAAE,SAAS,EAC1B,gBAAgB,EAAE,EAAc,EAChC,gBAAgB,EAAE,cAAc,GAAG,YAAY,GAAG,QAAQ,GACxD,OAAO,CAAC,EAAE,CAAC,CAgBb;AAED;;;;;;GAMG;AACH,wBAAsB,6BAA6B,CAClD,MAAM,EAAE,MAAM,EACd,eAAe,EAAE,SAAS,EAC1B,gBAAgB,GAAE,EAAc,GAC9B,OAAO,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,CAenB;AAED;;;;;;GAMG;AACH,wBAAsB,yCAAyC,CAC9D,MAAM,EAAE,MAAM,EACd,eAAe,EAAE,SAAS,EAC1B,gBAAgB,GAAE,EAAc,GAC9B,OAAO,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,CAe3B;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,MAAM,GAAG,EAAE,CAQvD"}
@@ -40,7 +40,7 @@ function calculateAllEstimatedFundingRate(market, oraclePriceData, periodAdjustm
40
40
  const lastMarkPriceTwapTs = market.amm.lastMarkPriceTwapTs;
41
41
  const timeSinceLastMarkChange = now.sub(lastMarkPriceTwapTs);
42
42
  const markTwapTimeSinceLastUpdate = anchor_1.BN.max(secondsInHour, secondsInHour.sub(timeSinceLastMarkChange));
43
- const baseAssetPriceWithMantissa = market_1.calculateMarkPrice(market);
43
+ const baseAssetPriceWithMantissa = (0, market_1.calculateMarkPrice)(market);
44
44
  const markTwapWithMantissa = markTwapTimeSinceLastUpdate
45
45
  .mul(lastMarkTwapWithMantissa)
46
46
  .add(timeSinceLastMarkChange.mul(baseAssetPriceWithMantissa))
@@ -78,7 +78,7 @@ function calculateAllEstimatedFundingRate(market, oraclePriceData, periodAdjustm
78
78
  .add(timeSinceLastMarkChange.mul(oraclePriceStableWithMantissa))
79
79
  .div(timeSinceLastOracleTwapUpdate.add(oracleTwapTimeSinceLastUpdate));
80
80
  }
81
- const twapSpread = markTwapWithMantissa.sub(oracleTwapWithMantissa);
81
+ const twapSpread = lastMarkTwapWithMantissa.sub(lastOracleTwapWithMantissa);
82
82
  const twapSpreadPct = twapSpread
83
83
  .mul(numericConstants_1.MARK_PRICE_PRECISION)
84
84
  .mul(new anchor_1.BN(100))
@@ -193,9 +193,8 @@ exports.calculateEstimatedFundingRate = calculateEstimatedFundingRate;
193
193
  /**
194
194
  *
195
195
  * @param market
196
- * @param pythClient
196
+ * @param oraclePriceData
197
197
  * @param periodAdjustment
198
- * @param estimationMethod
199
198
  * @returns Estimated funding rate. : Precision //TODO-PRECISION
200
199
  */
201
200
  function calculateLongShortFundingRate(market, oraclePriceData, periodAdjustment = new anchor_1.BN(1)) {
@@ -216,9 +215,8 @@ exports.calculateLongShortFundingRate = calculateLongShortFundingRate;
216
215
  /**
217
216
  *
218
217
  * @param market
219
- * @param pythClient
218
+ * @param oraclePriceData
220
219
  * @param periodAdjustment
221
- * @param estimationMethod
222
220
  * @returns Estimated funding rate. : Precision //TODO-PRECISION
223
221
  */
224
222
  function calculateLongShortFundingRateAndLiveTwaps(market, oraclePriceData, periodAdjustment = new anchor_1.BN(1)) {
@@ -244,7 +242,7 @@ exports.calculateLongShortFundingRateAndLiveTwaps = calculateLongShortFundingRat
244
242
  function calculateFundingPool(market) {
245
243
  // todo
246
244
  const totalFeeLB = market.amm.totalFee.div(new anchor_1.BN(2));
247
- const feePool = market.amm.totalFeeMinusDistributions.sub(totalFeeLB);
245
+ const feePool = anchor_1.BN.max(numericConstants_1.ZERO, market.amm.totalFeeMinusDistributions.sub(totalFeeLB));
248
246
  return feePool;
249
247
  }
250
248
  exports.calculateFundingPool = calculateFundingPool;
@@ -9,6 +9,6 @@ const amm_1 = require("./amm");
9
9
  * @return markPrice : Precision MARK_PRICE_PRECISION
10
10
  */
11
11
  function calculateMarkPrice(market) {
12
- return amm_1.calculatePrice(market.amm.baseAssetReserve, market.amm.quoteAssetReserve, market.amm.pegMultiplier);
12
+ return (0, amm_1.calculatePrice)(market.amm.baseAssetReserve, market.amm.quoteAssetReserve, market.amm.pegMultiplier);
13
13
  }
14
14
  exports.calculateMarkPrice = calculateMarkPrice;
@@ -22,7 +22,7 @@ function calculateBaseAssetValue(market, userPosition) {
22
22
  const directionToClose = userPosition.baseAssetAmount.gt(numericConstants_1.ZERO)
23
23
  ? types_1.PositionDirection.SHORT
24
24
  : types_1.PositionDirection.LONG;
25
- const [newQuoteAssetReserve, _] = amm_1.calculateAmmReservesAfterSwap(market.amm, 'base', userPosition.baseAssetAmount.abs(), amm_1.getSwapDirection('base', directionToClose));
25
+ const [newQuoteAssetReserve, _] = (0, amm_1.calculateAmmReservesAfterSwap)(market.amm, 'base', userPosition.baseAssetAmount.abs(), (0, amm_1.getSwapDirection)('base', directionToClose));
26
26
  switch (directionToClose) {
27
27
  case types_1.PositionDirection.SHORT:
28
28
  return market.amm.quoteAssetReserve
package/lib/math/trade.js CHANGED
@@ -25,18 +25,18 @@ const MAXPCT = new anchor_1.BN(1000); //percentage units are [0,1000] => [0,1]
25
25
  * 'newPrice' => the price of the asset after the trade : Precision MARK_PRICE_PRECISION
26
26
  */
27
27
  function calculateTradeSlippage(direction, amount, market, inputAssetType = 'quote') {
28
- const oldPrice = market_1.calculateMarkPrice(market);
28
+ const oldPrice = (0, market_1.calculateMarkPrice)(market);
29
29
  if (amount.eq(numericConstants_1.ZERO)) {
30
30
  return [numericConstants_1.ZERO, numericConstants_1.ZERO, oldPrice, oldPrice];
31
31
  }
32
32
  const [acquiredBase, acquiredQuote] = calculateTradeAcquiredAmounts(direction, amount, market, inputAssetType);
33
- const entryPrice = amm_1.calculatePrice(acquiredBase, acquiredQuote, market.amm.pegMultiplier).mul(new anchor_1.BN(-1));
34
- const newPrice = amm_1.calculatePrice(market.amm.baseAssetReserve.sub(acquiredBase), market.amm.quoteAssetReserve.sub(acquiredQuote), market.amm.pegMultiplier);
33
+ const entryPrice = (0, amm_1.calculatePrice)(acquiredBase, acquiredQuote, market.amm.pegMultiplier).mul(new anchor_1.BN(-1));
34
+ const newPrice = (0, amm_1.calculatePrice)(market.amm.baseAssetReserve.sub(acquiredBase), market.amm.quoteAssetReserve.sub(acquiredQuote), market.amm.pegMultiplier);
35
35
  if (direction == types_1.PositionDirection.SHORT) {
36
- assert_1.assert(newPrice.lt(oldPrice));
36
+ (0, assert_1.assert)(newPrice.lt(oldPrice));
37
37
  }
38
38
  else {
39
- assert_1.assert(oldPrice.lt(newPrice));
39
+ (0, assert_1.assert)(oldPrice.lt(newPrice));
40
40
  }
41
41
  const pctMaxSlippage = newPrice
42
42
  .sub(oldPrice)
@@ -64,7 +64,7 @@ function calculateTradeAcquiredAmounts(direction, amount, market, inputAssetType
64
64
  if (amount.eq(numericConstants_1.ZERO)) {
65
65
  return [numericConstants_1.ZERO, numericConstants_1.ZERO];
66
66
  }
67
- const [newQuoteAssetReserve, newBaseAssetReserve] = amm_1.calculateAmmReservesAfterSwap(market.amm, inputAssetType, amount, amm_1.getSwapDirection(inputAssetType, direction));
67
+ const [newQuoteAssetReserve, newBaseAssetReserve] = (0, amm_1.calculateAmmReservesAfterSwap)(market.amm, inputAssetType, amount, (0, amm_1.getSwapDirection)(inputAssetType, direction));
68
68
  const acquiredBase = market.amm.baseAssetReserve.sub(newBaseAssetReserve);
69
69
  const acquiredQuote = market.amm.quoteAssetReserve.sub(newQuoteAssetReserve);
70
70
  return [acquiredBase, acquiredQuote];
@@ -86,10 +86,10 @@ exports.calculateTradeAcquiredAmounts = calculateTradeAcquiredAmounts;
86
86
  * ]
87
87
  */
88
88
  function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAssetType = 'quote') {
89
- assert_1.assert(market.amm.baseAssetReserve.gt(numericConstants_1.ZERO));
90
- assert_1.assert(targetPrice.gt(numericConstants_1.ZERO));
91
- assert_1.assert(pct.lte(MAXPCT) && pct.gt(numericConstants_1.ZERO));
92
- const markPriceBefore = market_1.calculateMarkPrice(market);
89
+ (0, assert_1.assert)(market.amm.baseAssetReserve.gt(numericConstants_1.ZERO));
90
+ (0, assert_1.assert)(targetPrice.gt(numericConstants_1.ZERO));
91
+ (0, assert_1.assert)(pct.lte(MAXPCT) && pct.gt(numericConstants_1.ZERO));
92
+ const markPriceBefore = (0, market_1.calculateMarkPrice)(market);
93
93
  if (targetPrice.gt(markPriceBefore)) {
94
94
  const priceGap = targetPrice.sub(markPriceBefore);
95
95
  const priceGapScaled = priceGap.mul(pct).div(MAXPCT);
@@ -114,11 +114,11 @@ function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAsse
114
114
  let markPriceAfter;
115
115
  if (markPriceBefore.gt(targetPrice)) {
116
116
  // overestimate y2
117
- baseAssetReserveAfter = utils_1.squareRootBN(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).sub(biasModifier)).sub(new anchor_1.BN(1));
117
+ baseAssetReserveAfter = (0, utils_1.squareRootBN)(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).sub(biasModifier)).sub(new anchor_1.BN(1));
118
118
  quoteAssetReserveAfter = k
119
119
  .div(numericConstants_1.MARK_PRICE_PRECISION)
120
120
  .div(baseAssetReserveAfter);
121
- markPriceAfter = amm_1.calculatePrice(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
121
+ markPriceAfter = (0, amm_1.calculatePrice)(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
122
122
  direction = types_1.PositionDirection.SHORT;
123
123
  tradeSize = quoteAssetReserveBefore
124
124
  .sub(quoteAssetReserveAfter)
@@ -129,11 +129,11 @@ function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAsse
129
129
  }
130
130
  else if (markPriceBefore.lt(targetPrice)) {
131
131
  // underestimate y2
132
- baseAssetReserveAfter = utils_1.squareRootBN(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).add(biasModifier)).add(new anchor_1.BN(1));
132
+ baseAssetReserveAfter = (0, utils_1.squareRootBN)(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).add(biasModifier)).add(new anchor_1.BN(1));
133
133
  quoteAssetReserveAfter = k
134
134
  .div(numericConstants_1.MARK_PRICE_PRECISION)
135
135
  .div(baseAssetReserveAfter);
136
- markPriceAfter = amm_1.calculatePrice(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
136
+ markPriceAfter = (0, amm_1.calculatePrice)(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
137
137
  direction = types_1.PositionDirection.LONG;
138
138
  tradeSize = quoteAssetReserveAfter
139
139
  .sub(quoteAssetReserveBefore)
@@ -160,8 +160,8 @@ function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAsse
160
160
  .mul(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
161
161
  .mul(numericConstants_1.MARK_PRICE_PRECISION)
162
162
  .div(baseSize.abs());
163
- assert_1.assert(tp1.sub(tp2).lte(originalDiff), 'Target Price Calculation incorrect');
164
- assert_1.assert(tp2.lte(tp1) || tp2.sub(tp1).abs() < 100000, 'Target Price Calculation incorrect' +
163
+ (0, assert_1.assert)(tp1.sub(tp2).lte(originalDiff), 'Target Price Calculation incorrect');
164
+ (0, assert_1.assert)(tp2.lte(tp1) || tp2.sub(tp1).abs() < 100000, 'Target Price Calculation incorrect' +
165
165
  tp2.toString() +
166
166
  '>=' +
167
167
  tp1.toString() +
package/lib/pythClient.js CHANGED
@@ -18,7 +18,7 @@ class PythClient {
18
18
  getPriceData(pricePublicKey) {
19
19
  return __awaiter(this, void 0, void 0, function* () {
20
20
  const account = yield this.connection.getAccountInfo(pricePublicKey);
21
- return client_1.parsePriceData(account.data);
21
+ return (0, client_1.parsePriceData)(account.data);
22
22
  });
23
23
  }
24
24
  }
@@ -0,0 +1,3 @@
1
+ import { Connection, PublicKey } from '@solana/web3.js';
2
+ export declare function estimateTps(programId: PublicKey, connection: Connection, failed: boolean): Promise<number>;
3
+ //# sourceMappingURL=tps.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tps.d.ts","sourceRoot":"","sources":["../../src/util/tps.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAExD,wBAAsB,WAAW,CAChC,SAAS,EAAE,SAAS,EACpB,UAAU,EAAE,UAAU,EACtB,MAAM,EAAE,OAAO,GACb,OAAO,CAAC,MAAM,CAAC,CAoBjB"}
@@ -0,0 +1,27 @@
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.estimateTps = void 0;
13
+ function estimateTps(programId, connection, failed) {
14
+ return __awaiter(this, void 0, void 0, function* () {
15
+ let signatures = yield connection.getSignaturesForAddress(programId, undefined, 'finalized');
16
+ if (failed) {
17
+ signatures = signatures.filter((signature) => signature.err);
18
+ }
19
+ const numberOfSignatures = signatures.length;
20
+ if (numberOfSignatures === 0) {
21
+ return 0;
22
+ }
23
+ return (numberOfSignatures /
24
+ (signatures[0].blockTime - signatures[numberOfSignatures - 1].blockTime));
25
+ });
26
+ }
27
+ exports.estimateTps = estimateTps;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@drift-labs/sdk",
3
- "version": "0.1.14",
3
+ "version": "0.1.17-master.1",
4
4
  "main": "lib/index.js",
5
5
  "types": "lib/index.d.ts",
6
6
  "author": "crispheaney",
@@ -579,34 +579,35 @@ export class ClearingHouseUser {
579
579
 
580
580
  let priceDelt;
581
581
  if (proposedBaseAssetAmount.lt(ZERO)) {
582
- priceDelt = (tc
582
+ priceDelt = tc
583
583
  .mul(thisLev)
584
- .sub(tpv))
584
+ .sub(tpv)
585
585
  .mul(PRICE_TO_QUOTE_PRECISION)
586
586
  .div(thisLev.add(new BN(1)));
587
587
  } else {
588
- priceDelt = (tc
588
+ priceDelt = tc
589
589
  .mul(thisLev)
590
- .sub(tpv))
590
+ .sub(tpv)
591
591
  .mul(PRICE_TO_QUOTE_PRECISION)
592
592
  .div(thisLev.sub(new BN(1)));
593
593
  }
594
594
 
595
595
  let currentPrice;
596
- if(positionBaseSizeChange.eq(ZERO)){
596
+ if (positionBaseSizeChange.eq(ZERO)) {
597
597
  currentPrice = calculateMarkPrice(
598
598
  this.clearingHouse.getMarket(targetMarket.marketIndex)
599
599
  );
600
- } else{
601
- const direction = positionBaseSizeChange.gt(ZERO) ? PositionDirection.LONG : PositionDirection.SHORT;
600
+ } else {
601
+ const direction = positionBaseSizeChange.gt(ZERO)
602
+ ? PositionDirection.LONG
603
+ : PositionDirection.SHORT;
602
604
  currentPrice = calculateTradeSlippage(
603
605
  direction,
604
606
  positionBaseSizeChange.abs(),
605
607
  this.clearingHouse.getMarket(targetMarket.marketIndex),
606
- 'base',
608
+ 'base'
607
609
  )[3]; // newPrice after swap
608
610
  }
609
-
610
611
 
611
612
  // if the position value after the trade is less than total collateral, there is no liq price
612
613
  if (
@@ -622,7 +623,7 @@ export class ClearingHouseUser {
622
623
  .mul(AMM_RESERVE_PRECISION)
623
624
  .div(proposedBaseAssetAmount);
624
625
 
625
- if(eatMargin2.gt(currentPrice)){
626
+ if (eatMargin2.gt(currentPrice)) {
626
627
  return new BN(-1);
627
628
  }
628
629
 
@@ -6,6 +6,7 @@ type Market = {
6
6
  marketIndex: BN;
7
7
  devnetPythOracle: string;
8
8
  mainnetPythOracle: string;
9
+ launchTs: number;
9
10
  };
10
11
 
11
12
  export const Markets: Market[] = [
@@ -15,6 +16,7 @@ export const Markets: Market[] = [
15
16
  marketIndex: new BN(0),
16
17
  devnetPythOracle: 'J83w4HKfqxwcq3BEMMkPFSppX3gqekLyLJBexebFVkix',
17
18
  mainnetPythOracle: 'H6ARHf6YXhGYeQfUzQNGk6rDNnLBQKrenN712K4AQJEG',
19
+ launchTs: 1635209696886,
18
20
  },
19
21
  {
20
22
  symbol: 'BTC-PERP',
@@ -22,6 +24,7 @@ export const Markets: Market[] = [
22
24
  marketIndex: new BN(1),
23
25
  devnetPythOracle: 'HovQMDrbAgAYPCmHVSrezcSmkMtXSSUsLDFANExrZh2J',
24
26
  mainnetPythOracle: 'GVXRSBjFk6e6J3NbVPXohDJetcTjaeeuykUpbQF8UoMU',
27
+ launchTs: 1637691088868,
25
28
  },
26
29
  {
27
30
  symbol: 'ETH-PERP',
@@ -29,6 +32,7 @@ export const Markets: Market[] = [
29
32
  marketIndex: new BN(2),
30
33
  devnetPythOracle: 'EdVCmQ9FSPcVe5YySXDPCRmc8aDQLKJ9xvYBMZPie1Vw',
31
34
  mainnetPythOracle: 'JBu1AL4obBcCMqKBBxhpWCNUt136ijcuMZLFvTP7iWdB',
35
+ launchTs: 1637691133472,
32
36
  },
33
37
  {
34
38
  symbol: 'LUNA-PERP',
@@ -36,6 +40,7 @@ export const Markets: Market[] = [
36
40
  marketIndex: new BN(3),
37
41
  devnetPythOracle: '8PugCXTAHLM9kfLSQWe2njE5pzAgUdpPk3Nx5zSm7BD3',
38
42
  mainnetPythOracle: '5bmWuR1dgP4avtGYMNKLuxumZTVKGgoN2BCMXWDNL9nY',
43
+ launchTs: 1638821738525,
39
44
  },
40
45
  {
41
46
  symbol: 'AVAX-PERP',
@@ -43,6 +48,7 @@ export const Markets: Market[] = [
43
48
  marketIndex: new BN(4),
44
49
  devnetPythOracle: 'FVb5h1VmHPfVb1RfqZckchq18GxRv4iKt8T4eVTQAqdz',
45
50
  mainnetPythOracle: 'Ax9ujW5B9oqcv59N8m6f1BpTBq2rGeGaBcpKjC5UYsXU',
51
+ launchTs: 1639092501080,
46
52
  },
47
53
  {
48
54
  symbol: 'BNB-PERP',
@@ -50,6 +56,7 @@ export const Markets: Market[] = [
50
56
  marketIndex: new BN(5),
51
57
  devnetPythOracle: 'GwzBgrXb4PG59zjce24SF2b9JXbLEjJJTBkmytuEZj1b',
52
58
  mainnetPythOracle: '4CkQJBxhU8EZ2UjhigbtdaPbpTe6mqf811fipYBFbSYN',
59
+ launchTs: 1639523193012,
53
60
  },
54
61
  {
55
62
  symbol: 'MATIC-PERP',
@@ -57,6 +64,7 @@ export const Markets: Market[] = [
57
64
  marketIndex: new BN(6),
58
65
  devnetPythOracle: 'FBirwuDFuRAu4iSGc7RGxN5koHB7EJM1wbCmyPuQoGur',
59
66
  mainnetPythOracle: '7KVswB9vkCgeM3SHP7aGDijvdRAHK8P5wi9JXViCrtYh',
67
+ launchTs: 1641488603564,
60
68
  },
61
69
  {
62
70
  symbol: 'ATOM-PERP',
@@ -64,5 +72,14 @@ export const Markets: Market[] = [
64
72
  marketIndex: new BN(7),
65
73
  devnetPythOracle: '7YAze8qFUMkBnyLVdKT4TFUUFui99EwS5gfRArMcrvFk',
66
74
  mainnetPythOracle: 'CrCpTerNqtZvqLcKqz1k13oVeXV9WkMD2zA9hBKXrsbN',
75
+ launchTs: 1641920238195,
76
+ },
77
+ {
78
+ symbol: 'DOT-PERP',
79
+ baseAssetSymbol: 'DOT',
80
+ marketIndex: new BN(8),
81
+ devnetPythOracle: '4dqq5VBpN4EwYb7wyywjjfknvMKu7m78j9mKZRXTj462',
82
+ mainnetPythOracle: 'EcV1X1gY2yb4KXxjVQtTHTbioum2gvmPnFk4zYAt7zne',
83
+ launchTs: 1642629253786,
67
84
  },
68
85
  ];
@@ -102,10 +102,11 @@ const main = async () => {
102
102
  // Estimate the slippage for a $5000 LONG trade
103
103
  const solMarketAccount = clearingHouse.getMarket(solMarketInfo.marketIndex);
104
104
 
105
+ const longAmount = new BN(5000).mul(QUOTE_PRECISION);
105
106
  const slippage = convertToNumber(
106
107
  calculateTradeSlippage(
107
108
  PositionDirection.LONG,
108
- new BN(5000).mul(QUOTE_PRECISION),
109
+ longAmount,
109
110
  solMarketAccount
110
111
  )[0],
111
112
  MARK_PRICE_PRECISION
@@ -118,23 +119,16 @@ const main = async () => {
118
119
  // Make a $5000 LONG trade
119
120
  await clearingHouse.openPosition(
120
121
  PositionDirection.LONG,
121
- new BN(5000).mul(QUOTE_PRECISION),
122
+ longAmount,
122
123
  solMarketInfo.marketIndex
123
124
  );
124
125
  console.log(`LONGED $5000 SOL`);
125
126
 
126
- // Make a $5000 LONG trade
127
- await clearingHouse.openPosition(
128
- PositionDirection.LONG,
129
- new BN(5000).mul(QUOTE_PRECISION),
130
- solMarketInfo.marketIndex
131
- );
132
- console.log(`LONGED $5000 worth of SOL`);
133
-
134
127
  // Reduce the position by $2000
128
+ const reduceAmount = new BN(2000).mul(QUOTE_PRECISION);
135
129
  await clearingHouse.openPosition(
136
130
  PositionDirection.SHORT,
137
- new BN(2000).mul(QUOTE_PRECISION),
131
+ reduceAmount,
138
132
  solMarketInfo.marketIndex
139
133
  );
140
134
 
package/src/index.ts CHANGED
@@ -23,5 +23,6 @@ export * from './math/utils';
23
23
  export * from './config';
24
24
  export * from './constants/numericConstants';
25
25
  export * from './util/computeUnits';
26
+ export * from './util/tps';
26
27
 
27
28
  export { BN };
@@ -99,7 +99,7 @@ export async function calculateAllEstimatedFundingRate(
99
99
  .div(timeSinceLastOracleTwapUpdate.add(oracleTwapTimeSinceLastUpdate));
100
100
  }
101
101
 
102
- const twapSpread = markTwapWithMantissa.sub(oracleTwapWithMantissa);
102
+ const twapSpread = lastMarkTwapWithMantissa.sub(lastOracleTwapWithMantissa);
103
103
 
104
104
  const twapSpreadPct = twapSpread
105
105
  .mul(MARK_PRICE_PRECISION)
@@ -226,9 +226,8 @@ export async function calculateEstimatedFundingRate(
226
226
  /**
227
227
  *
228
228
  * @param market
229
- * @param pythClient
229
+ * @param oraclePriceData
230
230
  * @param periodAdjustment
231
- * @param estimationMethod
232
231
  * @returns Estimated funding rate. : Precision //TODO-PRECISION
233
232
  */
234
233
  export async function calculateLongShortFundingRate(
@@ -255,9 +254,8 @@ export async function calculateLongShortFundingRate(
255
254
  /**
256
255
  *
257
256
  * @param market
258
- * @param pythClient
257
+ * @param oraclePriceData
259
258
  * @param periodAdjustment
260
- * @param estimationMethod
261
259
  * @returns Estimated funding rate. : Precision //TODO-PRECISION
262
260
  */
263
261
  export async function calculateLongShortFundingRateAndLiveTwaps(
@@ -289,6 +287,9 @@ export async function calculateLongShortFundingRateAndLiveTwaps(
289
287
  export function calculateFundingPool(market: Market): BN {
290
288
  // todo
291
289
  const totalFeeLB = market.amm.totalFee.div(new BN(2));
292
- const feePool = market.amm.totalFeeMinusDistributions.sub(totalFeeLB);
290
+ const feePool = BN.max(
291
+ ZERO,
292
+ market.amm.totalFeeMinusDistributions.sub(totalFeeLB)
293
+ );
293
294
  return feePool;
294
295
  }
@@ -0,0 +1,27 @@
1
+ import { Connection, PublicKey } from '@solana/web3.js';
2
+
3
+ export async function estimateTps(
4
+ programId: PublicKey,
5
+ connection: Connection,
6
+ failed: boolean
7
+ ): Promise<number> {
8
+ let signatures = await connection.getSignaturesForAddress(
9
+ programId,
10
+ undefined,
11
+ 'finalized'
12
+ );
13
+ if (failed) {
14
+ signatures = signatures.filter((signature) => signature.err);
15
+ }
16
+
17
+ const numberOfSignatures = signatures.length;
18
+
19
+ if (numberOfSignatures === 0) {
20
+ return 0;
21
+ }
22
+
23
+ return (
24
+ numberOfSignatures /
25
+ (signatures[0].blockTime - signatures[numberOfSignatures - 1].blockTime)
26
+ );
27
+ }