@d8x/perpetuals-sdk 0.7.6 → 0.7.7

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 (119) hide show
  1. package/dist/cjs/accountTrade.js +243 -134
  2. package/dist/cjs/accountTrade.js.map +1 -1
  3. package/dist/cjs/brokerTool.js +290 -144
  4. package/dist/cjs/brokerTool.js.map +1 -1
  5. package/dist/cjs/config/priceFeedConfig.json +1 -1
  6. package/dist/cjs/contracts/factories/ERC20__factory.js +12 -9
  7. package/dist/cjs/contracts/factories/ERC20__factory.js.map +1 -1
  8. package/dist/cjs/contracts/factories/IPerpetualManager__factory.js +12 -9
  9. package/dist/cjs/contracts/factories/IPerpetualManager__factory.js.map +1 -1
  10. package/dist/cjs/contracts/factories/LimitOrderBookFactory__factory.js +12 -9
  11. package/dist/cjs/contracts/factories/LimitOrderBookFactory__factory.js.map +1 -1
  12. package/dist/cjs/contracts/factories/LimitOrderBook__factory.js +12 -9
  13. package/dist/cjs/contracts/factories/LimitOrderBook__factory.js.map +1 -1
  14. package/dist/cjs/contracts/factories/MockTokenSwap__factory.js +12 -9
  15. package/dist/cjs/contracts/factories/MockTokenSwap__factory.js.map +1 -1
  16. package/dist/cjs/contracts/factories/ShareToken__factory.js +12 -9
  17. package/dist/cjs/contracts/factories/ShareToken__factory.js.map +1 -1
  18. package/dist/cjs/contracts/factories/zkevmTestnet/IPerpetualManager__factory.js +12 -9
  19. package/dist/cjs/contracts/factories/zkevmTestnet/IPerpetualManager__factory.js.map +1 -1
  20. package/dist/cjs/contracts/factories/zkevmTestnet/LimitOrderBookFactory__factory.js +12 -9
  21. package/dist/cjs/contracts/factories/zkevmTestnet/LimitOrderBookFactory__factory.js.map +1 -1
  22. package/dist/cjs/contracts/factories/zkevmTestnet/LimitOrderBook__factory.js +12 -9
  23. package/dist/cjs/contracts/factories/zkevmTestnet/LimitOrderBook__factory.js.map +1 -1
  24. package/dist/cjs/contracts/factories/zkevmTestnet/ShareToken__factory.js +12 -9
  25. package/dist/cjs/contracts/factories/zkevmTestnet/ShareToken__factory.js.map +1 -1
  26. package/dist/cjs/contracts/index.js +1 -1
  27. package/dist/cjs/d8XMath.js +66 -65
  28. package/dist/cjs/d8XMath.js.map +1 -1
  29. package/dist/cjs/index.js +11 -11
  30. package/dist/cjs/index.js.map +1 -1
  31. package/dist/cjs/liquidatorTool.js +137 -80
  32. package/dist/cjs/liquidatorTool.js.map +1 -1
  33. package/dist/cjs/liquidityProviderTool.js +65 -33
  34. package/dist/cjs/liquidityProviderTool.js.map +1 -1
  35. package/dist/cjs/marketData.js +978 -635
  36. package/dist/cjs/marketData.js.map +1 -1
  37. package/dist/cjs/nodeSDKTypes.js +22 -10
  38. package/dist/cjs/nodeSDKTypes.js.map +1 -1
  39. package/dist/cjs/orderReferrerTool.js +323 -200
  40. package/dist/cjs/orderReferrerTool.js.map +1 -1
  41. package/dist/cjs/perpetualDataHandler.js +550 -404
  42. package/dist/cjs/perpetualDataHandler.js.map +1 -1
  43. package/dist/cjs/perpetualEventHandler.js +190 -129
  44. package/dist/cjs/perpetualEventHandler.js.map +1 -1
  45. package/dist/cjs/priceFeeds.js +335 -223
  46. package/dist/cjs/priceFeeds.js.map +1 -1
  47. package/dist/cjs/traderDigests.js +23 -20
  48. package/dist/cjs/traderDigests.js.map +1 -1
  49. package/dist/cjs/traderInterface.js +87 -54
  50. package/dist/cjs/traderInterface.js.map +1 -1
  51. package/dist/cjs/triangulator.js +38 -34
  52. package/dist/cjs/triangulator.js.map +1 -1
  53. package/dist/cjs/utils.js +32 -18
  54. package/dist/cjs/utils.js.map +1 -1
  55. package/dist/cjs/version.d.ts +1 -1
  56. package/dist/cjs/version.js +1 -1
  57. package/dist/cjs/writeAccessHandler.js +112 -78
  58. package/dist/cjs/writeAccessHandler.js.map +1 -1
  59. package/dist/esm/accountTrade.js +237 -126
  60. package/dist/esm/accountTrade.js.map +1 -1
  61. package/dist/esm/brokerTool.js +284 -136
  62. package/dist/esm/brokerTool.js.map +1 -1
  63. package/dist/esm/config/priceFeedConfig.json +1 -1
  64. package/dist/esm/contracts/factories/ERC20__factory.js +12 -8
  65. package/dist/esm/contracts/factories/ERC20__factory.js.map +1 -1
  66. package/dist/esm/contracts/factories/IPerpetualManager__factory.js +12 -8
  67. package/dist/esm/contracts/factories/IPerpetualManager__factory.js.map +1 -1
  68. package/dist/esm/contracts/factories/LimitOrderBookFactory__factory.js +12 -8
  69. package/dist/esm/contracts/factories/LimitOrderBookFactory__factory.js.map +1 -1
  70. package/dist/esm/contracts/factories/LimitOrderBook__factory.js +12 -8
  71. package/dist/esm/contracts/factories/LimitOrderBook__factory.js.map +1 -1
  72. package/dist/esm/contracts/factories/MockTokenSwap__factory.js +12 -8
  73. package/dist/esm/contracts/factories/MockTokenSwap__factory.js.map +1 -1
  74. package/dist/esm/contracts/factories/ShareToken__factory.js +12 -8
  75. package/dist/esm/contracts/factories/ShareToken__factory.js.map +1 -1
  76. package/dist/esm/contracts/factories/zkevmTestnet/IPerpetualManager__factory.js +12 -8
  77. package/dist/esm/contracts/factories/zkevmTestnet/IPerpetualManager__factory.js.map +1 -1
  78. package/dist/esm/contracts/factories/zkevmTestnet/LimitOrderBookFactory__factory.js +12 -8
  79. package/dist/esm/contracts/factories/zkevmTestnet/LimitOrderBookFactory__factory.js.map +1 -1
  80. package/dist/esm/contracts/factories/zkevmTestnet/LimitOrderBook__factory.js +12 -8
  81. package/dist/esm/contracts/factories/zkevmTestnet/LimitOrderBook__factory.js.map +1 -1
  82. package/dist/esm/contracts/factories/zkevmTestnet/ShareToken__factory.js +12 -8
  83. package/dist/esm/contracts/factories/zkevmTestnet/ShareToken__factory.js.map +1 -1
  84. package/dist/esm/d8XMath.js +64 -63
  85. package/dist/esm/d8XMath.js.map +1 -1
  86. package/dist/esm/liquidatorTool.js +136 -77
  87. package/dist/esm/liquidatorTool.js.map +1 -1
  88. package/dist/esm/liquidityProviderTool.js +63 -29
  89. package/dist/esm/liquidityProviderTool.js.map +1 -1
  90. package/dist/esm/marketData.js +971 -626
  91. package/dist/esm/marketData.js.map +1 -1
  92. package/dist/esm/nodeSDKTypes.js +48 -36
  93. package/dist/esm/nodeSDKTypes.js.map +1 -1
  94. package/dist/esm/orderReferrerTool.js +319 -194
  95. package/dist/esm/orderReferrerTool.js.map +1 -1
  96. package/dist/esm/perpetualDataHandler.js +542 -394
  97. package/dist/esm/perpetualDataHandler.js.map +1 -1
  98. package/dist/esm/perpetualEventHandler.js +188 -126
  99. package/dist/esm/perpetualEventHandler.js.map +1 -1
  100. package/dist/esm/priceFeeds.js +332 -218
  101. package/dist/esm/priceFeeds.js.map +1 -1
  102. package/dist/esm/traderDigests.js +19 -15
  103. package/dist/esm/traderDigests.js.map +1 -1
  104. package/dist/esm/traderInterface.js +83 -48
  105. package/dist/esm/traderInterface.js.map +1 -1
  106. package/dist/esm/triangulator.js +39 -34
  107. package/dist/esm/triangulator.js.map +1 -1
  108. package/dist/esm/utils.js +30 -16
  109. package/dist/esm/utils.js.map +1 -1
  110. package/dist/esm/version.d.ts +1 -1
  111. package/dist/esm/version.js +1 -1
  112. package/dist/esm/version.js.map +1 -1
  113. package/dist/esm/writeAccessHandler.js +105 -69
  114. package/dist/esm/writeAccessHandler.js.map +1 -1
  115. package/package.json +1 -1
  116. package/src/accountTrade.ts +6 -1
  117. package/src/config/priceFeedConfig.json +1 -1
  118. package/src/orderReferrerTool.ts +2 -0
  119. package/src/version.ts +1 -1
@@ -1,21 +1,21 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const tslib_1 = require("tslib");
4
- const abi_1 = require("@ethersproject/abi");
5
- const abstract_signer_1 = require("@ethersproject/abstract-signer");
6
- const bignumber_1 = require("@ethersproject/bignumber");
7
- const constants_1 = require("@ethersproject/constants");
8
- const contracts_1 = require("./contracts");
9
- const d8XMath_1 = require("./d8XMath");
10
- const nodeSDKTypes_1 = require("./nodeSDKTypes");
11
- const priceFeeds_1 = tslib_1.__importDefault(require("./priceFeeds"));
12
- const utils_1 = require("./utils");
3
+ var tslib_1 = require("tslib");
4
+ var abi_1 = require("@ethersproject/abi");
5
+ var abstract_signer_1 = require("@ethersproject/abstract-signer");
6
+ var bignumber_1 = require("@ethersproject/bignumber");
7
+ var constants_1 = require("@ethersproject/constants");
8
+ var contracts_1 = require("./contracts");
9
+ var d8XMath_1 = require("./d8XMath");
10
+ var nodeSDKTypes_1 = require("./nodeSDKTypes");
11
+ var priceFeeds_1 = tslib_1.__importDefault(require("./priceFeeds"));
12
+ var utils_1 = require("./utils");
13
13
  /**
14
14
  * Parent class for MarketData and WriteAccessHandler that handles
15
15
  * common data and chain operations.
16
16
  */
17
- class PerpetualDataHandler {
18
- constructor(config) {
17
+ var PerpetualDataHandler = /** @class */ (function () {
18
+ function PerpetualDataHandler(config) {
19
19
  this.PRICE_UPDATE_FEE_GWEI = 1;
20
20
  this.proxyContract = null;
21
21
  // limit order book
@@ -37,168 +37,226 @@ class PerpetualDataHandler {
37
37
  this.symbolList = nodeSDKTypes_1.SYMBOL_LIST;
38
38
  this.priceFeedGetter = new priceFeeds_1.default(this, config.priceFeedConfigNetwork);
39
39
  }
40
- async initContractsAndData(signerOrProvider, overrides) {
41
- this.signerOrProvider = signerOrProvider;
42
- // check network
43
- let network;
44
- try {
45
- if (signerOrProvider instanceof abstract_signer_1.Signer) {
46
- network = await signerOrProvider.provider.getNetwork();
47
- }
48
- else {
49
- network = await signerOrProvider.getNetwork();
50
- }
51
- }
52
- catch (error) {
53
- console.log(error);
54
- throw new Error(`Unable to connect to network.`);
55
- }
56
- if (network.chainId !== this.chainId) {
57
- throw new Error(`Provider: chain id ${network.chainId} does not match config (${this.chainId})`);
58
- }
59
- this.proxyContract = contracts_1.IPerpetualManager__factory.connect(this.proxyAddr, signerOrProvider);
60
- this.lobFactoryAddr = await this.proxyContract.getOrderBookFactoryAddress(overrides || {});
61
- this.lobFactoryContract = contracts_1.LimitOrderBookFactory__factory.connect(this.lobFactoryAddr, signerOrProvider);
62
- await this._fillSymbolMaps(overrides);
63
- }
40
+ PerpetualDataHandler.prototype.initContractsAndData = function (signerOrProvider, overrides) {
41
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
42
+ var network, error_1, _a;
43
+ return tslib_1.__generator(this, function (_b) {
44
+ switch (_b.label) {
45
+ case 0:
46
+ this.signerOrProvider = signerOrProvider;
47
+ _b.label = 1;
48
+ case 1:
49
+ _b.trys.push([1, 6, , 7]);
50
+ if (!(signerOrProvider instanceof abstract_signer_1.Signer)) return [3 /*break*/, 3];
51
+ return [4 /*yield*/, signerOrProvider.provider.getNetwork()];
52
+ case 2:
53
+ network = _b.sent();
54
+ return [3 /*break*/, 5];
55
+ case 3: return [4 /*yield*/, signerOrProvider.getNetwork()];
56
+ case 4:
57
+ network = _b.sent();
58
+ _b.label = 5;
59
+ case 5: return [3 /*break*/, 7];
60
+ case 6:
61
+ error_1 = _b.sent();
62
+ console.log(error_1);
63
+ throw new Error("Unable to connect to network.");
64
+ case 7:
65
+ if (network.chainId !== this.chainId) {
66
+ throw new Error("Provider: chain id ".concat(network.chainId, " does not match config (").concat(this.chainId, ")"));
67
+ }
68
+ this.proxyContract = contracts_1.IPerpetualManager__factory.connect(this.proxyAddr, signerOrProvider);
69
+ _a = this;
70
+ return [4 /*yield*/, this.proxyContract.getOrderBookFactoryAddress(overrides || {})];
71
+ case 8:
72
+ _a.lobFactoryAddr = _b.sent();
73
+ this.lobFactoryContract = contracts_1.LimitOrderBookFactory__factory.connect(this.lobFactoryAddr, signerOrProvider);
74
+ return [4 /*yield*/, this._fillSymbolMaps(overrides)];
75
+ case 9:
76
+ _b.sent();
77
+ return [2 /*return*/];
78
+ }
79
+ });
80
+ });
81
+ };
64
82
  /**
65
83
  * Returns the order-book contract for the symbol if found or fails
66
84
  * @param symbol symbol of the form ETH-USD-MATIC
67
85
  * @returns order book contract for the perpetual
68
86
  */
69
- getOrderBookContract(symbol) {
70
- let orderBookAddr = this.symbolToPerpStaticInfo.get(symbol)?.limitOrderBookAddr;
87
+ PerpetualDataHandler.prototype.getOrderBookContract = function (symbol) {
88
+ var _a;
89
+ var orderBookAddr = (_a = this.symbolToPerpStaticInfo.get(symbol)) === null || _a === void 0 ? void 0 : _a.limitOrderBookAddr;
71
90
  if (orderBookAddr == "" || orderBookAddr == undefined || this.signerOrProvider == null) {
72
- throw Error(`no limit order book found for ${symbol} or no signer`);
91
+ throw Error("no limit order book found for ".concat(symbol, " or no signer"));
73
92
  }
74
- let lobContract = contracts_1.LimitOrderBook__factory.connect(orderBookAddr, this.signerOrProvider);
93
+ var lobContract = contracts_1.LimitOrderBook__factory.connect(orderBookAddr, this.signerOrProvider);
75
94
  return lobContract;
76
- }
95
+ };
77
96
  /**
78
97
  * Called when initializing. This function fills this.symbolToTokenAddrMap,
79
98
  * and this.nestedPerpetualIDs and this.symbolToPerpStaticInfo
80
99
  *
81
100
  */
82
- async _fillSymbolMaps(overrides) {
83
- if (!this.proxyContract || !this.lobFactoryContract) {
84
- throw Error("proxy or limit order book not defined");
85
- }
86
- let poolInfo = await PerpetualDataHandler.getPoolStaticInfo(this.proxyContract, overrides);
87
- this.nestedPerpetualIDs = poolInfo.nestedPerpetualIDs;
88
- for (let j = 0; j < poolInfo.nestedPerpetualIDs.length; j++) {
89
- let decimals = await contracts_1.ERC20__factory.connect(poolInfo.poolMarginTokenAddr[j], this.provider).decimals();
90
- let info = {
91
- poolId: j + 1,
92
- poolMarginSymbol: "",
93
- poolMarginTokenAddr: poolInfo.poolMarginTokenAddr[j],
94
- poolMarginTokenDecimals: decimals,
95
- shareTokenAddr: poolInfo.poolShareTokenAddr[j],
96
- oracleFactoryAddr: poolInfo.oracleFactory,
97
- isRunning: poolInfo.poolShareTokenAddr[j] != constants_1.AddressZero,
98
- };
99
- this.poolStaticInfos.push(info);
100
- }
101
- let perpStaticInfos = await PerpetualDataHandler.getPerpetualStaticInfo(this.proxyContract, this.nestedPerpetualIDs, this.symbolList, overrides);
102
- let requiredPairs = new Set();
103
- // 1) determine pool currency based on its perpetuals
104
- // 2) determine which triangulations we need
105
- // 3) fill mapping this.symbolToPerpStaticInf
106
- for (let j = 0; j < perpStaticInfos.length; j++) {
107
- const perp = perpStaticInfos[j];
108
- requiredPairs.add(perp.S2Symbol);
109
- if (perp.S3Symbol != "") {
110
- requiredPairs.add(perp.S3Symbol);
111
- }
112
- let poolCCY = this.poolStaticInfos[perp.poolId - 1].poolMarginSymbol;
113
- if (poolCCY == "") {
114
- //not already filled
115
- const [base, quote] = perp.S2Symbol.split("-");
116
- const base3 = perp.S3Symbol.split("-")[0];
117
- // we find out the pool currency by looking at all perpetuals
118
- // from the perpetual.
119
- if (perp.collateralCurrencyType == nodeSDKTypes_1.COLLATERAL_CURRENCY_BASE) {
120
- poolCCY = base;
101
+ PerpetualDataHandler.prototype._fillSymbolMaps = function (overrides) {
102
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
103
+ var poolInfo, j, decimals, info, perpStaticInfos, requiredPairs, j, perp, poolCCY, _a, base, quote, base3, currentSymbol3, _b, _c, _d, key, info;
104
+ var e_1, _e;
105
+ return tslib_1.__generator(this, function (_f) {
106
+ switch (_f.label) {
107
+ case 0:
108
+ if (!this.proxyContract || !this.lobFactoryContract) {
109
+ throw Error("proxy or limit order book not defined");
110
+ }
111
+ return [4 /*yield*/, PerpetualDataHandler.getPoolStaticInfo(this.proxyContract, overrides)];
112
+ case 1:
113
+ poolInfo = _f.sent();
114
+ this.nestedPerpetualIDs = poolInfo.nestedPerpetualIDs;
115
+ j = 0;
116
+ _f.label = 2;
117
+ case 2:
118
+ if (!(j < poolInfo.nestedPerpetualIDs.length)) return [3 /*break*/, 5];
119
+ return [4 /*yield*/, contracts_1.ERC20__factory.connect(poolInfo.poolMarginTokenAddr[j], this.provider).decimals()];
120
+ case 3:
121
+ decimals = _f.sent();
122
+ info = {
123
+ poolId: j + 1,
124
+ poolMarginSymbol: "",
125
+ poolMarginTokenAddr: poolInfo.poolMarginTokenAddr[j],
126
+ poolMarginTokenDecimals: decimals,
127
+ shareTokenAddr: poolInfo.poolShareTokenAddr[j],
128
+ oracleFactoryAddr: poolInfo.oracleFactory,
129
+ isRunning: poolInfo.poolShareTokenAddr[j] != constants_1.AddressZero,
130
+ };
131
+ this.poolStaticInfos.push(info);
132
+ _f.label = 4;
133
+ case 4:
134
+ j++;
135
+ return [3 /*break*/, 2];
136
+ case 5: return [4 /*yield*/, PerpetualDataHandler.getPerpetualStaticInfo(this.proxyContract, this.nestedPerpetualIDs, this.symbolList, overrides)];
137
+ case 6:
138
+ perpStaticInfos = _f.sent();
139
+ requiredPairs = new Set();
140
+ // 1) determine pool currency based on its perpetuals
141
+ // 2) determine which triangulations we need
142
+ // 3) fill mapping this.symbolToPerpStaticInf
143
+ for (j = 0; j < perpStaticInfos.length; j++) {
144
+ perp = perpStaticInfos[j];
145
+ requiredPairs.add(perp.S2Symbol);
146
+ if (perp.S3Symbol != "") {
147
+ requiredPairs.add(perp.S3Symbol);
148
+ }
149
+ poolCCY = this.poolStaticInfos[perp.poolId - 1].poolMarginSymbol;
150
+ if (poolCCY == "") {
151
+ _a = tslib_1.__read(perp.S2Symbol.split("-"), 2), base = _a[0], quote = _a[1];
152
+ base3 = perp.S3Symbol.split("-")[0];
153
+ // we find out the pool currency by looking at all perpetuals
154
+ // from the perpetual.
155
+ if (perp.collateralCurrencyType == nodeSDKTypes_1.COLLATERAL_CURRENCY_BASE) {
156
+ poolCCY = base;
157
+ }
158
+ else if (perp.collateralCurrencyType == nodeSDKTypes_1.COLLATERAL_CURRENCY_QUOTE) {
159
+ poolCCY = quote;
160
+ }
161
+ else {
162
+ poolCCY = base3;
163
+ }
164
+ // set pool currency
165
+ this.poolStaticInfos[perp.poolId - 1].poolMarginSymbol = poolCCY;
166
+ // push pool margin token address into map
167
+ this.symbolToTokenAddrMap.set(poolCCY, this.poolStaticInfos[perp.poolId - 1].poolMarginTokenAddr);
168
+ }
169
+ currentSymbol3 = perp.S2Symbol + "-" + poolCCY;
170
+ this.symbolToPerpStaticInfo.set(currentSymbol3, perpStaticInfos[j]);
171
+ }
172
+ // pre-calculate all triangulation paths so we can easily get from
173
+ // the prices of price-feeds to the index price required, e.g.
174
+ // BTC-USDC : BTC-USD / USDC-USD
175
+ this.priceFeedGetter.initializeTriangulations(requiredPairs);
176
+ try {
177
+ // fill this.perpetualIdToSymbol
178
+ for (_b = tslib_1.__values(this.symbolToPerpStaticInfo), _c = _b.next(); !_c.done; _c = _b.next()) {
179
+ _d = tslib_1.__read(_c.value, 2), key = _d[0], info = _d[1];
180
+ this.perpetualIdToSymbol.set(info.id, key);
181
+ }
182
+ }
183
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
184
+ finally {
185
+ try {
186
+ if (_c && !_c.done && (_e = _b.return)) _e.call(_b);
187
+ }
188
+ finally { if (e_1) throw e_1.error; }
189
+ }
190
+ return [2 /*return*/];
121
191
  }
122
- else if (perp.collateralCurrencyType == nodeSDKTypes_1.COLLATERAL_CURRENCY_QUOTE) {
123
- poolCCY = quote;
124
- }
125
- else {
126
- poolCCY = base3;
127
- }
128
- // set pool currency
129
- this.poolStaticInfos[perp.poolId - 1].poolMarginSymbol = poolCCY;
130
- // push pool margin token address into map
131
- this.symbolToTokenAddrMap.set(poolCCY, this.poolStaticInfos[perp.poolId - 1].poolMarginTokenAddr);
132
- }
133
- let currentSymbol3 = perp.S2Symbol + "-" + poolCCY;
134
- this.symbolToPerpStaticInfo.set(currentSymbol3, perpStaticInfos[j]);
135
- }
136
- // pre-calculate all triangulation paths so we can easily get from
137
- // the prices of price-feeds to the index price required, e.g.
138
- // BTC-USDC : BTC-USD / USDC-USD
139
- this.priceFeedGetter.initializeTriangulations(requiredPairs);
140
- // fill this.perpetualIdToSymbol
141
- for (let [key, info] of this.symbolToPerpStaticInfo) {
142
- this.perpetualIdToSymbol.set(info.id, key);
143
- }
144
- }
192
+ });
193
+ });
194
+ };
145
195
  /**
146
196
  * Get pool symbol given a pool Id.
147
197
  * @param {number} poolId Pool Id.
148
198
  * @returns {symbol} Pool symbol, e.g. "USDC".
149
199
  */
150
- getSymbolFromPoolId(poolId) {
200
+ PerpetualDataHandler.prototype.getSymbolFromPoolId = function (poolId) {
151
201
  return PerpetualDataHandler._getSymbolFromPoolId(poolId, this.poolStaticInfos);
152
- }
202
+ };
153
203
  /**
154
204
  * Get pool Id given a pool symbol. Pool IDs start at 1.
155
205
  * @param {string} symbol Pool symbol.
156
206
  * @returns {number} Pool Id.
157
207
  */
158
- getPoolIdFromSymbol(symbol) {
208
+ PerpetualDataHandler.prototype.getPoolIdFromSymbol = function (symbol) {
159
209
  return PerpetualDataHandler._getPoolIdFromSymbol(symbol, this.poolStaticInfos);
160
- }
210
+ };
161
211
  /**
162
212
  * Get perpetual Id given a perpetual symbol.
163
213
  * @param {string} symbol Perpetual symbol, e.g. "BTC-USD-MATIC".
164
214
  * @returns {number} Perpetual Id.
165
215
  */
166
- getPerpIdFromSymbol(symbol) {
216
+ PerpetualDataHandler.prototype.getPerpIdFromSymbol = function (symbol) {
167
217
  return PerpetualDataHandler.symbolToPerpetualId(symbol, this.symbolToPerpStaticInfo);
168
- }
218
+ };
169
219
  /**
170
220
  * Get the symbol in long format of the perpetual id
171
221
  * @param perpId perpetual id
172
222
  */
173
- getSymbolFromPerpId(perpId) {
223
+ PerpetualDataHandler.prototype.getSymbolFromPerpId = function (perpId) {
174
224
  return this.perpetualIdToSymbol.get(perpId);
175
- }
176
- symbol4BToLongSymbol(sym) {
225
+ };
226
+ PerpetualDataHandler.prototype.symbol4BToLongSymbol = function (sym) {
177
227
  return (0, utils_1.symbol4BToLongSymbol)(sym, this.symbolList);
178
- }
228
+ };
179
229
  /**
180
230
  * Get PriceFeedSubmission data required for blockchain queries that involve price data, and the corresponding
181
231
  * triangulated prices for the indices S2 and S3
182
232
  * @param symbol pool symbol of the form "ETH-USD-MATIC"
183
233
  * @returns PriceFeedSubmission and prices for S2 and S3. [S2price, 0] if S3 not defined.
184
234
  */
185
- async fetchPriceSubmissionInfoForPerpetual(symbol) {
186
- // fetch prices from required price-feeds (REST)
187
- return await this.priceFeedGetter.fetchFeedPriceInfoAndIndicesForPerpetual(symbol);
188
- }
235
+ PerpetualDataHandler.prototype.fetchPriceSubmissionInfoForPerpetual = function (symbol) {
236
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
237
+ return tslib_1.__generator(this, function (_a) {
238
+ switch (_a.label) {
239
+ case 0: return [4 /*yield*/, this.priceFeedGetter.fetchFeedPriceInfoAndIndicesForPerpetual(symbol)];
240
+ case 1:
241
+ // fetch prices from required price-feeds (REST)
242
+ return [2 /*return*/, _a.sent()];
243
+ }
244
+ });
245
+ });
246
+ };
189
247
  /**
190
248
  * Get the symbols required as indices for the given perpetual
191
249
  * @param symbol of the form ETH-USD-MATIC, specifying the perpetual
192
250
  * @returns name of underlying index prices, e.g. ["MATIC-USD", ""]
193
251
  */
194
- getIndexSymbols(symbol) {
252
+ PerpetualDataHandler.prototype.getIndexSymbols = function (symbol) {
195
253
  // get index
196
- let staticInfo = this.symbolToPerpStaticInfo.get(symbol);
254
+ var staticInfo = this.symbolToPerpStaticInfo.get(symbol);
197
255
  if (staticInfo == undefined) {
198
- throw new Error(`No static info for perpetual with symbol ${symbol}`);
256
+ throw new Error("No static info for perpetual with symbol ".concat(symbol));
199
257
  }
200
258
  return [staticInfo.S2Symbol, staticInfo.S3Symbol];
201
- }
259
+ };
202
260
  /**
203
261
  * Get the latest prices for a given perpetual from the offchain oracle
204
262
  * networks
@@ -206,60 +264,68 @@ class PerpetualDataHandler {
206
264
  * @returns array of price feed updates that can be submitted to the smart contract
207
265
  * and corresponding price information
208
266
  */
209
- async fetchLatestFeedPriceInfo(symbol) {
210
- return await this.priceFeedGetter.fetchLatestFeedPriceInfoForPerpetual(symbol);
211
- }
267
+ PerpetualDataHandler.prototype.fetchLatestFeedPriceInfo = function (symbol) {
268
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
269
+ return tslib_1.__generator(this, function (_a) {
270
+ switch (_a.label) {
271
+ case 0: return [4 /*yield*/, this.priceFeedGetter.fetchLatestFeedPriceInfoForPerpetual(symbol)];
272
+ case 1: return [2 /*return*/, _a.sent()];
273
+ }
274
+ });
275
+ });
276
+ };
212
277
  /**
213
278
  * Get list of required pyth price source IDs for given perpetual
214
279
  * @param symbol perpetual symbol, e.g., BTC-USD-MATIC
215
280
  * @returns list of required pyth price sources for this perpetual
216
281
  */
217
- getPriceIds(symbol) {
218
- let perpInfo = this.symbolToPerpStaticInfo.get(symbol);
282
+ PerpetualDataHandler.prototype.getPriceIds = function (symbol) {
283
+ var perpInfo = this.symbolToPerpStaticInfo.get(symbol);
219
284
  if (perpInfo == undefined) {
220
- throw Error(`Perpetual with symbol ${symbol} not found. Check symbol or use createProxyInstance().`);
285
+ throw Error("Perpetual with symbol ".concat(symbol, " not found. Check symbol or use createProxyInstance()."));
221
286
  }
222
287
  return perpInfo.priceIds;
223
- }
224
- static _getSymbolFromPoolId(poolId, staticInfos) {
225
- let idx = poolId - 1;
288
+ };
289
+ PerpetualDataHandler._getSymbolFromPoolId = function (poolId, staticInfos) {
290
+ var idx = poolId - 1;
226
291
  return staticInfos[idx].poolMarginSymbol;
227
- }
228
- static _getPoolIdFromSymbol(symbol, staticInfos) {
229
- let symbols = symbol.split("-");
292
+ };
293
+ PerpetualDataHandler._getPoolIdFromSymbol = function (symbol, staticInfos) {
294
+ var symbols = symbol.split("-");
230
295
  //in case user provided ETH-USD-MATIC instead of MATIC; or similar
231
296
  if (symbols.length == 3) {
232
297
  symbol = symbols[2];
233
298
  }
234
- let j = 0;
299
+ var j = 0;
235
300
  while (j < staticInfos.length && staticInfos[j].poolMarginSymbol != symbol) {
236
301
  j++;
237
302
  }
238
303
  if (j == staticInfos.length) {
239
- throw new Error(`no pool found for symbol ${symbol}`);
304
+ throw new Error("no pool found for symbol ".concat(symbol));
240
305
  }
241
306
  return j + 1;
242
- }
307
+ };
243
308
  /**
244
309
  * Get perpetual symbols for a given pool
245
310
  * @param poolSymbol pool symbol such as "MATIC"
246
311
  * @returns array of perpetual symbols in this pool
247
312
  */
248
- getPerpetualSymbolsInPool(poolSymbol) {
249
- const j = PerpetualDataHandler._getPoolIdFromSymbol(poolSymbol, this.poolStaticInfos);
250
- const perpIds = this.nestedPerpetualIDs[j - 1];
251
- const perpSymbols = perpIds.map((k) => {
252
- let s = this.getSymbolFromPerpId(k);
313
+ PerpetualDataHandler.prototype.getPerpetualSymbolsInPool = function (poolSymbol) {
314
+ var _this = this;
315
+ var j = PerpetualDataHandler._getPoolIdFromSymbol(poolSymbol, this.poolStaticInfos);
316
+ var perpIds = this.nestedPerpetualIDs[j - 1];
317
+ var perpSymbols = perpIds.map(function (k) {
318
+ var s = _this.getSymbolFromPerpId(k);
253
319
  if (s == undefined) {
254
320
  return "";
255
321
  }
256
322
  return s;
257
323
  });
258
324
  return perpSymbols;
259
- }
260
- getNestedPerpetualIds() {
325
+ };
326
+ PerpetualDataHandler.prototype.getNestedPerpetualIds = function () {
261
327
  return this.nestedPerpetualIDs;
262
- }
328
+ };
263
329
  /**
264
330
  * Collect all perpetuals static info
265
331
  * @param {ethers.Contract} _proxyContract perpetuals contract with getter
@@ -267,51 +333,65 @@ class PerpetualDataHandler {
267
333
  * @param {Map<string, string>} symbolList mapping of symbols to convert long-format <-> blockchain-format
268
334
  * @returns array with PerpetualStaticInfo for each perpetual
269
335
  */
270
- static async getPerpetualStaticInfo(_proxyContract, nestedPerpetualIDs, symbolList, overrides) {
271
- // flatten perpetual ids into chunks
272
- const chunkSize = 10;
273
- let ids = PerpetualDataHandler.nestedIDsToChunks(chunkSize, nestedPerpetualIDs);
274
- // query blockchain in chunks
275
- const infoArr = new Array();
276
- for (let k = 0; k < ids.length; k++) {
277
- let perpInfos = await _proxyContract.getPerpetualStaticInfo(ids[k], overrides || {});
278
- for (let j = 0; j < perpInfos.length; j++) {
279
- let base = (0, utils_1.contractSymbolToSymbol)(perpInfos[j].S2BaseCCY, symbolList);
280
- let quote = (0, utils_1.contractSymbolToSymbol)(perpInfos[j].S2QuoteCCY, symbolList);
281
- let base3 = (0, utils_1.contractSymbolToSymbol)(perpInfos[j].S3BaseCCY, symbolList);
282
- let quote3 = (0, utils_1.contractSymbolToSymbol)(perpInfos[j].S3QuoteCCY, symbolList);
283
- let sym2 = base + "-" + quote;
284
- let sym3 = base3 == "" ? "" : base3 + "-" + quote3;
285
- let info = {
286
- id: perpInfos[j].id,
287
- poolId: Math.floor(perpInfos[j].id / 100000),
288
- limitOrderBookAddr: perpInfos[j].limitOrderBookAddr,
289
- initialMarginRate: (0, d8XMath_1.ABDK29ToFloat)(perpInfos[j].fInitialMarginRate),
290
- maintenanceMarginRate: (0, d8XMath_1.ABDK29ToFloat)(perpInfos[j].fMaintenanceMarginRate),
291
- collateralCurrencyType: perpInfos[j].collCurrencyType,
292
- S2Symbol: sym2,
293
- S3Symbol: sym3,
294
- lotSizeBC: (0, d8XMath_1.ABK64x64ToFloat)(perpInfos[j].fLotSizeBC),
295
- referralRebate: (0, d8XMath_1.ABK64x64ToFloat)(perpInfos[j].fReferralRebateCC),
296
- priceIds: perpInfos[j].priceIds,
297
- };
298
- infoArr.push(info);
299
- }
300
- }
301
- return infoArr;
302
- }
336
+ PerpetualDataHandler.getPerpetualStaticInfo = function (_proxyContract, nestedPerpetualIDs, symbolList, overrides) {
337
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
338
+ var chunkSize, ids, infoArr, k, perpInfos, j, base, quote, base3, quote3, sym2, sym3, info;
339
+ return tslib_1.__generator(this, function (_a) {
340
+ switch (_a.label) {
341
+ case 0:
342
+ chunkSize = 10;
343
+ ids = PerpetualDataHandler.nestedIDsToChunks(chunkSize, nestedPerpetualIDs);
344
+ infoArr = new Array();
345
+ k = 0;
346
+ _a.label = 1;
347
+ case 1:
348
+ if (!(k < ids.length)) return [3 /*break*/, 4];
349
+ return [4 /*yield*/, _proxyContract.getPerpetualStaticInfo(ids[k], overrides || {})];
350
+ case 2:
351
+ perpInfos = _a.sent();
352
+ for (j = 0; j < perpInfos.length; j++) {
353
+ base = (0, utils_1.contractSymbolToSymbol)(perpInfos[j].S2BaseCCY, symbolList);
354
+ quote = (0, utils_1.contractSymbolToSymbol)(perpInfos[j].S2QuoteCCY, symbolList);
355
+ base3 = (0, utils_1.contractSymbolToSymbol)(perpInfos[j].S3BaseCCY, symbolList);
356
+ quote3 = (0, utils_1.contractSymbolToSymbol)(perpInfos[j].S3QuoteCCY, symbolList);
357
+ sym2 = base + "-" + quote;
358
+ sym3 = base3 == "" ? "" : base3 + "-" + quote3;
359
+ info = {
360
+ id: perpInfos[j].id,
361
+ poolId: Math.floor(perpInfos[j].id / 100000),
362
+ limitOrderBookAddr: perpInfos[j].limitOrderBookAddr,
363
+ initialMarginRate: (0, d8XMath_1.ABDK29ToFloat)(perpInfos[j].fInitialMarginRate),
364
+ maintenanceMarginRate: (0, d8XMath_1.ABDK29ToFloat)(perpInfos[j].fMaintenanceMarginRate),
365
+ collateralCurrencyType: perpInfos[j].collCurrencyType,
366
+ S2Symbol: sym2,
367
+ S3Symbol: sym3,
368
+ lotSizeBC: (0, d8XMath_1.ABK64x64ToFloat)(perpInfos[j].fLotSizeBC),
369
+ referralRebate: (0, d8XMath_1.ABK64x64ToFloat)(perpInfos[j].fReferralRebateCC),
370
+ priceIds: perpInfos[j].priceIds,
371
+ };
372
+ infoArr.push(info);
373
+ }
374
+ _a.label = 3;
375
+ case 3:
376
+ k++;
377
+ return [3 /*break*/, 1];
378
+ case 4: return [2 /*return*/, infoArr];
379
+ }
380
+ });
381
+ });
382
+ };
303
383
  /**
304
384
  * Breaks up an array of nested arrays into chunks of a specified size.
305
385
  * @param {number} chunkSize The size of each chunk.
306
386
  * @param {number[][]} nestedIDs The array of nested arrays to chunk.
307
387
  * @returns {number[][]} An array of subarrays, each containing `chunkSize` or fewer elements from `nestedIDs`.
308
388
  */
309
- static nestedIDsToChunks(chunkSize, nestedIDs) {
310
- const chunkIDs = [];
311
- let currentChunk = [];
312
- for (let k = 0; k < nestedIDs.length; k++) {
313
- const currentPoolIds = nestedIDs[k];
314
- for (let j = 0; j < currentPoolIds.length; j++) {
389
+ PerpetualDataHandler.nestedIDsToChunks = function (chunkSize, nestedIDs) {
390
+ var chunkIDs = [];
391
+ var currentChunk = [];
392
+ for (var k = 0; k < nestedIDs.length; k++) {
393
+ var currentPoolIds = nestedIDs[k];
394
+ for (var j = 0; j < currentPoolIds.length; j++) {
315
395
  currentChunk.push(currentPoolIds[j]);
316
396
  if (currentChunk.length === chunkSize) {
317
397
  chunkIDs.push(currentChunk);
@@ -323,48 +403,61 @@ class PerpetualDataHandler {
323
403
  chunkIDs.push(currentChunk);
324
404
  }
325
405
  return chunkIDs;
326
- }
327
- static async getPoolStaticInfo(_proxyContract, overrides) {
328
- let idxFrom = 1;
329
- const len = 10;
330
- let lenReceived = 10;
331
- let nestedPerpetualIDs = [];
332
- let poolShareTokenAddr = [];
333
- let poolMarginTokenAddr = [];
334
- let oracleFactory = "";
335
- while (lenReceived == len) {
336
- let res = await _proxyContract.getPoolStaticInfo(idxFrom, idxFrom + len - 1, overrides || {});
337
- lenReceived = res.length;
338
- nestedPerpetualIDs = nestedPerpetualIDs.concat(res[0]);
339
- poolShareTokenAddr = res[1];
340
- poolMarginTokenAddr = res[2];
341
- oracleFactory = res[3];
342
- idxFrom = idxFrom + len;
343
- }
344
- return {
345
- nestedPerpetualIDs: nestedPerpetualIDs,
346
- poolShareTokenAddr: poolShareTokenAddr,
347
- poolMarginTokenAddr: poolMarginTokenAddr,
348
- oracleFactory: oracleFactory,
349
- };
350
- }
351
- static buildMarginAccountFromState(symbol, traderState, symbolToPerpStaticInfo, _pxS2S3) {
352
- const idx_cash = 3;
353
- const idx_notional = 4;
354
- const idx_locked_in = 5;
355
- const idx_mark_price = 8;
356
- const idx_lvg = 7;
357
- const idx_s3 = 9;
358
- let isEmpty = traderState[idx_notional].eq(0);
359
- let cash = (0, d8XMath_1.ABK64x64ToFloat)(traderState[idx_cash]);
360
- let S2Liq = 0, S3Liq = 0, tau = Infinity, pnl = 0, unpaidFundingCC = 0, fLockedIn = bignumber_1.BigNumber.from(0), side = nodeSDKTypes_1.CLOSED_SIDE, entryPrice = 0;
406
+ };
407
+ PerpetualDataHandler.getPoolStaticInfo = function (_proxyContract, overrides) {
408
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
409
+ var idxFrom, len, lenReceived, nestedPerpetualIDs, poolShareTokenAddr, poolMarginTokenAddr, oracleFactory, res;
410
+ return tslib_1.__generator(this, function (_a) {
411
+ switch (_a.label) {
412
+ case 0:
413
+ idxFrom = 1;
414
+ len = 10;
415
+ lenReceived = 10;
416
+ nestedPerpetualIDs = [];
417
+ poolShareTokenAddr = [];
418
+ poolMarginTokenAddr = [];
419
+ oracleFactory = "";
420
+ _a.label = 1;
421
+ case 1:
422
+ if (!(lenReceived == len)) return [3 /*break*/, 3];
423
+ return [4 /*yield*/, _proxyContract.getPoolStaticInfo(idxFrom, idxFrom + len - 1, overrides || {})];
424
+ case 2:
425
+ res = _a.sent();
426
+ lenReceived = res.length;
427
+ nestedPerpetualIDs = nestedPerpetualIDs.concat(res[0]);
428
+ poolShareTokenAddr = res[1];
429
+ poolMarginTokenAddr = res[2];
430
+ oracleFactory = res[3];
431
+ idxFrom = idxFrom + len;
432
+ return [3 /*break*/, 1];
433
+ case 3: return [2 /*return*/, {
434
+ nestedPerpetualIDs: nestedPerpetualIDs,
435
+ poolShareTokenAddr: poolShareTokenAddr,
436
+ poolMarginTokenAddr: poolMarginTokenAddr,
437
+ oracleFactory: oracleFactory,
438
+ }];
439
+ }
440
+ });
441
+ });
442
+ };
443
+ PerpetualDataHandler.buildMarginAccountFromState = function (symbol, traderState, symbolToPerpStaticInfo, _pxS2S3) {
444
+ var _a;
445
+ var idx_cash = 3;
446
+ var idx_notional = 4;
447
+ var idx_locked_in = 5;
448
+ var idx_mark_price = 8;
449
+ var idx_lvg = 7;
450
+ var idx_s3 = 9;
451
+ var isEmpty = traderState[idx_notional].eq(0);
452
+ var cash = (0, d8XMath_1.ABK64x64ToFloat)(traderState[idx_cash]);
453
+ var S2Liq = 0, S3Liq = 0, tau = Infinity, pnl = 0, unpaidFundingCC = 0, fLockedIn = bignumber_1.BigNumber.from(0), side = nodeSDKTypes_1.CLOSED_SIDE, entryPrice = 0;
361
454
  if (!isEmpty) {
362
- [S2Liq, S3Liq, tau, pnl, unpaidFundingCC] = PerpetualDataHandler._calculateLiquidationPrice(symbol, traderState, _pxS2S3[0], symbolToPerpStaticInfo);
455
+ _a = tslib_1.__read(PerpetualDataHandler._calculateLiquidationPrice(symbol, traderState, _pxS2S3[0], symbolToPerpStaticInfo), 5), S2Liq = _a[0], S3Liq = _a[1], tau = _a[2], pnl = _a[3], unpaidFundingCC = _a[4];
363
456
  fLockedIn = traderState[idx_locked_in];
364
457
  side = traderState[idx_locked_in].gt(0) ? nodeSDKTypes_1.BUY_SIDE : nodeSDKTypes_1.SELL_SIDE;
365
458
  entryPrice = (0, d8XMath_1.ABK64x64ToFloat)((0, d8XMath_1.div64x64)(fLockedIn, traderState[idx_notional]));
366
459
  }
367
- let mgn = {
460
+ var mgn = {
368
461
  symbol: symbol,
369
462
  positionNotionalBaseCCY: isEmpty ? 0 : (0, d8XMath_1.ABK64x64ToFloat)(traderState[idx_notional].abs()),
370
463
  side: isEmpty ? nodeSDKTypes_1.CLOSED_SIDE : side,
@@ -379,56 +472,96 @@ class PerpetualDataHandler {
379
472
  collToQuoteConversion: (0, d8XMath_1.ABK64x64ToFloat)(traderState[idx_s3]),
380
473
  };
381
474
  return mgn;
382
- }
383
- static async getMarginAccount(traderAddr, symbol, symbolToPerpStaticInfo, _proxyContract, _pxS2S3, overrides) {
384
- let perpId = Number(symbol);
385
- if (isNaN(perpId)) {
386
- perpId = PerpetualDataHandler.symbolToPerpetualId(symbol, symbolToPerpStaticInfo);
387
- }
388
- let traderState = await _proxyContract.getTraderState(perpId, traderAddr, _pxS2S3.map((x) => (0, d8XMath_1.floatToABK64x64)(x)), overrides || {});
389
- return PerpetualDataHandler.buildMarginAccountFromState(symbol, traderState, symbolToPerpStaticInfo, _pxS2S3);
390
- }
391
- static async _queryPerpetualPrice(symbol, tradeAmount, symbolToPerpStaticInfo, _proxyContract, indexPrices, overrides) {
392
- let perpId = PerpetualDataHandler.symbolToPerpetualId(symbol, symbolToPerpStaticInfo);
393
- let fIndexPrices = indexPrices.map((x) => (0, d8XMath_1.floatToABK64x64)(x == undefined || Number.isNaN(x) ? 0 : x));
394
- let fPrice = await _proxyContract.queryPerpetualPrice(perpId, (0, d8XMath_1.floatToABK64x64)(tradeAmount), fIndexPrices, overrides || {});
395
- return (0, d8XMath_1.ABK64x64ToFloat)(fPrice);
396
- }
397
- static async _queryPerpetualMarkPrice(symbol, symbolToPerpStaticInfo, _proxyContract, indexPrices, overrides) {
398
- let perpId = PerpetualDataHandler.symbolToPerpetualId(symbol, symbolToPerpStaticInfo);
399
- let [S2, S3] = indexPrices.map((x) => (0, d8XMath_1.floatToABK64x64)(x == undefined || Number.isNaN(x) ? 0 : x));
400
- let ammState = await _proxyContract.getAMMState(perpId, [S2, S3], overrides || {});
401
- // ammState[6] == S2 == indexPrices[0] up to rounding errors (indexPrices is most accurate)
402
- return indexPrices[0] * (1 + (0, d8XMath_1.ABK64x64ToFloat)(ammState[8]));
403
- }
404
- static async _queryPerpetualState(symbol, symbolToPerpStaticInfo, _proxyContract, indexPrices, overrides) {
405
- let perpId = PerpetualDataHandler.symbolToPerpetualId(symbol, symbolToPerpStaticInfo);
406
- let staticInfo = symbolToPerpStaticInfo.get(symbol);
407
- let ccy = symbol.split("-");
408
- let [S2, S3] = [indexPrices[0], indexPrices[1]];
409
- if (staticInfo.collateralCurrencyType == nodeSDKTypes_1.CollaterlCCY.BASE) {
410
- S3 = S2;
411
- }
412
- else if (staticInfo.collateralCurrencyType == nodeSDKTypes_1.CollaterlCCY.QUOTE) {
413
- S3 = 1;
414
- }
415
- let ammState = await _proxyContract.getAMMState(perpId, [S2, S3].map(d8XMath_1.floatToABK64x64), overrides || {});
416
- let markPrice = S2 * (1 + (0, d8XMath_1.ABK64x64ToFloat)(ammState[8]));
417
- let state = {
418
- id: perpId,
419
- state: nodeSDKTypes_1.PERP_STATE_STR[ammState[13].toNumber()],
420
- baseCurrency: ccy[0],
421
- quoteCurrency: ccy[1],
422
- indexPrice: S2,
423
- collToQuoteIndexPrice: S3,
424
- markPrice: markPrice,
425
- midPrice: (0, d8XMath_1.ABK64x64ToFloat)(ammState[10]),
426
- currentFundingRateBps: (0, d8XMath_1.ABK64x64ToFloat)(ammState[14]) * 1e4,
427
- openInterestBC: (0, d8XMath_1.ABK64x64ToFloat)(ammState[11]),
428
- isMarketClosed: indexPrices[2] || indexPrices[3],
429
- };
430
- return state;
431
- }
475
+ };
476
+ PerpetualDataHandler.getMarginAccount = function (traderAddr, symbol, symbolToPerpStaticInfo, _proxyContract, _pxS2S3, overrides) {
477
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
478
+ var perpId, traderState;
479
+ return tslib_1.__generator(this, function (_a) {
480
+ switch (_a.label) {
481
+ case 0:
482
+ perpId = Number(symbol);
483
+ if (isNaN(perpId)) {
484
+ perpId = PerpetualDataHandler.symbolToPerpetualId(symbol, symbolToPerpStaticInfo);
485
+ }
486
+ return [4 /*yield*/, _proxyContract.getTraderState(perpId, traderAddr, _pxS2S3.map(function (x) { return (0, d8XMath_1.floatToABK64x64)(x); }), overrides || {})];
487
+ case 1:
488
+ traderState = _a.sent();
489
+ return [2 /*return*/, PerpetualDataHandler.buildMarginAccountFromState(symbol, traderState, symbolToPerpStaticInfo, _pxS2S3)];
490
+ }
491
+ });
492
+ });
493
+ };
494
+ PerpetualDataHandler._queryPerpetualPrice = function (symbol, tradeAmount, symbolToPerpStaticInfo, _proxyContract, indexPrices, overrides) {
495
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
496
+ var perpId, fIndexPrices, fPrice;
497
+ return tslib_1.__generator(this, function (_a) {
498
+ switch (_a.label) {
499
+ case 0:
500
+ perpId = PerpetualDataHandler.symbolToPerpetualId(symbol, symbolToPerpStaticInfo);
501
+ fIndexPrices = indexPrices.map(function (x) { return (0, d8XMath_1.floatToABK64x64)(x == undefined || Number.isNaN(x) ? 0 : x); });
502
+ return [4 /*yield*/, _proxyContract.queryPerpetualPrice(perpId, (0, d8XMath_1.floatToABK64x64)(tradeAmount), fIndexPrices, overrides || {})];
503
+ case 1:
504
+ fPrice = _a.sent();
505
+ return [2 /*return*/, (0, d8XMath_1.ABK64x64ToFloat)(fPrice)];
506
+ }
507
+ });
508
+ });
509
+ };
510
+ PerpetualDataHandler._queryPerpetualMarkPrice = function (symbol, symbolToPerpStaticInfo, _proxyContract, indexPrices, overrides) {
511
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
512
+ var perpId, _a, S2, S3, ammState;
513
+ return tslib_1.__generator(this, function (_b) {
514
+ switch (_b.label) {
515
+ case 0:
516
+ perpId = PerpetualDataHandler.symbolToPerpetualId(symbol, symbolToPerpStaticInfo);
517
+ _a = tslib_1.__read(indexPrices.map(function (x) { return (0, d8XMath_1.floatToABK64x64)(x == undefined || Number.isNaN(x) ? 0 : x); }), 2), S2 = _a[0], S3 = _a[1];
518
+ return [4 /*yield*/, _proxyContract.getAMMState(perpId, [S2, S3], overrides || {})];
519
+ case 1:
520
+ ammState = _b.sent();
521
+ // ammState[6] == S2 == indexPrices[0] up to rounding errors (indexPrices is most accurate)
522
+ return [2 /*return*/, indexPrices[0] * (1 + (0, d8XMath_1.ABK64x64ToFloat)(ammState[8]))];
523
+ }
524
+ });
525
+ });
526
+ };
527
+ PerpetualDataHandler._queryPerpetualState = function (symbol, symbolToPerpStaticInfo, _proxyContract, indexPrices, overrides) {
528
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
529
+ var perpId, staticInfo, ccy, _a, S2, S3, ammState, markPrice, state;
530
+ return tslib_1.__generator(this, function (_b) {
531
+ switch (_b.label) {
532
+ case 0:
533
+ perpId = PerpetualDataHandler.symbolToPerpetualId(symbol, symbolToPerpStaticInfo);
534
+ staticInfo = symbolToPerpStaticInfo.get(symbol);
535
+ ccy = symbol.split("-");
536
+ _a = tslib_1.__read([indexPrices[0], indexPrices[1]], 2), S2 = _a[0], S3 = _a[1];
537
+ if (staticInfo.collateralCurrencyType == nodeSDKTypes_1.CollaterlCCY.BASE) {
538
+ S3 = S2;
539
+ }
540
+ else if (staticInfo.collateralCurrencyType == nodeSDKTypes_1.CollaterlCCY.QUOTE) {
541
+ S3 = 1;
542
+ }
543
+ return [4 /*yield*/, _proxyContract.getAMMState(perpId, [S2, S3].map(d8XMath_1.floatToABK64x64), overrides || {})];
544
+ case 1:
545
+ ammState = _b.sent();
546
+ markPrice = S2 * (1 + (0, d8XMath_1.ABK64x64ToFloat)(ammState[8]));
547
+ state = {
548
+ id: perpId,
549
+ state: nodeSDKTypes_1.PERP_STATE_STR[ammState[13].toNumber()],
550
+ baseCurrency: ccy[0],
551
+ quoteCurrency: ccy[1],
552
+ indexPrice: S2,
553
+ collToQuoteIndexPrice: S3,
554
+ markPrice: markPrice,
555
+ midPrice: (0, d8XMath_1.ABK64x64ToFloat)(ammState[10]),
556
+ currentFundingRateBps: (0, d8XMath_1.ABK64x64ToFloat)(ammState[14]) * 1e4,
557
+ openInterestBC: (0, d8XMath_1.ABK64x64ToFloat)(ammState[11]),
558
+ isMarketClosed: indexPrices[2] || indexPrices[3],
559
+ };
560
+ return [2 /*return*/, state];
561
+ }
562
+ });
563
+ });
564
+ };
432
565
  /**
433
566
  * Liquidation price
434
567
  * @param symbol symbol of the form BTC-USD-MATIC
@@ -437,34 +570,34 @@ class PerpetualDataHandler {
437
570
  * @param symbolToPerpStaticInfo mapping symbol->PerpStaticInfo
438
571
  * @returns liquidation mark-price, corresponding collateral/quote conversion
439
572
  */
440
- static _calculateLiquidationPrice(symbol, traderState, S2, symbolToPerpStaticInfo) {
441
- const idx_availableCashCC = 2;
442
- const idx_cash = 3;
443
- const idx_notional = 4;
444
- const idx_locked_in = 5;
445
- const idx_mark_price = 8;
446
- const idx_s3 = 9;
573
+ PerpetualDataHandler._calculateLiquidationPrice = function (symbol, traderState, S2, symbolToPerpStaticInfo) {
574
+ var idx_availableCashCC = 2;
575
+ var idx_cash = 3;
576
+ var idx_notional = 4;
577
+ var idx_locked_in = 5;
578
+ var idx_mark_price = 8;
579
+ var idx_s3 = 9;
447
580
  // const idx_s2 = 10;
448
- let S2Liq;
449
- let S3Liq = (0, d8XMath_1.ABK64x64ToFloat)(traderState[idx_s3]);
450
- let perpInfo = symbolToPerpStaticInfo.get(symbol);
581
+ var S2Liq;
582
+ var S3Liq = (0, d8XMath_1.ABK64x64ToFloat)(traderState[idx_s3]);
583
+ var perpInfo = symbolToPerpStaticInfo.get(symbol);
451
584
  if (perpInfo == undefined) {
452
- throw new Error(`no info for perpetual ${symbol}`);
453
- }
454
- let tau = perpInfo.maintenanceMarginRate;
455
- let lockedInValueQC = (0, d8XMath_1.ABK64x64ToFloat)(traderState[idx_locked_in]);
456
- let position = (0, d8XMath_1.ABK64x64ToFloat)(traderState[idx_notional]);
457
- let cashCC = (0, d8XMath_1.ABK64x64ToFloat)(traderState[idx_availableCashCC]);
458
- let Sm = (0, d8XMath_1.ABK64x64ToFloat)(traderState[idx_mark_price]);
459
- let unpaidFundingCC = (0, d8XMath_1.ABK64x64ToFloat)(traderState[idx_availableCashCC].sub(traderState[idx_cash]));
460
- let unpaidFunding = unpaidFundingCC;
585
+ throw new Error("no info for perpetual ".concat(symbol));
586
+ }
587
+ var tau = perpInfo.maintenanceMarginRate;
588
+ var lockedInValueQC = (0, d8XMath_1.ABK64x64ToFloat)(traderState[idx_locked_in]);
589
+ var position = (0, d8XMath_1.ABK64x64ToFloat)(traderState[idx_notional]);
590
+ var cashCC = (0, d8XMath_1.ABK64x64ToFloat)(traderState[idx_availableCashCC]);
591
+ var Sm = (0, d8XMath_1.ABK64x64ToFloat)(traderState[idx_mark_price]);
592
+ var unpaidFundingCC = (0, d8XMath_1.ABK64x64ToFloat)(traderState[idx_availableCashCC].sub(traderState[idx_cash]));
593
+ var unpaidFunding = unpaidFundingCC;
461
594
  if (perpInfo.collateralCurrencyType == nodeSDKTypes_1.CollaterlCCY.BASE) {
462
595
  S2Liq = (0, d8XMath_1.calculateLiquidationPriceCollateralBase)(lockedInValueQC, position, cashCC, tau);
463
596
  S3Liq = S2Liq;
464
597
  unpaidFunding = unpaidFunding / S2;
465
598
  }
466
599
  else if (perpInfo.collateralCurrencyType == nodeSDKTypes_1.CollaterlCCY.QUANTO) {
467
- let S3 = S3Liq;
600
+ var S3 = S3Liq;
468
601
  S3Liq = S3;
469
602
  S2Liq = (0, d8XMath_1.calculateLiquidationPriceCollateralQuanto)(lockedInValueQC, position, cashCC, tau, S3, Sm);
470
603
  unpaidFunding = unpaidFunding / S3;
@@ -476,9 +609,9 @@ class PerpetualDataHandler {
476
609
  S2Liq = S2Liq < 0 ? 0 : S2Liq;
477
610
  S3Liq = S3Liq && S3Liq < 0 ? 0 : S3Liq;
478
611
  // account cash + pnl = avail cash + pos Sm - L = margin balance
479
- let pnl = position * Sm - lockedInValueQC + unpaidFunding;
612
+ var pnl = position * Sm - lockedInValueQC + unpaidFunding;
480
613
  return [S2Liq, S3Liq, tau, pnl, unpaidFundingCC];
481
- }
614
+ };
482
615
  /**
483
616
  * Finds the perpetual id for a symbol of the form
484
617
  * <base>-<quote>-<collateral>. The function first converts the
@@ -488,45 +621,57 @@ class PerpetualDataHandler {
488
621
  * including id mapping
489
622
  * @returns perpetual id or it fails
490
623
  */
491
- static symbolToPerpetualId(symbol, symbolToPerpStaticInfo) {
492
- let id = symbolToPerpStaticInfo.get(symbol)?.id;
624
+ PerpetualDataHandler.symbolToPerpetualId = function (symbol, symbolToPerpStaticInfo) {
625
+ var _a;
626
+ var id = (_a = symbolToPerpStaticInfo.get(symbol)) === null || _a === void 0 ? void 0 : _a.id;
493
627
  if (id == undefined) {
494
- throw Error(`No perpetual found for symbol ${symbol}`);
628
+ throw Error("No perpetual found for symbol ".concat(symbol));
495
629
  }
496
630
  return id;
497
- }
498
- static symbolToBytes4Symbol(symbol) {
631
+ };
632
+ PerpetualDataHandler.symbolToBytes4Symbol = function (symbol) {
499
633
  //split by dashes BTC-USD-MATIC
500
- let symbols = symbol.split("-");
634
+ var symbols = symbol.split("-");
501
635
  if (symbols.length != 3) {
502
- throw Error(`Symbol ${symbol} not valid. Expecting CCY-CCY-CCY format`);
636
+ throw Error("Symbol ".concat(symbol, " not valid. Expecting CCY-CCY-CCY format"));
503
637
  }
504
638
  //transform into bytes4 currencies (without the space): "BTC", "USD", "MATC"
505
- symbols = symbols.map((x) => {
506
- let v = (0, utils_1.to4Chars)(x);
639
+ symbols = symbols.map(function (x) {
640
+ var v = (0, utils_1.to4Chars)(x);
507
641
  v = v.replace(/\0/g, "");
508
642
  return v;
509
643
  });
510
644
  // concatenate and find perpetual Id in map
511
645
  return symbols[0] + "-" + symbols[1] + "-" + symbols[2];
512
- }
513
- static _getByValue(map, searchValue, valueField) {
514
- for (let [key, value] of map.entries()) {
515
- if (value[valueField] === searchValue) {
516
- return key;
646
+ };
647
+ PerpetualDataHandler._getByValue = function (map, searchValue, valueField) {
648
+ var e_2, _a;
649
+ try {
650
+ for (var _b = tslib_1.__values(map.entries()), _c = _b.next(); !_c.done; _c = _b.next()) {
651
+ var _d = tslib_1.__read(_c.value, 2), key = _d[0], value = _d[1];
652
+ if (value[valueField] === searchValue) {
653
+ return key;
654
+ }
517
655
  }
518
656
  }
657
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
658
+ finally {
659
+ try {
660
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
661
+ }
662
+ finally { if (e_2) throw e_2.error; }
663
+ }
519
664
  return undefined;
520
- }
521
- static fromSmartContractOrder(order, symbolToPerpInfoMap) {
665
+ };
666
+ PerpetualDataHandler.fromSmartContractOrder = function (order, symbolToPerpInfoMap) {
522
667
  // find symbol of perpetual id
523
- let symbol = PerpetualDataHandler._getByValue(symbolToPerpInfoMap, order.iPerpetualId, "id");
668
+ var symbol = PerpetualDataHandler._getByValue(symbolToPerpInfoMap, order.iPerpetualId, "id");
524
669
  if (symbol == undefined) {
525
- throw Error(`Perpetual id ${order.iPerpetualId} not found. Check with marketData.exchangeInfo().`);
670
+ throw Error("Perpetual id ".concat(order.iPerpetualId, " not found. Check with marketData.exchangeInfo()."));
526
671
  }
527
- let side = order.fAmount > bignumber_1.BigNumber.from(0) ? nodeSDKTypes_1.BUY_SIDE : nodeSDKTypes_1.SELL_SIDE;
528
- let limitPrice, stopPrice;
529
- let fLimitPrice = bignumber_1.BigNumber.from(order.fLimitPrice);
672
+ var side = order.fAmount > bignumber_1.BigNumber.from(0) ? nodeSDKTypes_1.BUY_SIDE : nodeSDKTypes_1.SELL_SIDE;
673
+ var limitPrice, stopPrice;
674
+ var fLimitPrice = bignumber_1.BigNumber.from(order.fLimitPrice);
530
675
  if (fLimitPrice.eq(0)) {
531
676
  limitPrice = side == nodeSDKTypes_1.BUY_SIDE ? undefined : 0;
532
677
  }
@@ -536,14 +681,14 @@ class PerpetualDataHandler {
536
681
  else {
537
682
  limitPrice = (0, d8XMath_1.ABK64x64ToFloat)(fLimitPrice);
538
683
  }
539
- let fStopPrice = bignumber_1.BigNumber.from(order.fTriggerPrice);
684
+ var fStopPrice = bignumber_1.BigNumber.from(order.fTriggerPrice);
540
685
  if (fStopPrice.eq(0) || fStopPrice.eq(nodeSDKTypes_1.MAX_64x64)) {
541
686
  stopPrice = undefined;
542
687
  }
543
688
  else {
544
689
  stopPrice = (0, d8XMath_1.ABK64x64ToFloat)(fStopPrice);
545
690
  }
546
- let userOrder = {
691
+ var userOrder = {
547
692
  symbol: symbol,
548
693
  side: side,
549
694
  type: PerpetualDataHandler._flagToOrderType(bignumber_1.BigNumber.from(order.flags), bignumber_1.BigNumber.from(order.fLimitPrice)),
@@ -561,7 +706,7 @@ class PerpetualDataHandler {
561
706
  submittedTimestamp: Number(order.submittedTimestamp),
562
707
  };
563
708
  return userOrder;
564
- }
709
+ };
565
710
  /**
566
711
  * Transform the convenient form of the order into a smart-contract accepted type of order
567
712
  * @param order order type
@@ -569,14 +714,14 @@ class PerpetualDataHandler {
569
714
  * @param symbolToPerpetualMap mapping of symbol to perpetual Id
570
715
  * @returns SmartContractOrder
571
716
  */
572
- static toSmartContractOrder(order, traderAddr, perpStaticInfo) {
717
+ PerpetualDataHandler.toSmartContractOrder = function (order, traderAddr, perpStaticInfo) {
573
718
  // this revers if order is invalid
574
719
  PerpetualDataHandler.checkOrder(order, perpStaticInfo);
575
720
  // translate order
576
- let flags = PerpetualDataHandler._orderTypeToFlag(order);
577
- let brokerSig = order.brokerSignature == undefined ? [] : order.brokerSignature;
578
- let perpetualId = PerpetualDataHandler.symbolToPerpetualId(order.symbol, perpStaticInfo);
579
- let fAmount;
721
+ var flags = PerpetualDataHandler._orderTypeToFlag(order);
722
+ var brokerSig = order.brokerSignature == undefined ? [] : order.brokerSignature;
723
+ var perpetualId = PerpetualDataHandler.symbolToPerpetualId(order.symbol, perpStaticInfo);
724
+ var fAmount;
580
725
  if (order.side == nodeSDKTypes_1.BUY_SIDE) {
581
726
  fAmount = (0, d8XMath_1.floatToABK64x64)(Math.abs(order.quantity));
582
727
  }
@@ -584,9 +729,9 @@ class PerpetualDataHandler {
584
729
  fAmount = (0, d8XMath_1.floatToABK64x64)(-Math.abs(order.quantity));
585
730
  }
586
731
  else {
587
- throw Error(`invalid side in order spec, use ${nodeSDKTypes_1.BUY_SIDE} or ${nodeSDKTypes_1.SELL_SIDE}`);
732
+ throw Error("invalid side in order spec, use ".concat(nodeSDKTypes_1.BUY_SIDE, " or ").concat(nodeSDKTypes_1.SELL_SIDE));
588
733
  }
589
- let fLimitPrice;
734
+ var fLimitPrice;
590
735
  if (order.limitPrice == undefined) {
591
736
  // we need to set the limit price to infinity or zero for
592
737
  // the trade to go through
@@ -597,9 +742,9 @@ class PerpetualDataHandler {
597
742
  else {
598
743
  fLimitPrice = (0, d8XMath_1.floatToABK64x64)(order.limitPrice);
599
744
  }
600
- let iDeadline = order.deadline == undefined ? Date.now() / 1000 + nodeSDKTypes_1.ORDER_MAX_DURATION_SEC : order.deadline;
601
- let fTriggerPrice = order.stopPrice == undefined ? bignumber_1.BigNumber.from(0) : (0, d8XMath_1.floatToABK64x64)(order.stopPrice);
602
- let smOrder = {
745
+ var iDeadline = order.deadline == undefined ? Date.now() / 1000 + nodeSDKTypes_1.ORDER_MAX_DURATION_SEC : order.deadline;
746
+ var fTriggerPrice = order.stopPrice == undefined ? bignumber_1.BigNumber.from(0) : (0, d8XMath_1.floatToABK64x64)(order.stopPrice);
747
+ var smOrder = {
603
748
  flags: flags,
604
749
  iPerpetualId: perpetualId,
605
750
  brokerFeeTbps: order.brokerFeeTbps == undefined ? 0 : order.brokerFeeTbps,
@@ -616,14 +761,14 @@ class PerpetualDataHandler {
616
761
  submittedTimestamp: 0,
617
762
  };
618
763
  return smOrder;
619
- }
764
+ };
620
765
  /**
621
766
  * Converts a smart contract order to a client order
622
767
  * @param scOrder Smart contract order
623
768
  * @param parentChildIds Optional parent-child dependency
624
769
  * @returns Client order that can be submitted to the corresponding LOB
625
770
  */
626
- static fromSmartContratOrderToClientOrder(scOrder, parentChildIds) {
771
+ PerpetualDataHandler.fromSmartContratOrderToClientOrder = function (scOrder, parentChildIds) {
627
772
  return {
628
773
  flags: scOrder.flags,
629
774
  iPerpetualId: scOrder.iPerpetualId,
@@ -641,24 +786,24 @@ class PerpetualDataHandler {
641
786
  parentChildDigest1: parentChildIds ? parentChildIds[0] : nodeSDKTypes_1.ZERO_ORDER_ID,
642
787
  parentChildDigest2: parentChildIds ? parentChildIds[1] : nodeSDKTypes_1.ZERO_ORDER_ID,
643
788
  };
644
- }
789
+ };
645
790
  /**
646
791
  * Converts a user-friendly order to a client order
647
792
  * @param order Order
648
793
  * @param parentChildIds Optional parent-child dependency
649
794
  * @returns Client order that can be submitted to the corresponding LOB
650
795
  */
651
- static toClientOrder(order, traderAddr, perpStaticInfo, parentChildIds) {
652
- const scOrder = PerpetualDataHandler.toSmartContractOrder(order, traderAddr, perpStaticInfo);
796
+ PerpetualDataHandler.toClientOrder = function (order, traderAddr, perpStaticInfo, parentChildIds) {
797
+ var scOrder = PerpetualDataHandler.toSmartContractOrder(order, traderAddr, perpStaticInfo);
653
798
  return PerpetualDataHandler.fromSmartContratOrderToClientOrder(scOrder, parentChildIds);
654
- }
799
+ };
655
800
  /**
656
801
  * Converts an order as stored in the LOB smart contract into a user-friendly order type
657
802
  * @param obOrder Order-book contract order type
658
803
  * @returns User friendly order struct
659
804
  */
660
- static fromClientOrder(obOrder, perpStaticInfo) {
661
- const scOrder = {
805
+ PerpetualDataHandler.fromClientOrder = function (obOrder, perpStaticInfo) {
806
+ var scOrder = {
662
807
  flags: obOrder.flags,
663
808
  iPerpetualId: obOrder.iPerpetualId,
664
809
  brokerFeeTbps: obOrder.brokerFeeTbps,
@@ -672,18 +817,18 @@ class PerpetualDataHandler {
672
817
  iDeadline: obOrder.iDeadline,
673
818
  executionTimestamp: obOrder.executionTimestamp,
674
819
  };
675
- const order = PerpetualDataHandler.fromSmartContractOrder(scOrder, perpStaticInfo);
820
+ var order = PerpetualDataHandler.fromSmartContractOrder(scOrder, perpStaticInfo);
676
821
  if (obOrder.parentChildDigest1.toString() != nodeSDKTypes_1.ZERO_ORDER_ID ||
677
822
  obOrder.parentChildDigest2.toString() != nodeSDKTypes_1.ZERO_ORDER_ID) {
678
823
  order.parentChildOrderIds = [obOrder.parentChildDigest1.toString(), obOrder.parentChildDigest2.toString()];
679
824
  }
680
825
  return order;
681
- }
682
- static _flagToOrderType(orderFlags, orderLimitPrice) {
683
- let flag = bignumber_1.BigNumber.from(orderFlags);
684
- let isLimit = (0, utils_1.containsFlag)(flag, nodeSDKTypes_1.MASK_LIMIT_ORDER);
685
- let hasLimit = !bignumber_1.BigNumber.from(orderLimitPrice).eq(0) || !bignumber_1.BigNumber.from(orderLimitPrice).eq(nodeSDKTypes_1.MAX_64x64);
686
- let isStop = (0, utils_1.containsFlag)(flag, nodeSDKTypes_1.MASK_STOP_ORDER);
826
+ };
827
+ PerpetualDataHandler._flagToOrderType = function (orderFlags, orderLimitPrice) {
828
+ var flag = bignumber_1.BigNumber.from(orderFlags);
829
+ var isLimit = (0, utils_1.containsFlag)(flag, nodeSDKTypes_1.MASK_LIMIT_ORDER);
830
+ var hasLimit = !bignumber_1.BigNumber.from(orderLimitPrice).eq(0) || !bignumber_1.BigNumber.from(orderLimitPrice).eq(nodeSDKTypes_1.MAX_64x64);
831
+ var isStop = (0, utils_1.containsFlag)(flag, nodeSDKTypes_1.MASK_STOP_ORDER);
687
832
  if (isStop && hasLimit) {
688
833
  return nodeSDKTypes_1.ORDER_TYPE_STOP_LIMIT;
689
834
  }
@@ -696,15 +841,15 @@ class PerpetualDataHandler {
696
841
  else {
697
842
  return nodeSDKTypes_1.ORDER_TYPE_MARKET;
698
843
  }
699
- }
844
+ };
700
845
  /**
701
846
  * Determine the correct order flags based on the order-properties.
702
847
  * Checks for some misspecifications.
703
848
  * @param order order type
704
849
  * @returns BigNumber flags
705
850
  */
706
- static _orderTypeToFlag(order) {
707
- let flag;
851
+ PerpetualDataHandler._orderTypeToFlag = function (order) {
852
+ var flag;
708
853
  order.type = order.type.toUpperCase();
709
854
  switch (order.type) {
710
855
  case nodeSDKTypes_1.ORDER_TYPE_LIMIT:
@@ -720,7 +865,7 @@ class PerpetualDataHandler {
720
865
  flag = nodeSDKTypes_1.MASK_STOP_ORDER;
721
866
  break;
722
867
  default: {
723
- throw Error(`Order type ${order.type} not found.`);
868
+ throw Error("Order type ".concat(order.type, " not found."));
724
869
  }
725
870
  }
726
871
  if (order.keepPositionLvg != undefined && order.keepPositionLvg) {
@@ -730,37 +875,37 @@ class PerpetualDataHandler {
730
875
  flag = (0, utils_1.combineFlags)(flag, nodeSDKTypes_1.MASK_CLOSE_ONLY);
731
876
  }
732
877
  if ((order.type == nodeSDKTypes_1.ORDER_TYPE_LIMIT || order.type == nodeSDKTypes_1.ORDER_TYPE_STOP_LIMIT) && order.limitPrice == undefined) {
733
- throw Error(`Order type ${order.type} requires limit price.`);
878
+ throw Error("Order type ".concat(order.type, " requires limit price."));
734
879
  }
735
880
  if ((order.type == nodeSDKTypes_1.ORDER_TYPE_STOP_MARKET || order.type == nodeSDKTypes_1.ORDER_TYPE_STOP_LIMIT) && order.stopPrice == undefined) {
736
- throw Error(`Order type ${order.type} requires trigger price.`);
881
+ throw Error("Order type ".concat(order.type, " requires trigger price."));
737
882
  }
738
883
  if ((order.type == nodeSDKTypes_1.ORDER_TYPE_MARKET || order.type == nodeSDKTypes_1.ORDER_TYPE_LIMIT) && order.stopPrice != undefined) {
739
- throw Error(`Order type ${order.type} has no trigger price.`);
884
+ throw Error("Order type ".concat(order.type, " has no trigger price."));
740
885
  }
741
886
  if (order.type != nodeSDKTypes_1.ORDER_TYPE_STOP_LIMIT && order.type != nodeSDKTypes_1.ORDER_TYPE_STOP_MARKET && order.stopPrice != undefined) {
742
- throw Error(`Order type ${order.type} has no trigger price.`);
887
+ throw Error("Order type ".concat(order.type, " has no trigger price."));
743
888
  }
744
889
  return flag;
745
- }
746
- static _getLotSize(symbol, symbolToPerpStaticInfo) {
747
- let perpInfo = symbolToPerpStaticInfo.get(symbol);
890
+ };
891
+ PerpetualDataHandler._getLotSize = function (symbol, symbolToPerpStaticInfo) {
892
+ var perpInfo = symbolToPerpStaticInfo.get(symbol);
748
893
  if (perpInfo == undefined) {
749
- throw new Error(`no info for perpetual ${symbol}`);
894
+ throw new Error("no info for perpetual ".concat(symbol));
750
895
  }
751
896
  return perpInfo.lotSizeBC;
752
- }
753
- static _getMinimalPositionSize(symbol, symbolToPerpStaticInfo) {
897
+ };
898
+ PerpetualDataHandler._getMinimalPositionSize = function (symbol, symbolToPerpStaticInfo) {
754
899
  return 10 * PerpetualDataHandler._getLotSize(symbol, symbolToPerpStaticInfo);
755
- }
900
+ };
756
901
  /**
757
902
  * Get NodeSDKConfig from a chain ID, known config name, or custom file location..
758
903
  * @param configNameOrfileLocation Name of a known default config, or chain ID, or json-file with required variables for config
759
904
  * @param version Config version number. Defaults to highest version if name or chain ID are not unique
760
905
  * @returns NodeSDKConfig
761
906
  */
762
- static readSDKConfig(configNameOrChainIdOrFileLocation, version) {
763
- let config;
907
+ PerpetualDataHandler.readSDKConfig = function (configNameOrChainIdOrFileLocation, version) {
908
+ var config;
764
909
  if (typeof configNameOrChainIdOrFileLocation === "number") {
765
910
  // user entered a chain ID
766
911
  config = this.getConfigByChainId(configNameOrChainIdOrFileLocation, version);
@@ -777,92 +922,92 @@ class PerpetualDataHandler {
777
922
  }
778
923
  else {
779
924
  // error
780
- throw Error(`Please specify a chain ID, config name, or custom file location.`);
925
+ throw Error("Please specify a chain ID, config name, or custom file location.");
781
926
  }
782
927
  if (config == undefined) {
783
- throw Error(`Config ${configNameOrChainIdOrFileLocation} not found.`);
928
+ throw Error("Config ".concat(configNameOrChainIdOrFileLocation, " not found."));
784
929
  }
785
930
  return config;
786
- }
931
+ };
787
932
  /**
788
933
  * Get a NodeSDKConfig from its name
789
934
  * @param name Name of the known config
790
935
  * @param version Version of the config. Defaults to highest available.
791
936
  * @returns NodeSDKConfig
792
937
  */
793
- static getConfigByName(name, version) {
794
- let configFile = nodeSDKTypes_1.DEFAULT_CONFIG.filter((c) => c.name == name);
938
+ PerpetualDataHandler.getConfigByName = function (name, version) {
939
+ var configFile = nodeSDKTypes_1.DEFAULT_CONFIG.filter(function (c) { return c.name == name; });
795
940
  if (configFile.length == 0) {
796
- throw Error(`No SDK config found with name ${name}.`);
941
+ throw Error("No SDK config found with name ".concat(name, "."));
797
942
  }
798
943
  if (configFile.length == 1) {
799
944
  return configFile[0];
800
945
  }
801
946
  else {
802
947
  if (version === undefined) {
803
- configFile = configFile.sort((conf) => -conf.version);
948
+ configFile = configFile.sort(function (conf) { return -conf.version; });
804
949
  return configFile[0];
805
950
  }
806
951
  else {
807
- return configFile.find((conf) => conf.version === version);
952
+ return configFile.find(function (conf) { return conf.version === version; });
808
953
  }
809
954
  }
810
- }
955
+ };
811
956
  /**
812
957
  * Get a NodeSDKConfig from a json file.
813
958
  * @param filename Location of the file
814
959
  * @param version Version of the config. Defaults to highest available.
815
960
  * @returns NodeSDKConfig
816
961
  */
817
- static getConfigByLocation(filename) {
962
+ PerpetualDataHandler.getConfigByLocation = function (filename) {
818
963
  // file path: this throws a warning during build - that's ok, it just won't work in react apps
819
964
  // eslint-disable-next-line
820
- let configFile = require(filename);
965
+ var configFile = require(filename);
821
966
  (0, nodeSDKTypes_1.loadABIs)(configFile);
822
967
  return configFile;
823
- }
968
+ };
824
969
  /**
825
970
  * Get a NodeSDKConfig from its chain Id
826
971
  * @param chainId Chain Id
827
972
  * @param version Version of the config. Defaults to highest available.
828
973
  * @returns NodeSDKConfig
829
974
  */
830
- static getConfigByChainId(chainId, version) {
831
- let configFile = nodeSDKTypes_1.DEFAULT_CONFIG.filter((c) => c.chainId == chainId);
975
+ PerpetualDataHandler.getConfigByChainId = function (chainId, version) {
976
+ var configFile = nodeSDKTypes_1.DEFAULT_CONFIG.filter(function (c) { return c.chainId == chainId; });
832
977
  if (configFile.length == 0) {
833
- throw Error(`No SDK config found for chain ID ${chainId}.`);
978
+ throw Error("No SDK config found for chain ID ".concat(chainId, "."));
834
979
  }
835
980
  if (configFile.length == 1) {
836
981
  return configFile[0];
837
982
  }
838
983
  else {
839
984
  if (version === undefined) {
840
- configFile = configFile.sort((conf) => -conf.version);
985
+ configFile = configFile.sort(function (conf) { return -conf.version; });
841
986
  return configFile[0];
842
987
  }
843
988
  else {
844
- return configFile.find((conf) => conf.version === version);
989
+ return configFile.find(function (conf) { return conf.version === version; });
845
990
  }
846
991
  }
847
- }
992
+ };
848
993
  /**
849
994
  * Get the ABI of a function in a given contract
850
995
  * @param contract A contract instance, e.g. this.proxyContract
851
996
  * @param functionName Name of the function whose ABI we want
852
997
  * @returns Function ABI as a single JSON string
853
998
  */
854
- static _getABIFromContract(contract, functionName) {
999
+ PerpetualDataHandler._getABIFromContract = function (contract, functionName) {
855
1000
  return contract.interface.getFunction(functionName).format(abi_1.FormatTypes.full);
856
- }
1001
+ };
857
1002
  /**
858
1003
  * Gets the pool index (starting at 0 in exchangeInfo, not ID!) corresponding to a given symbol.
859
1004
  * @param symbol Symbol of the form ETH-USD-MATIC
860
1005
  * @returns Pool index
861
1006
  */
862
- getPoolStaticInfoIndexFromSymbol(symbol) {
863
- let pools = this.poolStaticInfos;
864
- let poolId = PerpetualDataHandler._getPoolIdFromSymbol(symbol, this.poolStaticInfos);
865
- let k = 0;
1007
+ PerpetualDataHandler.prototype.getPoolStaticInfoIndexFromSymbol = function (symbol) {
1008
+ var pools = this.poolStaticInfos;
1009
+ var poolId = PerpetualDataHandler._getPoolIdFromSymbol(symbol, this.poolStaticInfos);
1010
+ var k = 0;
866
1011
  while (k < pools.length) {
867
1012
  if (pools[k].poolId == poolId) {
868
1013
  // pool found
@@ -871,16 +1016,16 @@ class PerpetualDataHandler {
871
1016
  k++;
872
1017
  }
873
1018
  return -1;
874
- }
1019
+ };
875
1020
  /**
876
1021
  *
877
1022
  * @param symbol Symbol of the form USDC
878
1023
  * @returns Address of the corresponding token
879
1024
  */
880
- getMarginTokenFromSymbol(symbol) {
881
- let pools = this.poolStaticInfos;
882
- let poolId = PerpetualDataHandler._getPoolIdFromSymbol(symbol, this.poolStaticInfos);
883
- let k = 0;
1025
+ PerpetualDataHandler.prototype.getMarginTokenFromSymbol = function (symbol) {
1026
+ var pools = this.poolStaticInfos;
1027
+ var poolId = PerpetualDataHandler._getPoolIdFromSymbol(symbol, this.poolStaticInfos);
1028
+ var k = 0;
884
1029
  while (k < pools.length) {
885
1030
  if (pools[k].poolId == poolId) {
886
1031
  // pool found
@@ -889,16 +1034,16 @@ class PerpetualDataHandler {
889
1034
  k++;
890
1035
  }
891
1036
  return undefined;
892
- }
1037
+ };
893
1038
  /**
894
1039
  *
895
1040
  * @param symbol Symbol of the form USDC
896
1041
  * @returns Decimals of the corresponding token
897
1042
  */
898
- getMarginTokenDecimalsFromSymbol(symbol) {
899
- let pools = this.poolStaticInfos;
900
- let poolId = PerpetualDataHandler._getPoolIdFromSymbol(symbol, this.poolStaticInfos);
901
- let k = 0;
1043
+ PerpetualDataHandler.prototype.getMarginTokenDecimalsFromSymbol = function (symbol) {
1044
+ var pools = this.poolStaticInfos;
1045
+ var poolId = PerpetualDataHandler._getPoolIdFromSymbol(symbol, this.poolStaticInfos);
1046
+ var k = 0;
902
1047
  while (k < pools.length) {
903
1048
  if (pools[k].poolId == poolId) {
904
1049
  // pool found
@@ -907,13 +1052,13 @@ class PerpetualDataHandler {
907
1052
  k++;
908
1053
  }
909
1054
  return undefined;
910
- }
1055
+ };
911
1056
  /**
912
1057
  * Get ABI for LimitOrderBook, Proxy, or Share Pool Token
913
1058
  * @param contract name of contract: proxy|lob|sharetoken
914
1059
  * @returns ABI for the requested contract
915
1060
  */
916
- getABI(contract) {
1061
+ PerpetualDataHandler.prototype.getABI = function (contract) {
917
1062
  switch (contract) {
918
1063
  case "proxy":
919
1064
  return this.proxyABI;
@@ -924,22 +1069,22 @@ class PerpetualDataHandler {
924
1069
  default:
925
1070
  return undefined;
926
1071
  }
927
- }
1072
+ };
928
1073
  /**
929
1074
  * Performs basic validity checks on a given order
930
1075
  * @param order Order struct
931
1076
  * @param traderAccount Trader account
932
1077
  * @param perpStaticInfo Symbol to perpetual info map
933
1078
  */
934
- static checkOrder(order,
1079
+ PerpetualDataHandler.checkOrder = function (order,
935
1080
  // traderAccount: MarginAccount,
936
1081
  perpStaticInfo) {
937
1082
  // check side
938
1083
  if (order.side != nodeSDKTypes_1.BUY_SIDE && order.side != nodeSDKTypes_1.SELL_SIDE) {
939
- throw Error(`order side must be ${nodeSDKTypes_1.BUY_SIDE} or ${nodeSDKTypes_1.SELL_SIDE}`);
1084
+ throw Error("order side must be ".concat(nodeSDKTypes_1.BUY_SIDE, " or ").concat(nodeSDKTypes_1.SELL_SIDE));
940
1085
  }
941
1086
  // check amount
942
- let lotSize = perpStaticInfo.get(order.symbol).lotSizeBC;
1087
+ var lotSize = perpStaticInfo.get(order.symbol).lotSizeBC;
943
1088
  // let curPos =
944
1089
  // traderAccount.side == CLOSED_SIDE
945
1090
  // ? 0
@@ -947,21 +1092,22 @@ class PerpetualDataHandler {
947
1092
  // let newPos = curPos + (order.side == BUY_SIDE ? 1 : -1) * order.quantity;
948
1093
  // if (Math.abs(order.quantity) < lotSize || (Math.abs(newPos) >= lotSize && Math.abs(newPos) < 10 * lotSize)) {
949
1094
  if (Math.abs(order.quantity) < lotSize) {
950
- throw Error(`trade amount too small: ${order.quantity} ${perpStaticInfo.get(order.symbol).S2Symbol}`);
1095
+ throw Error("trade amount too small: ".concat(order.quantity, " ").concat(perpStaticInfo.get(order.symbol).S2Symbol));
951
1096
  }
952
1097
  // check limit price
953
1098
  if (order.side == nodeSDKTypes_1.BUY_SIDE && order.limitPrice != undefined && order.limitPrice <= 0) {
954
- throw Error(`invalid limit price for buy order: ${order.limitPrice}`);
1099
+ throw Error("invalid limit price for buy order: ".concat(order.limitPrice));
955
1100
  }
956
1101
  // broker fee
957
1102
  if (order.brokerFeeTbps != undefined && order.brokerFeeTbps < 0) {
958
- throw Error(`invalid broker fee: ${order.brokerFeeTbps / 10} bps`);
1103
+ throw Error("invalid broker fee: ".concat(order.brokerFeeTbps / 10, " bps"));
959
1104
  }
960
1105
  // stop price
961
1106
  if (order.stopPrice != undefined && order.stopPrice < 0) {
962
- throw Error(`invalid stop price: ${order.stopPrice}`);
1107
+ throw Error("invalid stop price: ".concat(order.stopPrice));
963
1108
  }
964
- }
965
- }
1109
+ };
1110
+ return PerpetualDataHandler;
1111
+ }());
966
1112
  exports.default = PerpetualDataHandler;
967
1113
  //# sourceMappingURL=perpetualDataHandler.js.map