@drift-labs/sdk 0.1.12 → 0.1.16

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.
Files changed (83) hide show
  1. package/README.md +2 -2
  2. package/lib/accounts/defaultClearingHouseAccountSubscriber.d.ts +1 -0
  3. package/lib/accounts/defaultClearingHouseAccountSubscriber.d.ts.map +1 -1
  4. package/lib/accounts/defaultClearingHouseAccountSubscriber.js +17 -0
  5. package/lib/accounts/defaultUserAccountSubscriber.d.ts +2 -0
  6. package/lib/accounts/defaultUserAccountSubscriber.d.ts.map +1 -1
  7. package/lib/accounts/defaultUserAccountSubscriber.js +16 -0
  8. package/lib/accounts/types.d.ts +3 -21
  9. package/lib/accounts/types.d.ts.map +1 -1
  10. package/lib/accounts/webSocketAccountSubscriber.d.ts +2 -0
  11. package/lib/accounts/webSocketAccountSubscriber.d.ts.map +1 -1
  12. package/lib/accounts/webSocketAccountSubscriber.js +13 -3
  13. package/lib/clearingHouse.d.ts +4 -0
  14. package/lib/clearingHouse.d.ts.map +1 -1
  15. package/lib/clearingHouse.js +8 -0
  16. package/lib/clearingHouseUser.d.ts +31 -3
  17. package/lib/clearingHouseUser.d.ts.map +1 -1
  18. package/lib/clearingHouseUser.js +213 -47
  19. package/lib/constants/markets.d.ts.map +1 -1
  20. package/lib/constants/markets.js +21 -0
  21. package/lib/constants/numericConstants.d.ts +1 -0
  22. package/lib/constants/numericConstants.d.ts.map +1 -1
  23. package/lib/constants/numericConstants.js +2 -1
  24. package/lib/examples/makeTradeExample.d.ts.map +1 -1
  25. package/lib/examples/makeTradeExample.js +14 -13
  26. package/lib/idl/clearing_house.json +94 -42
  27. package/lib/index.d.ts +4 -1
  28. package/lib/index.d.ts.map +1 -1
  29. package/lib/index.js +4 -1
  30. package/lib/math/amm.d.ts +26 -1
  31. package/lib/math/amm.d.ts.map +1 -1
  32. package/lib/math/amm.js +85 -10
  33. package/lib/math/funding.d.ts +6 -6
  34. package/lib/math/funding.d.ts.map +1 -1
  35. package/lib/math/funding.js +41 -22
  36. package/lib/math/insuranceFund.d.ts +15 -0
  37. package/lib/math/insuranceFund.d.ts.map +1 -0
  38. package/lib/math/insuranceFund.js +36 -0
  39. package/lib/math/position.d.ts +1 -1
  40. package/lib/math/position.d.ts.map +1 -1
  41. package/lib/math/position.js +15 -23
  42. package/lib/math/trade.d.ts +1 -1
  43. package/lib/math/trade.d.ts.map +1 -1
  44. package/lib/math/trade.js +9 -4
  45. package/lib/types.d.ts +0 -13
  46. package/lib/types.d.ts.map +1 -1
  47. package/lib/util/computeUnits.d.ts +3 -0
  48. package/lib/util/computeUnits.d.ts.map +1 -0
  49. package/lib/util/computeUnits.js +27 -0
  50. package/lib/util/tps.d.ts +3 -0
  51. package/lib/util/tps.d.ts.map +1 -0
  52. package/lib/util/tps.js +27 -0
  53. package/lib/wallet.d.ts +10 -0
  54. package/lib/wallet.d.ts.map +1 -0
  55. package/lib/wallet.js +35 -0
  56. package/package.json +3 -13
  57. package/src/accounts/defaultClearingHouseAccountSubscriber.ts +18 -0
  58. package/src/accounts/defaultUserAccountSubscriber.ts +18 -0
  59. package/src/accounts/types.ts +3 -28
  60. package/src/accounts/webSocketAccountSubscriber.ts +16 -6
  61. package/src/clearingHouse.ts +9 -3
  62. package/src/clearingHouseUser.ts +306 -65
  63. package/src/constants/markets.ts +21 -0
  64. package/src/constants/numericConstants.ts +2 -0
  65. package/src/examples/makeTradeExample.ts +2 -1
  66. package/src/idl/clearing_house.json +94 -42
  67. package/src/index.ts +4 -1
  68. package/src/math/amm.ts +120 -13
  69. package/src/math/funding.ts +47 -25
  70. package/src/math/insuranceFund.ts +29 -0
  71. package/src/math/position.ts +16 -28
  72. package/src/math/trade.ts +9 -5
  73. package/src/types.ts +0 -14
  74. package/src/util/computeUnits.ts +21 -0
  75. package/src/util/tps.ts +27 -0
  76. package/src/wallet.ts +22 -0
  77. package/.eslintrc.json +0 -36
  78. package/.prettierignore +0 -1
  79. package/.prettierrc.js +0 -9
  80. package/lib/accounts/defaultHistoryAccountSubscriber.d.ts +0 -29
  81. package/lib/accounts/defaultHistoryAccountSubscriber.d.ts.map +0 -1
  82. package/lib/accounts/defaultHistoryAccountSubscriber.js +0 -110
  83. package/src/accounts/defaultHistoryAccountSubscriber.ts +0 -179
@@ -0,0 +1,29 @@
1
+ import { MarketsAccount, StateAccount } from '../types';
2
+ import BN from 'bn.js';
3
+ import { Connection } from '@solana/web3.js';
4
+
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
+ export async function calculateInsuranceFundSize(
16
+ connection: Connection,
17
+ state: StateAccount,
18
+ marketsAccount: MarketsAccount
19
+ ): Promise<BN> {
20
+ const insuranceVaultPublicKey = state.insuranceVault;
21
+ const insuranceVaultAmount = new BN(
22
+ (
23
+ await connection.getTokenAccountBalance(insuranceVaultPublicKey)
24
+ ).value.amount
25
+ );
26
+ return marketsAccount.markets.reduce((insuranceVaultAmount, market) => {
27
+ return insuranceVaultAmount.add(market.amm.totalFee.div(new BN(2)));
28
+ }, insuranceVaultAmount);
29
+ }
@@ -1,18 +1,16 @@
1
- import { Market, PositionDirection, UserPosition } from '../types';
2
- import {
3
- AMM_TO_QUOTE_PRECISION_RATIO,
4
- MARK_PRICE_PRECISION,
5
- PEG_PRECISION,
6
- QUOTE_PRECISION,
7
- ZERO,
8
- } from '../constants/numericConstants';
9
1
  import BN from 'bn.js';
10
- import { calculateAmmReservesAfterSwap, getSwapDirection } from './amm';
11
2
  import {
12
3
  AMM_RESERVE_PRECISION,
4
+ AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO,
5
+ AMM_TO_QUOTE_PRECISION_RATIO,
13
6
  FUNDING_PAYMENT_PRECISION,
7
+ MARK_PRICE_PRECISION,
8
+ ONE,
14
9
  PRICE_TO_QUOTE_PRECISION,
10
+ ZERO,
15
11
  } from '../constants/numericConstants';
12
+ import { Market, PositionDirection, UserPosition } from '../types';
13
+ import { calculateAmmReservesAfterSwap, getSwapDirection } from './amm';
16
14
 
17
15
  /**
18
16
  * calculateBaseAssetValue
@@ -45,15 +43,13 @@ export function calculateBaseAssetValue(
45
43
  return market.amm.quoteAssetReserve
46
44
  .sub(newQuoteAssetReserve)
47
45
  .mul(market.amm.pegMultiplier)
48
- .div(PEG_PRECISION)
49
- .div(AMM_TO_QUOTE_PRECISION_RATIO);
46
+ .div(AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO);
50
47
 
51
48
  case PositionDirection.LONG:
52
49
  return newQuoteAssetReserve
53
50
  .sub(market.amm.quoteAssetReserve)
54
51
  .mul(market.amm.pegMultiplier)
55
- .div(PEG_PRECISION)
56
- .div(AMM_TO_QUOTE_PRECISION_RATIO);
52
+ .div(AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO);
57
53
  }
58
54
  }
59
55
 
@@ -74,21 +70,13 @@ export function calculatePositionPNL(
74
70
  return ZERO;
75
71
  }
76
72
 
77
- const directionToClose = marketPosition.baseAssetAmount.gt(ZERO)
78
- ? PositionDirection.SHORT
79
- : PositionDirection.LONG;
80
-
81
73
  const baseAssetValue = calculateBaseAssetValue(market, marketPosition);
82
- let pnlAssetAmount;
83
-
84
- switch (directionToClose) {
85
- case PositionDirection.SHORT:
86
- pnlAssetAmount = baseAssetValue.sub(marketPosition.quoteAssetAmount);
87
- break;
88
74
 
89
- case PositionDirection.LONG:
90
- pnlAssetAmount = marketPosition.quoteAssetAmount.sub(baseAssetValue);
91
- break;
75
+ let pnl;
76
+ if (marketPosition.baseAssetAmount.gt(ZERO)) {
77
+ pnl = baseAssetValue.sub(marketPosition.quoteAssetAmount);
78
+ } else {
79
+ pnl = marketPosition.quoteAssetAmount.sub(baseAssetValue).sub(ONE);
92
80
  }
93
81
 
94
82
  if (withFunding) {
@@ -97,10 +85,10 @@ export function calculatePositionPNL(
97
85
  marketPosition
98
86
  ).div(PRICE_TO_QUOTE_PRECISION);
99
87
 
100
- pnlAssetAmount = pnlAssetAmount.add(fundingRatePnL);
88
+ pnl = pnl.add(fundingRatePnL);
101
89
  }
102
90
 
103
- return pnlAssetAmount;
91
+ return pnl;
104
92
  }
105
93
 
106
94
  /**
package/src/math/trade.ts CHANGED
@@ -146,7 +146,8 @@ export function calculateTradeAcquiredAmounts(
146
146
  export function calculateTargetPriceTrade(
147
147
  market: Market,
148
148
  targetPrice: BN,
149
- pct: BN = MAXPCT
149
+ pct: BN = MAXPCT,
150
+ outputAssetType: AssetType = 'quote'
150
151
  ): [PositionDirection, BN, BN, BN] {
151
152
  assert(market.amm.baseAssetReserve.gt(ZERO));
152
153
  assert(targetPrice.gt(ZERO));
@@ -199,7 +200,7 @@ export function calculateTargetPriceTrade(
199
200
  .mul(peg)
200
201
  .div(PEG_PRECISION)
201
202
  .div(AMM_TO_QUOTE_PRECISION_RATIO);
202
- baseSize = baseAssetReserveBefore.sub(baseAssetReserveAfter);
203
+ baseSize = baseAssetReserveAfter.sub(baseAssetReserveBefore);
203
204
  } else if (markPriceBefore.lt(targetPrice)) {
204
205
  // underestimate y2
205
206
  baseAssetReserveAfter = squareRootBN(
@@ -221,7 +222,7 @@ export function calculateTargetPriceTrade(
221
222
  .mul(peg)
222
223
  .div(PEG_PRECISION)
223
224
  .div(AMM_TO_QUOTE_PRECISION_RATIO);
224
- baseSize = baseAssetReserveAfter.sub(baseAssetReserveBefore);
225
+ baseSize = baseAssetReserveBefore.sub(baseAssetReserveAfter);
225
226
  } else {
226
227
  // no trade, market is at target
227
228
  direction = PositionDirection.LONG;
@@ -254,6 +255,9 @@ export function calculateTargetPriceTrade(
254
255
  'err: ' +
255
256
  tp2.sub(tp1).abs().toString()
256
257
  );
257
-
258
- return [direction, tradeSize, entryPrice, targetPrice];
258
+ if (outputAssetType == 'quote') {
259
+ return [direction, tradeSize, entryPrice, targetPrice];
260
+ } else {
261
+ return [direction, baseSize, entryPrice, targetPrice];
262
+ }
259
263
  }
package/src/types.ts CHANGED
@@ -244,9 +244,6 @@ export type UserPosition = {
244
244
  lastCumulativeFundingRate: BN;
245
245
  marketIndex: BN;
246
246
  quoteAssetAmount: BN;
247
- unrealizedPnl?: BN;
248
- unrealizedFundingPnl?: BN;
249
- baseAssetValue?: BN;
250
247
  };
251
248
 
252
249
  export type UserPositionsAccount = {
@@ -262,17 +259,6 @@ export type UserAccount = {
262
259
  totalFeePaid: BN;
263
260
  };
264
261
 
265
- export type UserSnapshotRecord = {
266
- ts: BN;
267
- userAuthority: PublicKey;
268
- user: PublicKey;
269
- userPositions: UserPosition[];
270
- userTotalRealizedPnl: BN;
271
- userTotalUnrealizedPnl: BN;
272
- userTotalUnrealizedFundingPnl: BN;
273
- userCollateral: BN;
274
- };
275
-
276
262
  // # Misc Types
277
263
  export interface IWallet {
278
264
  signTransaction(tx: Transaction): Promise<Transaction>;
@@ -0,0 +1,21 @@
1
+ import { Connection, Finality, PublicKey } from '@solana/web3.js';
2
+
3
+ export async function findComputeUnitConsumption(
4
+ programId: PublicKey,
5
+ connection: Connection,
6
+ txSignature: string,
7
+ commitment: Finality = 'confirmed'
8
+ ): Promise<number[]> {
9
+ const tx = await connection.getTransaction(txSignature, { commitment });
10
+ const computeUnits = [];
11
+ const regex = new RegExp(
12
+ `Program ${programId.toString()} consumed ([0-9]{0,6}) of 200000 compute units`
13
+ );
14
+ tx.meta.logMessages.forEach((logMessage) => {
15
+ const match = logMessage.match(regex);
16
+ if (match && match[1]) {
17
+ computeUnits.push(match[1]);
18
+ }
19
+ });
20
+ return computeUnits;
21
+ }
@@ -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
+ }
package/src/wallet.ts ADDED
@@ -0,0 +1,22 @@
1
+ import { Keypair, PublicKey, Transaction } from '@solana/web3.js';
2
+ import { IWallet } from './types';
3
+
4
+ export class Wallet implements IWallet {
5
+ constructor(readonly payer: Keypair) {}
6
+
7
+ async signTransaction(tx: Transaction): Promise<Transaction> {
8
+ tx.partialSign(this.payer);
9
+ return tx;
10
+ }
11
+
12
+ async signAllTransactions(txs: Transaction[]): Promise<Transaction[]> {
13
+ return txs.map((t) => {
14
+ t.partialSign(this.payer);
15
+ return t;
16
+ });
17
+ }
18
+
19
+ get publicKey(): PublicKey {
20
+ return this.payer.publicKey;
21
+ }
22
+ }
package/.eslintrc.json DELETED
@@ -1,36 +0,0 @@
1
- {
2
- "root": true,
3
- "parser": "@typescript-eslint/parser",
4
- "env": {
5
- "browser": true
6
- },
7
- "ignorePatterns": ["**/lib"],
8
- "plugins": [],
9
- "extends": [
10
- "eslint:recommended",
11
- "plugin:@typescript-eslint/eslint-recommended",
12
- "plugin:@typescript-eslint/recommended"
13
- ],
14
- "rules": {
15
- "@typescript-eslint/explicit-function-return-type": "off",
16
- "@typescript-eslint/ban-ts-ignore": "off",
17
- "@typescript-eslint/ban-ts-comment": "off",
18
- "@typescript-eslint/no-explicit-any": "off",
19
- "@typescript-eslint/no-unused-vars": [
20
- 2,
21
- {
22
- "argsIgnorePattern": "^_",
23
- "varsIgnorePattern": "^_"
24
- }
25
- ],
26
- "@typescript-eslint/no-var-requires": 0,
27
- "@typescript-eslint/no-empty-function": 0,
28
- "no-mixed-spaces-and-tabs": [2, "smart-tabs"],
29
- "semi": 2
30
- },
31
- "settings": {
32
- "react": {
33
- "version": "detect"
34
- }
35
- }
36
- }
package/.prettierignore DELETED
@@ -1 +0,0 @@
1
- **/node_modules/**
package/.prettierrc.js DELETED
@@ -1,9 +0,0 @@
1
- module.exports = {
2
- semi: true,
3
- trailingComma: 'es5',
4
- singleQuote: true,
5
- printWidth: 80,
6
- tabWidth: 2,
7
- useTabs: true,
8
- bracketSameLine: false,
9
- };
@@ -1,29 +0,0 @@
1
- /// <reference types="node" />
2
- import { ClearingHouseAccountEvents, HistoryAccountSubscriber } from './types';
3
- import { AccountSubscriber } from './types';
4
- import { CurveHistoryAccount, DepositHistoryAccount, FundingPaymentHistoryAccount, FundingRateHistoryAccount, LiquidationHistoryAccount, TradeHistoryAccount } from '../types';
5
- import { Program } from '@project-serum/anchor';
6
- import StrictEventEmitter from 'strict-event-emitter-types';
7
- import { EventEmitter } from 'events';
8
- export declare class DefaultHistoryAccountSubscriber implements HistoryAccountSubscriber {
9
- isSubscribed: boolean;
10
- program: Program;
11
- eventEmitter: StrictEventEmitter<EventEmitter, ClearingHouseAccountEvents>;
12
- tradeHistoryAccountSubscriber?: AccountSubscriber<TradeHistoryAccount>;
13
- depositHistoryAccountSubscriber?: AccountSubscriber<DepositHistoryAccount>;
14
- fundingPaymentHistoryAccountSubscriber?: AccountSubscriber<FundingPaymentHistoryAccount>;
15
- fundingRateHistoryAccountSubscriber?: AccountSubscriber<FundingRateHistoryAccount>;
16
- curveHistoryAccountSubscriber?: AccountSubscriber<CurveHistoryAccount>;
17
- liquidationHistoryAccountSubscriber?: AccountSubscriber<LiquidationHistoryAccount>;
18
- constructor(program: Program);
19
- subscribe(): Promise<boolean>;
20
- unsubscribe(): Promise<void>;
21
- assertIsSubscribed(): void;
22
- getTradeHistoryAccount(): TradeHistoryAccount;
23
- getDepositHistoryAccount(): DepositHistoryAccount;
24
- getFundingPaymentHistoryAccount(): FundingPaymentHistoryAccount;
25
- getFundingRateHistoryAccount(): FundingRateHistoryAccount;
26
- getCurveHistoryAccount(): CurveHistoryAccount;
27
- getLiquidationHistoryAccount(): LiquidationHistoryAccount;
28
- }
29
- //# sourceMappingURL=defaultHistoryAccountSubscriber.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"defaultHistoryAccountSubscriber.d.ts","sourceRoot":"","sources":["../../src/accounts/defaultHistoryAccountSubscriber.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,0BAA0B,EAAE,wBAAwB,EAAE,MAAM,SAAS,CAAC;AAC/E,OAAO,EAAE,iBAAiB,EAAsB,MAAM,SAAS,CAAC;AAChE,OAAO,EACN,mBAAmB,EACnB,qBAAqB,EACrB,4BAA4B,EAC5B,yBAAyB,EACzB,yBAAyB,EAEzB,mBAAmB,EACnB,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAChD,OAAO,kBAAkB,MAAM,4BAA4B,CAAC;AAC5D,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAItC,qBAAa,+BACZ,YAAW,wBAAwB;IAEnC,YAAY,EAAE,OAAO,CAAC;IACtB,OAAO,EAAE,OAAO,CAAC;IACjB,YAAY,EAAE,kBAAkB,CAAC,YAAY,EAAE,0BAA0B,CAAC,CAAC;IAC3E,6BAA6B,CAAC,EAAE,iBAAiB,CAAC,mBAAmB,CAAC,CAAC;IACvE,+BAA+B,CAAC,EAAE,iBAAiB,CAAC,qBAAqB,CAAC,CAAC;IAC3E,sCAAsC,CAAC,EAAE,iBAAiB,CAAC,4BAA4B,CAAC,CAAC;IACzF,mCAAmC,CAAC,EAAE,iBAAiB,CAAC,yBAAyB,CAAC,CAAC;IACnF,6BAA6B,CAAC,EAAE,iBAAiB,CAAC,mBAAmB,CAAC,CAAC;IACvE,mCAAmC,CAAC,EAAE,iBAAiB,CAAC,yBAAyB,CAAC,CAAC;gBAEhE,OAAO,EAAE,OAAO;IAMtB,SAAS,IAAI,OAAO,CAAC,OAAO,CAAC;IA2F7B,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC;IAczC,kBAAkB,IAAI,IAAI;IAQnB,sBAAsB,IAAI,mBAAmB;IAK7C,wBAAwB,IAAI,qBAAqB;IAKjD,+BAA+B,IAAI,4BAA4B;IAK/D,4BAA4B,IAAI,yBAAyB;IAKzD,sBAAsB,IAAI,mBAAmB;IAK7C,4BAA4B,IAAI,yBAAyB;CAIhE"}
@@ -1,110 +0,0 @@
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.DefaultHistoryAccountSubscriber = void 0;
13
- const types_1 = require("./types");
14
- const events_1 = require("events");
15
- const addresses_1 = require("../addresses");
16
- const webSocketAccountSubscriber_1 = require("./webSocketAccountSubscriber");
17
- class DefaultHistoryAccountSubscriber {
18
- constructor(program) {
19
- this.isSubscribed = false;
20
- this.program = program;
21
- this.eventEmitter = new events_1.EventEmitter();
22
- }
23
- subscribe() {
24
- return __awaiter(this, void 0, void 0, function* () {
25
- if (this.isSubscribed) {
26
- return true;
27
- }
28
- const statePublicKey = yield addresses_1.getClearingHouseStateAccountPublicKey(this.program.programId);
29
- const state = yield this.program.account.state.fetch(statePublicKey);
30
- this.tradeHistoryAccountSubscriber = new webSocketAccountSubscriber_1.WebSocketAccountSubscriber('tradeHistory', this.program, state.tradeHistory);
31
- yield this.tradeHistoryAccountSubscriber.subscribe((data) => {
32
- this.eventEmitter.emit('tradeHistoryAccountUpdate', data);
33
- this.eventEmitter.emit('update');
34
- });
35
- this.depositHistoryAccountSubscriber = new webSocketAccountSubscriber_1.WebSocketAccountSubscriber('depositHistory', this.program, state.depositHistory);
36
- yield this.depositHistoryAccountSubscriber.subscribe((data) => {
37
- this.eventEmitter.emit('depositHistoryAccountUpdate', data);
38
- this.eventEmitter.emit('update');
39
- });
40
- this.fundingPaymentHistoryAccountSubscriber =
41
- new webSocketAccountSubscriber_1.WebSocketAccountSubscriber('fundingPaymentHistory', this.program, state.fundingPaymentHistory);
42
- yield this.fundingPaymentHistoryAccountSubscriber.subscribe((data) => {
43
- this.eventEmitter.emit('fundingPaymentHistoryAccountUpdate', data);
44
- this.eventEmitter.emit('update');
45
- });
46
- this.fundingRateHistoryAccountSubscriber = new webSocketAccountSubscriber_1.WebSocketAccountSubscriber('fundingRateHistory', this.program, state.fundingRateHistory);
47
- yield this.fundingRateHistoryAccountSubscriber.subscribe((data) => {
48
- this.eventEmitter.emit('fundingRateHistoryAccountUpdate', data);
49
- this.eventEmitter.emit('update');
50
- });
51
- this.liquidationHistoryAccountSubscriber = new webSocketAccountSubscriber_1.WebSocketAccountSubscriber('liquidationHistory', this.program, state.liquidationHistory);
52
- yield this.liquidationHistoryAccountSubscriber.subscribe((data) => {
53
- this.eventEmitter.emit('liquidationHistoryAccountUpdate', data);
54
- this.eventEmitter.emit('update');
55
- });
56
- this.curveHistoryAccountSubscriber = new webSocketAccountSubscriber_1.WebSocketAccountSubscriber('curveHistory', this.program, state.curveHistory);
57
- yield this.curveHistoryAccountSubscriber.subscribe((data) => {
58
- this.eventEmitter.emit('curveHistoryAccountUpdate', data);
59
- this.eventEmitter.emit('update');
60
- });
61
- this.eventEmitter.emit('update');
62
- this.isSubscribed = true;
63
- return true;
64
- });
65
- }
66
- unsubscribe() {
67
- return __awaiter(this, void 0, void 0, function* () {
68
- if (!this.isSubscribed) {
69
- return;
70
- }
71
- yield this.tradeHistoryAccountSubscriber.unsubscribe();
72
- yield this.fundingRateHistoryAccountSubscriber.unsubscribe();
73
- yield this.fundingPaymentHistoryAccountSubscriber.unsubscribe();
74
- yield this.depositHistoryAccountSubscriber.unsubscribe();
75
- yield this.curveHistoryAccountSubscriber.unsubscribe();
76
- yield this.liquidationHistoryAccountSubscriber.unsubscribe();
77
- this.isSubscribed = false;
78
- });
79
- }
80
- assertIsSubscribed() {
81
- if (!this.isSubscribed) {
82
- throw new types_1.NotSubscribedError('You must call `subscribe` before using this function');
83
- }
84
- }
85
- getTradeHistoryAccount() {
86
- this.assertIsSubscribed();
87
- return this.tradeHistoryAccountSubscriber.data;
88
- }
89
- getDepositHistoryAccount() {
90
- this.assertIsSubscribed();
91
- return this.depositHistoryAccountSubscriber.data;
92
- }
93
- getFundingPaymentHistoryAccount() {
94
- this.assertIsSubscribed();
95
- return this.fundingPaymentHistoryAccountSubscriber.data;
96
- }
97
- getFundingRateHistoryAccount() {
98
- this.assertIsSubscribed();
99
- return this.fundingRateHistoryAccountSubscriber.data;
100
- }
101
- getCurveHistoryAccount() {
102
- this.assertIsSubscribed();
103
- return this.curveHistoryAccountSubscriber.data;
104
- }
105
- getLiquidationHistoryAccount() {
106
- this.assertIsSubscribed();
107
- return this.liquidationHistoryAccountSubscriber.data;
108
- }
109
- }
110
- exports.DefaultHistoryAccountSubscriber = DefaultHistoryAccountSubscriber;
@@ -1,179 +0,0 @@
1
- import { ClearingHouseAccountEvents, HistoryAccountSubscriber } from './types';
2
- import { AccountSubscriber, NotSubscribedError } from './types';
3
- import {
4
- CurveHistoryAccount,
5
- DepositHistoryAccount,
6
- FundingPaymentHistoryAccount,
7
- FundingRateHistoryAccount,
8
- LiquidationHistoryAccount,
9
- StateAccount,
10
- TradeHistoryAccount,
11
- } from '../types';
12
- import { Program } from '@project-serum/anchor';
13
- import StrictEventEmitter from 'strict-event-emitter-types';
14
- import { EventEmitter } from 'events';
15
- import { getClearingHouseStateAccountPublicKey } from '../addresses';
16
- import { WebSocketAccountSubscriber } from './webSocketAccountSubscriber';
17
-
18
- export class DefaultHistoryAccountSubscriber
19
- implements HistoryAccountSubscriber
20
- {
21
- isSubscribed: boolean;
22
- program: Program;
23
- eventEmitter: StrictEventEmitter<EventEmitter, ClearingHouseAccountEvents>;
24
- tradeHistoryAccountSubscriber?: AccountSubscriber<TradeHistoryAccount>;
25
- depositHistoryAccountSubscriber?: AccountSubscriber<DepositHistoryAccount>;
26
- fundingPaymentHistoryAccountSubscriber?: AccountSubscriber<FundingPaymentHistoryAccount>;
27
- fundingRateHistoryAccountSubscriber?: AccountSubscriber<FundingRateHistoryAccount>;
28
- curveHistoryAccountSubscriber?: AccountSubscriber<CurveHistoryAccount>;
29
- liquidationHistoryAccountSubscriber?: AccountSubscriber<LiquidationHistoryAccount>;
30
-
31
- public constructor(program: Program) {
32
- this.isSubscribed = false;
33
- this.program = program;
34
- this.eventEmitter = new EventEmitter();
35
- }
36
-
37
- public async subscribe(): Promise<boolean> {
38
- if (this.isSubscribed) {
39
- return true;
40
- }
41
-
42
- const statePublicKey = await getClearingHouseStateAccountPublicKey(
43
- this.program.programId
44
- );
45
- const state: StateAccount = await this.program.account.state.fetch(
46
- statePublicKey
47
- );
48
-
49
- this.tradeHistoryAccountSubscriber = new WebSocketAccountSubscriber(
50
- 'tradeHistory',
51
- this.program,
52
- state.tradeHistory
53
- );
54
- await this.tradeHistoryAccountSubscriber.subscribe(
55
- (data: TradeHistoryAccount) => {
56
- this.eventEmitter.emit('tradeHistoryAccountUpdate', data);
57
- this.eventEmitter.emit('update');
58
- }
59
- );
60
-
61
- this.depositHistoryAccountSubscriber = new WebSocketAccountSubscriber(
62
- 'depositHistory',
63
- this.program,
64
- state.depositHistory
65
- );
66
- await this.depositHistoryAccountSubscriber.subscribe(
67
- (data: DepositHistoryAccount) => {
68
- this.eventEmitter.emit('depositHistoryAccountUpdate', data);
69
- this.eventEmitter.emit('update');
70
- }
71
- );
72
-
73
- this.fundingPaymentHistoryAccountSubscriber =
74
- new WebSocketAccountSubscriber(
75
- 'fundingPaymentHistory',
76
- this.program,
77
- state.fundingPaymentHistory
78
- );
79
- await this.fundingPaymentHistoryAccountSubscriber.subscribe(
80
- (data: FundingPaymentHistoryAccount) => {
81
- this.eventEmitter.emit('fundingPaymentHistoryAccountUpdate', data);
82
- this.eventEmitter.emit('update');
83
- }
84
- );
85
-
86
- this.fundingRateHistoryAccountSubscriber = new WebSocketAccountSubscriber(
87
- 'fundingRateHistory',
88
- this.program,
89
- state.fundingRateHistory
90
- );
91
- await this.fundingRateHistoryAccountSubscriber.subscribe(
92
- (data: FundingRateHistoryAccount) => {
93
- this.eventEmitter.emit('fundingRateHistoryAccountUpdate', data);
94
- this.eventEmitter.emit('update');
95
- }
96
- );
97
-
98
- this.liquidationHistoryAccountSubscriber = new WebSocketAccountSubscriber(
99
- 'liquidationHistory',
100
- this.program,
101
- state.liquidationHistory
102
- );
103
- await this.liquidationHistoryAccountSubscriber.subscribe(
104
- (data: LiquidationHistoryAccount) => {
105
- this.eventEmitter.emit('liquidationHistoryAccountUpdate', data);
106
- this.eventEmitter.emit('update');
107
- }
108
- );
109
-
110
- this.curveHistoryAccountSubscriber = new WebSocketAccountSubscriber(
111
- 'curveHistory',
112
- this.program,
113
- state.curveHistory
114
- );
115
- await this.curveHistoryAccountSubscriber.subscribe(
116
- (data: CurveHistoryAccount) => {
117
- this.eventEmitter.emit('curveHistoryAccountUpdate', data);
118
- this.eventEmitter.emit('update');
119
- }
120
- );
121
-
122
- this.eventEmitter.emit('update');
123
-
124
- this.isSubscribed = true;
125
- return true;
126
- }
127
-
128
- public async unsubscribe(): Promise<void> {
129
- if (!this.isSubscribed) {
130
- return;
131
- }
132
-
133
- await this.tradeHistoryAccountSubscriber.unsubscribe();
134
- await this.fundingRateHistoryAccountSubscriber.unsubscribe();
135
- await this.fundingPaymentHistoryAccountSubscriber.unsubscribe();
136
- await this.depositHistoryAccountSubscriber.unsubscribe();
137
- await this.curveHistoryAccountSubscriber.unsubscribe();
138
- await this.liquidationHistoryAccountSubscriber.unsubscribe();
139
- this.isSubscribed = false;
140
- }
141
-
142
- assertIsSubscribed(): void {
143
- if (!this.isSubscribed) {
144
- throw new NotSubscribedError(
145
- 'You must call `subscribe` before using this function'
146
- );
147
- }
148
- }
149
-
150
- public getTradeHistoryAccount(): TradeHistoryAccount {
151
- this.assertIsSubscribed();
152
- return this.tradeHistoryAccountSubscriber.data;
153
- }
154
-
155
- public getDepositHistoryAccount(): DepositHistoryAccount {
156
- this.assertIsSubscribed();
157
- return this.depositHistoryAccountSubscriber.data;
158
- }
159
-
160
- public getFundingPaymentHistoryAccount(): FundingPaymentHistoryAccount {
161
- this.assertIsSubscribed();
162
- return this.fundingPaymentHistoryAccountSubscriber.data;
163
- }
164
-
165
- public getFundingRateHistoryAccount(): FundingRateHistoryAccount {
166
- this.assertIsSubscribed();
167
- return this.fundingRateHistoryAccountSubscriber.data;
168
- }
169
-
170
- public getCurveHistoryAccount(): CurveHistoryAccount {
171
- this.assertIsSubscribed();
172
- return this.curveHistoryAccountSubscriber.data;
173
- }
174
-
175
- public getLiquidationHistoryAccount(): LiquidationHistoryAccount {
176
- this.assertIsSubscribed();
177
- return this.liquidationHistoryAccountSubscriber.data;
178
- }
179
- }