@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,22 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const tslib_1 = require("tslib");
4
- const bignumber_1 = require("@ethersproject/bignumber");
5
- const providers_1 = require("@ethersproject/providers");
6
- const units_1 = require("@ethersproject/units");
7
- const contracts_1 = require("./contracts");
8
- const d8XMath_1 = require("./d8XMath");
9
- const nodeSDKTypes_1 = require("./nodeSDKTypes");
10
- const perpetualDataHandler_1 = tslib_1.__importDefault(require("./perpetualDataHandler"));
11
- const utils_1 = require("./utils");
3
+ var tslib_1 = require("tslib");
4
+ var bignumber_1 = require("@ethersproject/bignumber");
5
+ var providers_1 = require("@ethersproject/providers");
6
+ var units_1 = require("@ethersproject/units");
7
+ var contracts_1 = require("./contracts");
8
+ var d8XMath_1 = require("./d8XMath");
9
+ var nodeSDKTypes_1 = require("./nodeSDKTypes");
10
+ var perpetualDataHandler_1 = tslib_1.__importDefault(require("./perpetualDataHandler"));
11
+ var utils_1 = require("./utils");
12
12
  /**
13
13
  * Functions to access market data (e.g., information on open orders, information on products that can be traded).
14
14
  * This class requires no private key and is blockchain read-only.
15
15
  * No gas required for the queries here.
16
16
  * @extends PerpetualDataHandler
17
17
  */
18
- class MarketData extends perpetualDataHandler_1.default {
18
+ var MarketData = /** @class */ (function (_super) {
19
+ tslib_1.__extends(MarketData, _super);
19
20
  /**
20
21
  * Constructor
21
22
  * @param {NodeSDKConfig} config Configuration object, see
@@ -34,8 +35,8 @@ class MarketData extends perpetualDataHandler_1.default {
34
35
  * main();
35
36
  *
36
37
  */
37
- constructor(config) {
38
- super(config);
38
+ function MarketData(config) {
39
+ return _super.call(this, config) || this;
39
40
  }
40
41
  /**
41
42
  * Initialize the marketData-Class with this function
@@ -43,33 +44,43 @@ class MarketData extends perpetualDataHandler_1.default {
43
44
  * about perpetual currencies
44
45
  * @param provider optional provider
45
46
  */
46
- async createProxyInstance(provider, overrides) {
47
- if (provider == undefined) {
48
- this.provider = new providers_1.StaticJsonRpcProvider(this.nodeURL);
49
- }
50
- else {
51
- this.provider = provider;
52
- }
53
- await this.initContractsAndData(this.provider, overrides);
54
- }
47
+ MarketData.prototype.createProxyInstance = function (provider, overrides) {
48
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
49
+ return tslib_1.__generator(this, function (_a) {
50
+ switch (_a.label) {
51
+ case 0:
52
+ if (provider == undefined) {
53
+ this.provider = new providers_1.StaticJsonRpcProvider(this.nodeURL);
54
+ }
55
+ else {
56
+ this.provider = provider;
57
+ }
58
+ return [4 /*yield*/, this.initContractsAndData(this.provider, overrides)];
59
+ case 1:
60
+ _a.sent();
61
+ return [2 /*return*/];
62
+ }
63
+ });
64
+ });
65
+ };
55
66
  /**
56
67
  * Get the proxy address
57
68
  * @returns Address of the perpetual proxy contract
58
69
  */
59
- getProxyAddress() {
70
+ MarketData.prototype.getProxyAddress = function () {
60
71
  if (this.proxyContract == null) {
61
72
  throw Error("no proxy contract initialized. Use createProxyInstance().");
62
73
  }
63
74
  return this.proxyContract.address;
64
- }
75
+ };
65
76
  /**
66
77
  * Convert the smart contract output of an order into a convenient format of type "Order"
67
78
  * @param smOrder SmartContractOrder, as obtained e.g., by PerpetualLimitOrderCreated event
68
79
  * @returns more convenient format of order, type "Order"
69
80
  */
70
- smartContractOrderToOrder(smOrder) {
81
+ MarketData.prototype.smartContractOrderToOrder = function (smOrder) {
71
82
  return perpetualDataHandler_1.default.fromSmartContractOrder(smOrder, this.symbolToPerpStaticInfo);
72
- }
83
+ };
73
84
  /**
74
85
  * Get contract instance. Useful for event listening.
75
86
  * @example
@@ -88,12 +99,12 @@ class MarketData extends perpetualDataHandler_1.default {
88
99
  *
89
100
  * @returns read-only proxy instance
90
101
  */
91
- getReadOnlyProxyInstance() {
102
+ MarketData.prototype.getReadOnlyProxyInstance = function () {
92
103
  if (this.proxyContract == null) {
93
104
  throw Error("no proxy contract initialized. Use createProxyInstance().");
94
105
  }
95
106
  return this.proxyContract;
96
- }
107
+ };
97
108
  /**
98
109
  * Information about the products traded in the exchange.
99
110
  * @example
@@ -112,12 +123,20 @@ class MarketData extends perpetualDataHandler_1.default {
112
123
  *
113
124
  * @returns {ExchangeInfo} Array of static data for all the pools and perpetuals in the system.
114
125
  */
115
- async exchangeInfo(overrides) {
116
- if (this.proxyContract == null) {
117
- throw Error("no proxy contract initialized. Use createProxyInstance().");
118
- }
119
- return await MarketData._exchangeInfo(this.proxyContract, this.poolStaticInfos, this.symbolToPerpStaticInfo, this.perpetualIdToSymbol, this.nestedPerpetualIDs, this.symbolList, this.priceFeedGetter, overrides);
120
- }
126
+ MarketData.prototype.exchangeInfo = function (overrides) {
127
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
128
+ return tslib_1.__generator(this, function (_a) {
129
+ switch (_a.label) {
130
+ case 0:
131
+ if (this.proxyContract == null) {
132
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
133
+ }
134
+ return [4 /*yield*/, MarketData._exchangeInfo(this.proxyContract, this.poolStaticInfos, this.symbolToPerpStaticInfo, this.perpetualIdToSymbol, this.nestedPerpetualIDs, this.symbolList, this.priceFeedGetter, overrides)];
135
+ case 1: return [2 /*return*/, _a.sent()];
136
+ }
137
+ });
138
+ });
139
+ };
121
140
  /**
122
141
  * All open orders for a trader-address and a symbol.
123
142
  * @param {string} traderAddr Address of the trader for which we get the open orders.
@@ -139,40 +158,58 @@ class MarketData extends perpetualDataHandler_1.default {
139
158
  *
140
159
  * @returns For each perpetual an array of open orders and corresponding order-ids.
141
160
  */
142
- async openOrders(traderAddr, symbol, overrides) {
143
- // open orders requested only for given symbol
144
- let resArray = [];
145
- if (symbol.split("-").length == 1) {
146
- // pool symbol
147
- const symbols = this.getPerpetualSymbolsInPool(symbol);
148
- let prom = [];
149
- for (let k = 0; k < symbols.length; k++) {
150
- let p = this._openOrdersOfPerpetual(traderAddr, symbols[k], overrides);
151
- prom.push(p);
152
- }
153
- resArray = await Promise.all(prom);
154
- }
155
- else {
156
- let res = await this._openOrdersOfPerpetual(traderAddr, symbol, overrides);
157
- resArray.push(res);
158
- }
159
- return resArray;
160
- }
161
+ MarketData.prototype.openOrders = function (traderAddr, symbol, overrides) {
162
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
163
+ var resArray, symbols, prom, k, p, res;
164
+ return tslib_1.__generator(this, function (_a) {
165
+ switch (_a.label) {
166
+ case 0:
167
+ resArray = [];
168
+ if (!(symbol.split("-").length == 1)) return [3 /*break*/, 2];
169
+ symbols = this.getPerpetualSymbolsInPool(symbol);
170
+ prom = [];
171
+ for (k = 0; k < symbols.length; k++) {
172
+ p = this._openOrdersOfPerpetual(traderAddr, symbols[k], overrides);
173
+ prom.push(p);
174
+ }
175
+ return [4 /*yield*/, Promise.all(prom)];
176
+ case 1:
177
+ resArray = _a.sent();
178
+ return [3 /*break*/, 4];
179
+ case 2: return [4 /*yield*/, this._openOrdersOfPerpetual(traderAddr, symbol, overrides)];
180
+ case 3:
181
+ res = _a.sent();
182
+ resArray.push(res);
183
+ _a.label = 4;
184
+ case 4: return [2 /*return*/, resArray];
185
+ }
186
+ });
187
+ });
188
+ };
161
189
  /**
162
190
  * All open orders for a trader-address and a given perpetual symbol.
163
191
  * @param {string} traderAddr Address of the trader for which we get the open orders.
164
192
  * @param {string} symbol perpetual-symbol of the form ETH-USD-MATIC
165
193
  * @returns open orders and order ids
166
194
  */
167
- async _openOrdersOfPerpetual(traderAddr, symbol, overrides) {
168
- // open orders requested only for given symbol
169
- let orderBookContract = this.getOrderBookContract(symbol);
170
- let [orders, digests] = await Promise.all([
171
- this.openOrdersOnOrderBook(traderAddr, orderBookContract, overrides),
172
- MarketData.orderIdsOfTrader(traderAddr, orderBookContract, overrides),
173
- ]);
174
- return { orders: orders, orderIds: digests };
175
- }
195
+ MarketData.prototype._openOrdersOfPerpetual = function (traderAddr, symbol, overrides) {
196
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
197
+ var orderBookContract, _a, orders, digests;
198
+ return tslib_1.__generator(this, function (_b) {
199
+ switch (_b.label) {
200
+ case 0:
201
+ orderBookContract = this.getOrderBookContract(symbol);
202
+ return [4 /*yield*/, Promise.all([
203
+ this.openOrdersOnOrderBook(traderAddr, orderBookContract, overrides),
204
+ MarketData.orderIdsOfTrader(traderAddr, orderBookContract, overrides),
205
+ ])];
206
+ case 1:
207
+ _a = tslib_1.__read.apply(void 0, [_b.sent(), 2]), orders = _a[0], digests = _a[1];
208
+ return [2 /*return*/, { orders: orders, orderIds: digests }];
209
+ }
210
+ });
211
+ });
212
+ };
176
213
  /**
177
214
  * Information about the position open by a given trader in a given perpetual contract, or
178
215
  * for all perpetuals in a pool
@@ -195,38 +232,59 @@ class MarketData extends perpetualDataHandler_1.default {
195
232
  *
196
233
  * @returns {MarginAccount[]} Array of position risks of trader.
197
234
  */
198
- async positionRisk(traderAddr, symbol, overrides) {
199
- if (this.proxyContract == null) {
200
- throw Error("no proxy contract initialized. Use createProxyInstance().");
201
- }
202
- let resArray = [];
203
- if (symbol.split("-").length == 1) {
204
- // pool symbol
205
- const symbols = this.getPerpetualSymbolsInPool(symbol);
206
- let prom = [];
207
- for (let k = 0; k < symbols.length; k++) {
208
- let p = this._positionRiskForTraderInPerpetual(traderAddr, symbols[k], overrides);
209
- prom.push(p);
210
- }
211
- resArray = await Promise.all(prom);
212
- }
213
- else {
214
- let res = await this._positionRiskForTraderInPerpetual(traderAddr, symbol, overrides);
215
- resArray.push(res);
216
- }
217
- return resArray;
218
- }
235
+ MarketData.prototype.positionRisk = function (traderAddr, symbol, overrides) {
236
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
237
+ var resArray, symbols, prom, k, p, res;
238
+ return tslib_1.__generator(this, function (_a) {
239
+ switch (_a.label) {
240
+ case 0:
241
+ if (this.proxyContract == null) {
242
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
243
+ }
244
+ resArray = [];
245
+ if (!(symbol.split("-").length == 1)) return [3 /*break*/, 2];
246
+ symbols = this.getPerpetualSymbolsInPool(symbol);
247
+ prom = [];
248
+ for (k = 0; k < symbols.length; k++) {
249
+ p = this._positionRiskForTraderInPerpetual(traderAddr, symbols[k], overrides);
250
+ prom.push(p);
251
+ }
252
+ return [4 /*yield*/, Promise.all(prom)];
253
+ case 1:
254
+ resArray = _a.sent();
255
+ return [3 /*break*/, 4];
256
+ case 2: return [4 /*yield*/, this._positionRiskForTraderInPerpetual(traderAddr, symbol, overrides)];
257
+ case 3:
258
+ res = _a.sent();
259
+ resArray.push(res);
260
+ _a.label = 4;
261
+ case 4: return [2 /*return*/, resArray];
262
+ }
263
+ });
264
+ });
265
+ };
219
266
  /**
220
267
  * Information about the position open by a given trader in a given perpetual contract.
221
268
  * @param {string} traderAddr Address of the trader for which we get the position risk.
222
269
  * @param {string} symbol perpetual symbol of the form ETH-USD-MATIC
223
270
  * @returns MarginAccount struct for the trader
224
271
  */
225
- async _positionRiskForTraderInPerpetual(traderAddr, symbol, overrides) {
226
- let obj = await this.priceFeedGetter.fetchPricesForPerpetual(symbol);
227
- let mgnAcct = await perpetualDataHandler_1.default.getMarginAccount(traderAddr, symbol, this.symbolToPerpStaticInfo, this.proxyContract, [obj.idxPrices[0], obj.idxPrices[1]], overrides);
228
- return mgnAcct;
229
- }
272
+ MarketData.prototype._positionRiskForTraderInPerpetual = function (traderAddr, symbol, overrides) {
273
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
274
+ var obj, mgnAcct;
275
+ return tslib_1.__generator(this, function (_a) {
276
+ switch (_a.label) {
277
+ case 0: return [4 /*yield*/, this.priceFeedGetter.fetchPricesForPerpetual(symbol)];
278
+ case 1:
279
+ obj = _a.sent();
280
+ return [4 /*yield*/, perpetualDataHandler_1.default.getMarginAccount(traderAddr, symbol, this.symbolToPerpStaticInfo, this.proxyContract, [obj.idxPrices[0], obj.idxPrices[1]], overrides)];
281
+ case 2:
282
+ mgnAcct = _a.sent();
283
+ return [2 /*return*/, mgnAcct];
284
+ }
285
+ });
286
+ });
287
+ };
230
288
  /**
231
289
  * Estimates what the position risk will be if a given order is executed.
232
290
  * @param traderAddr Address of trader
@@ -235,118 +293,119 @@ class MarketData extends perpetualDataHandler_1.default {
235
293
  * @param indexPriceInfo Index prices and market status (open/closed)
236
294
  * @returns Position risk after trade
237
295
  */
238
- async positionRiskOnTrade(traderAddr, order, account, indexPriceInfo, overrides) {
239
- if (this.proxyContract == null) {
240
- throw Error("no proxy contract initialized. Use createProxyInstance().");
241
- }
242
- // fetch undefined data
243
- if (account == undefined) {
244
- account = (await this.positionRisk(traderAddr, order.symbol, overrides))[0];
245
- }
246
- if (indexPriceInfo == undefined) {
247
- let obj = await this.priceFeedGetter.fetchPricesForPerpetual(account.symbol);
248
- indexPriceInfo = [obj.idxPrices[0], obj.idxPrices[1], obj.mktClosed[0], obj.mktClosed[1]];
249
- }
250
- let lotSizeBC = MarketData._getLotSize(account.symbol, this.symbolToPerpStaticInfo);
251
- // Too small, no change to account
252
- if (Math.abs(order.quantity) < lotSizeBC) {
253
- return { newPositionRisk: account, orderCost: 0 };
254
- }
255
- // Current state:
256
- // perp (for FXs and such)
257
- let perpetualState = await this.getPerpetualState(order.symbol, indexPriceInfo, overrides);
258
- let [S2, S3, Sm] = [perpetualState.indexPrice, perpetualState.collToQuoteIndexPrice, perpetualState.markPrice];
259
- // cash in margin account: upon trading, unpaid funding will be realized
260
- let currentMarginCashCC = account.collateralCC;
261
- // signed position, still correct if side is closed (==0)
262
- let currentPositionBC = (account.side == nodeSDKTypes_1.BUY_SIDE ? 1 : -1) * account.positionNotionalBaseCCY;
263
- // signed locked-in value
264
- let currentLockedInQC = account.entryPrice * currentPositionBC;
265
- // New trader state:
266
- // signed trade amount
267
- let tradeAmountBC = Math.abs(order.quantity) * (order.side == nodeSDKTypes_1.BUY_SIDE ? 1 : -1);
268
- // signed position
269
- let newPositionBC = currentPositionBC + tradeAmountBC;
270
- if (Math.abs(newPositionBC) < 10 * lotSizeBC) {
271
- // fully closed
272
- tradeAmountBC = -currentPositionBC;
273
- newPositionBC = 0;
274
- }
275
- let newSide = newPositionBC > 0 ? nodeSDKTypes_1.BUY_SIDE : newPositionBC < 0 ? nodeSDKTypes_1.SELL_SIDE : nodeSDKTypes_1.CLOSED_SIDE;
276
- // price for this order = limit price (conservative) if given, else the current perp price
277
- let tradePrice = order.limitPrice ??
278
- (await this.getPerpetualPrice(order.symbol, tradeAmountBC, [indexPriceInfo[0], indexPriceInfo[1]], overrides));
279
- // fees
280
- let poolId = perpetualDataHandler_1.default._getPoolIdFromSymbol(order.symbol, this.poolStaticInfos);
281
- let exchangeFeeTbps = await this.proxyContract.queryExchangeFee(poolId, traderAddr, order.brokerAddr ?? nodeSDKTypes_1.ZERO_ADDRESS, overrides || {});
282
- let exchangeFeeCC = (Math.abs(tradeAmountBC) * exchangeFeeTbps * 1e-5 * S2) / S3;
283
- let brokerFeeCC = (Math.abs(tradeAmountBC) * (order.brokerFeeTbps ?? 0) * 1e-5 * S2) / S3;
284
- let referralFeeCC = this.symbolToPerpStaticInfo.get(account.symbol).referralRebate;
285
- // Trade type:
286
- let isClose = newPositionBC == 0 || newPositionBC * tradeAmountBC < 0;
287
- let isOpen = newPositionBC != 0 && (currentPositionBC == 0 || tradeAmountBC * currentPositionBC > 0); // regular open, no flip
288
- let isFlip = Math.abs(newPositionBC) > Math.abs(currentPositionBC) && !isOpen; // flip position sign, not fully closed
289
- let keepPositionLvgOnClose = (order.keepPositionLvg ?? false) && !isOpen;
290
- // Contract: _doMarginCollateralActions
291
- // No collateral actions if
292
- // 1) leverage is not set or
293
- // 2) fully closed after trade or
294
- // 3) is a partial closing, it doesn't flip, and keep lvg flag is not set
295
- let traderDepositCC;
296
- let targetLvg;
297
- if (order.leverage == undefined || newPositionBC == 0 || (!isOpen && !isFlip && !keepPositionLvgOnClose)) {
298
- traderDepositCC = 0;
299
- targetLvg = 0;
300
- }
301
- else {
302
- // 1) opening and flipping trades need to specify a leverage: default to max if not given
303
- // 2) for others it's ignored, set target to 0
304
- let initialMarginRate = this.symbolToPerpStaticInfo.get(account.symbol).initialMarginRate;
305
- targetLvg = isFlip || isOpen ? order.leverage ?? 1 / initialMarginRate : 0;
306
- let [b0, pos0] = isOpen ? [0, 0] : [account.collateralCC, currentPositionBC];
307
- traderDepositCC = (0, d8XMath_1.getDepositAmountForLvgTrade)(b0, pos0, tradeAmountBC, targetLvg, tradePrice, S3, Sm);
308
- // fees are paid from wallet in this case
309
- traderDepositCC += exchangeFeeCC + brokerFeeCC + referralFeeCC;
310
- }
311
- // Contract: _executeTrade
312
- let deltaCashCC = (-tradeAmountBC * (tradePrice - S2)) / S3;
313
- let deltaLockedQC = tradeAmountBC * S2;
314
- if (isClose) {
315
- let pnl = account.entryPrice * tradeAmountBC - deltaLockedQC;
316
- deltaLockedQC += pnl;
317
- deltaCashCC += pnl / S3;
318
- }
319
- // funding and fees
320
- deltaCashCC = deltaCashCC + account.unrealizedFundingCollateralCCY - exchangeFeeCC - brokerFeeCC - referralFeeCC;
321
- // New cash, locked-in, entry price & leverage after trade
322
- let newLockedInValueQC = currentLockedInQC + deltaLockedQC;
323
- let newMarginCashCC = currentMarginCashCC + deltaCashCC + traderDepositCC;
324
- let newEntryPrice = newPositionBC == 0 ? 0 : Math.abs(newLockedInValueQC / newPositionBC);
325
- let newMarginBalanceCC = newMarginCashCC + (newPositionBC * Sm - newLockedInValueQC) / S3;
326
- let newLeverage = newPositionBC == 0
327
- ? 0
328
- : newMarginBalanceCC <= 0
329
- ? Infinity
330
- : (Math.abs(newPositionBC) * Sm) / S3 / newMarginBalanceCC;
331
- // Liquidation params
332
- let [S2Liq, S3Liq, tau] = MarketData._getLiquidationParams(account.symbol, newLockedInValueQC, newPositionBC, newMarginCashCC, Sm, S3, this.symbolToPerpStaticInfo);
333
- // New position risk
334
- let newPositionRisk = {
335
- symbol: account.symbol,
336
- positionNotionalBaseCCY: Math.abs(newPositionBC),
337
- side: newSide,
338
- entryPrice: newEntryPrice,
339
- leverage: newLeverage,
340
- markPrice: Sm,
341
- unrealizedPnlQuoteCCY: newPositionBC * Sm - newLockedInValueQC,
342
- unrealizedFundingCollateralCCY: 0,
343
- collateralCC: newMarginCashCC,
344
- collToQuoteConversion: S3,
345
- liquidationPrice: [S2Liq, S3Liq],
346
- liquidationLvg: 1 / tau,
347
- };
348
- return { newPositionRisk: newPositionRisk, orderCost: traderDepositCC };
349
- }
296
+ MarketData.prototype.positionRiskOnTrade = function (traderAddr, order, account, indexPriceInfo, overrides) {
297
+ var _a, _b, _c, _d, _e;
298
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
299
+ var obj, lotSizeBC, perpetualState, _f, S2, S3, Sm, currentMarginCashCC, currentPositionBC, currentLockedInQC, tradeAmountBC, newPositionBC, newSide, tradePrice, _g, poolId, exchangeFeeTbps, exchangeFeeCC, brokerFeeCC, referralFeeCC, isClose, isOpen, isFlip, keepPositionLvgOnClose, traderDepositCC, targetLvg, initialMarginRate, _h, b0, pos0, deltaCashCC, deltaLockedQC, pnl, newLockedInValueQC, newMarginCashCC, newEntryPrice, newMarginBalanceCC, newLeverage, _j, S2Liq, S3Liq, tau, newPositionRisk;
300
+ return tslib_1.__generator(this, function (_k) {
301
+ switch (_k.label) {
302
+ case 0:
303
+ if (this.proxyContract == null) {
304
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
305
+ }
306
+ if (!(account == undefined)) return [3 /*break*/, 2];
307
+ return [4 /*yield*/, this.positionRisk(traderAddr, order.symbol, overrides)];
308
+ case 1:
309
+ account = (_k.sent())[0];
310
+ _k.label = 2;
311
+ case 2:
312
+ if (!(indexPriceInfo == undefined)) return [3 /*break*/, 4];
313
+ return [4 /*yield*/, this.priceFeedGetter.fetchPricesForPerpetual(account.symbol)];
314
+ case 3:
315
+ obj = _k.sent();
316
+ indexPriceInfo = [obj.idxPrices[0], obj.idxPrices[1], obj.mktClosed[0], obj.mktClosed[1]];
317
+ _k.label = 4;
318
+ case 4:
319
+ lotSizeBC = MarketData._getLotSize(account.symbol, this.symbolToPerpStaticInfo);
320
+ // Too small, no change to account
321
+ if (Math.abs(order.quantity) < lotSizeBC) {
322
+ return [2 /*return*/, { newPositionRisk: account, orderCost: 0 }];
323
+ }
324
+ return [4 /*yield*/, this.getPerpetualState(order.symbol, indexPriceInfo, overrides)];
325
+ case 5:
326
+ perpetualState = _k.sent();
327
+ _f = tslib_1.__read([perpetualState.indexPrice, perpetualState.collToQuoteIndexPrice, perpetualState.markPrice], 3), S2 = _f[0], S3 = _f[1], Sm = _f[2];
328
+ currentMarginCashCC = account.collateralCC;
329
+ currentPositionBC = (account.side == nodeSDKTypes_1.BUY_SIDE ? 1 : -1) * account.positionNotionalBaseCCY;
330
+ currentLockedInQC = account.entryPrice * currentPositionBC;
331
+ tradeAmountBC = Math.abs(order.quantity) * (order.side == nodeSDKTypes_1.BUY_SIDE ? 1 : -1);
332
+ newPositionBC = currentPositionBC + tradeAmountBC;
333
+ if (Math.abs(newPositionBC) < 10 * lotSizeBC) {
334
+ // fully closed
335
+ tradeAmountBC = -currentPositionBC;
336
+ newPositionBC = 0;
337
+ }
338
+ newSide = newPositionBC > 0 ? nodeSDKTypes_1.BUY_SIDE : newPositionBC < 0 ? nodeSDKTypes_1.SELL_SIDE : nodeSDKTypes_1.CLOSED_SIDE;
339
+ if (!((_a = order.limitPrice) !== null && _a !== void 0)) return [3 /*break*/, 6];
340
+ _g = _a;
341
+ return [3 /*break*/, 8];
342
+ case 6: return [4 /*yield*/, this.getPerpetualPrice(order.symbol, tradeAmountBC, [indexPriceInfo[0], indexPriceInfo[1]], overrides)];
343
+ case 7:
344
+ _g = (_k.sent());
345
+ _k.label = 8;
346
+ case 8:
347
+ tradePrice = _g;
348
+ poolId = perpetualDataHandler_1.default._getPoolIdFromSymbol(order.symbol, this.poolStaticInfos);
349
+ return [4 /*yield*/, this.proxyContract.queryExchangeFee(poolId, traderAddr, (_b = order.brokerAddr) !== null && _b !== void 0 ? _b : nodeSDKTypes_1.ZERO_ADDRESS, overrides || {})];
350
+ case 9:
351
+ exchangeFeeTbps = _k.sent();
352
+ exchangeFeeCC = (Math.abs(tradeAmountBC) * exchangeFeeTbps * 1e-5 * S2) / S3;
353
+ brokerFeeCC = (Math.abs(tradeAmountBC) * ((_c = order.brokerFeeTbps) !== null && _c !== void 0 ? _c : 0) * 1e-5 * S2) / S3;
354
+ referralFeeCC = this.symbolToPerpStaticInfo.get(account.symbol).referralRebate;
355
+ isClose = newPositionBC == 0 || newPositionBC * tradeAmountBC < 0;
356
+ isOpen = newPositionBC != 0 && (currentPositionBC == 0 || tradeAmountBC * currentPositionBC > 0);
357
+ isFlip = Math.abs(newPositionBC) > Math.abs(currentPositionBC) && !isOpen;
358
+ keepPositionLvgOnClose = ((_d = order.keepPositionLvg) !== null && _d !== void 0 ? _d : false) && !isOpen;
359
+ if (order.leverage == undefined || newPositionBC == 0 || (!isOpen && !isFlip && !keepPositionLvgOnClose)) {
360
+ traderDepositCC = 0;
361
+ targetLvg = 0;
362
+ }
363
+ else {
364
+ initialMarginRate = this.symbolToPerpStaticInfo.get(account.symbol).initialMarginRate;
365
+ targetLvg = isFlip || isOpen ? (_e = order.leverage) !== null && _e !== void 0 ? _e : 1 / initialMarginRate : 0;
366
+ _h = tslib_1.__read(isOpen ? [0, 0] : [account.collateralCC, currentPositionBC], 2), b0 = _h[0], pos0 = _h[1];
367
+ traderDepositCC = (0, d8XMath_1.getDepositAmountForLvgTrade)(b0, pos0, tradeAmountBC, targetLvg, tradePrice, S3, Sm);
368
+ // fees are paid from wallet in this case
369
+ traderDepositCC += exchangeFeeCC + brokerFeeCC + referralFeeCC;
370
+ }
371
+ deltaCashCC = (-tradeAmountBC * (tradePrice - S2)) / S3;
372
+ deltaLockedQC = tradeAmountBC * S2;
373
+ if (isClose) {
374
+ pnl = account.entryPrice * tradeAmountBC - deltaLockedQC;
375
+ deltaLockedQC += pnl;
376
+ deltaCashCC += pnl / S3;
377
+ }
378
+ // funding and fees
379
+ deltaCashCC = deltaCashCC + account.unrealizedFundingCollateralCCY - exchangeFeeCC - brokerFeeCC - referralFeeCC;
380
+ newLockedInValueQC = currentLockedInQC + deltaLockedQC;
381
+ newMarginCashCC = currentMarginCashCC + deltaCashCC + traderDepositCC;
382
+ newEntryPrice = newPositionBC == 0 ? 0 : Math.abs(newLockedInValueQC / newPositionBC);
383
+ newMarginBalanceCC = newMarginCashCC + (newPositionBC * Sm - newLockedInValueQC) / S3;
384
+ newLeverage = newPositionBC == 0
385
+ ? 0
386
+ : newMarginBalanceCC <= 0
387
+ ? Infinity
388
+ : (Math.abs(newPositionBC) * Sm) / S3 / newMarginBalanceCC;
389
+ _j = tslib_1.__read(MarketData._getLiquidationParams(account.symbol, newLockedInValueQC, newPositionBC, newMarginCashCC, Sm, S3, this.symbolToPerpStaticInfo), 3), S2Liq = _j[0], S3Liq = _j[1], tau = _j[2];
390
+ newPositionRisk = {
391
+ symbol: account.symbol,
392
+ positionNotionalBaseCCY: Math.abs(newPositionBC),
393
+ side: newSide,
394
+ entryPrice: newEntryPrice,
395
+ leverage: newLeverage,
396
+ markPrice: Sm,
397
+ unrealizedPnlQuoteCCY: newPositionBC * Sm - newLockedInValueQC,
398
+ unrealizedFundingCollateralCCY: 0,
399
+ collateralCC: newMarginCashCC,
400
+ collToQuoteConversion: S3,
401
+ liquidationPrice: [S2Liq, S3Liq],
402
+ liquidationLvg: 1 / tau,
403
+ };
404
+ return [2 /*return*/, { newPositionRisk: newPositionRisk, orderCost: traderDepositCC }];
405
+ }
406
+ });
407
+ });
408
+ };
350
409
  /**
351
410
  * Estimates what the position risk will be if given amount of collateral is added/removed from the account.
352
411
  * @param traderAddr Address of trader
@@ -354,80 +413,90 @@ class MarketData extends perpetualDataHandler_1.default {
354
413
  * @param currentPositionRisk Position risk before
355
414
  * @returns {MarginAccount} Position risk after
356
415
  */
357
- async positionRiskOnCollateralAction(deltaCollateral, account, indexPriceInfo, overrides) {
358
- if (this.proxyContract == null) {
359
- throw Error("no proxy contract initialized. Use createProxyInstance().");
360
- }
361
- if (deltaCollateral + account.collateralCC + account.unrealizedFundingCollateralCCY < 0) {
362
- throw Error("not enough margin to remove");
363
- }
364
- if (indexPriceInfo == undefined) {
365
- let obj = await this.priceFeedGetter.fetchPricesForPerpetual(account.symbol);
366
- indexPriceInfo = [obj.idxPrices[0], obj.idxPrices[1], obj.mktClosed[0], obj.mktClosed[1]];
367
- }
368
- let perpetualState = await this.getPerpetualState(account.symbol, indexPriceInfo, overrides);
369
- let [S2, S3, Sm] = [perpetualState.indexPrice, perpetualState.collToQuoteIndexPrice, perpetualState.markPrice];
370
- // no position: just increase collateral and kill liquidation vars
371
- if (account.positionNotionalBaseCCY == 0) {
372
- return {
373
- symbol: account.symbol,
374
- positionNotionalBaseCCY: account.positionNotionalBaseCCY,
375
- side: account.side,
376
- entryPrice: account.entryPrice,
377
- leverage: account.leverage,
378
- markPrice: Sm,
379
- unrealizedPnlQuoteCCY: account.unrealizedPnlQuoteCCY,
380
- unrealizedFundingCollateralCCY: account.unrealizedFundingCollateralCCY,
381
- collateralCC: account.collateralCC + deltaCollateral,
382
- collToQuoteConversion: S3,
383
- liquidationPrice: [0, undefined],
384
- liquidationLvg: Infinity,
385
- };
386
- }
387
- let positionBC = account.positionNotionalBaseCCY * (account.side == nodeSDKTypes_1.BUY_SIDE ? 1 : -1);
388
- let lockedInQC = account.entryPrice * positionBC;
389
- let newMarginCashCC = account.collateralCC + deltaCollateral;
390
- let newMarginBalanceCC = newMarginCashCC + account.unrealizedFundingCollateralCCY + (positionBC * Sm - lockedInQC) / S3;
391
- if (newMarginBalanceCC <= 0) {
392
- return {
393
- symbol: account.symbol,
394
- positionNotionalBaseCCY: account.positionNotionalBaseCCY,
395
- side: account.side,
396
- entryPrice: account.entryPrice,
397
- leverage: Infinity,
398
- markPrice: Sm,
399
- unrealizedPnlQuoteCCY: account.unrealizedPnlQuoteCCY,
400
- unrealizedFundingCollateralCCY: account.unrealizedFundingCollateralCCY,
401
- collateralCC: newMarginCashCC,
402
- collToQuoteConversion: S3,
403
- liquidationPrice: [S2, S3],
404
- liquidationLvg: 0,
405
- };
406
- }
407
- let newLeverage = (Math.abs(positionBC) * Sm) / S3 / newMarginBalanceCC;
408
- // Liquidation params
409
- let [S2Liq, S3Liq, tau] = MarketData._getLiquidationParams(account.symbol, lockedInQC, positionBC, newMarginCashCC, Sm, S3, this.symbolToPerpStaticInfo);
410
- // New position risk
411
- let newPositionRisk = {
412
- symbol: account.symbol,
413
- positionNotionalBaseCCY: account.positionNotionalBaseCCY,
414
- side: account.side,
415
- entryPrice: account.entryPrice,
416
- leverage: newLeverage,
417
- markPrice: Sm,
418
- unrealizedPnlQuoteCCY: account.unrealizedPnlQuoteCCY,
419
- unrealizedFundingCollateralCCY: account.unrealizedFundingCollateralCCY,
420
- collateralCC: newMarginCashCC,
421
- collToQuoteConversion: S3,
422
- liquidationPrice: [S2Liq, S3Liq],
423
- liquidationLvg: 1 / tau,
424
- };
425
- return newPositionRisk;
426
- }
427
- static _getLiquidationParams(symbol, lockedInQC, signedPositionBC, marginCashCC, markPrice, collToQuoteConversion, symbolToPerpStaticInfo) {
428
- let S2Liq, S3Liq;
429
- let tau = symbolToPerpStaticInfo.get(symbol).maintenanceMarginRate;
430
- let ccyType = symbolToPerpStaticInfo.get(symbol).collateralCurrencyType;
416
+ MarketData.prototype.positionRiskOnCollateralAction = function (deltaCollateral, account, indexPriceInfo, overrides) {
417
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
418
+ var obj, perpetualState, _a, S2, S3, Sm, positionBC, lockedInQC, newMarginCashCC, newMarginBalanceCC, newLeverage, _b, S2Liq, S3Liq, tau, newPositionRisk;
419
+ return tslib_1.__generator(this, function (_c) {
420
+ switch (_c.label) {
421
+ case 0:
422
+ if (this.proxyContract == null) {
423
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
424
+ }
425
+ if (deltaCollateral + account.collateralCC + account.unrealizedFundingCollateralCCY < 0) {
426
+ throw Error("not enough margin to remove");
427
+ }
428
+ if (!(indexPriceInfo == undefined)) return [3 /*break*/, 2];
429
+ return [4 /*yield*/, this.priceFeedGetter.fetchPricesForPerpetual(account.symbol)];
430
+ case 1:
431
+ obj = _c.sent();
432
+ indexPriceInfo = [obj.idxPrices[0], obj.idxPrices[1], obj.mktClosed[0], obj.mktClosed[1]];
433
+ _c.label = 2;
434
+ case 2: return [4 /*yield*/, this.getPerpetualState(account.symbol, indexPriceInfo, overrides)];
435
+ case 3:
436
+ perpetualState = _c.sent();
437
+ _a = tslib_1.__read([perpetualState.indexPrice, perpetualState.collToQuoteIndexPrice, perpetualState.markPrice], 3), S2 = _a[0], S3 = _a[1], Sm = _a[2];
438
+ // no position: just increase collateral and kill liquidation vars
439
+ if (account.positionNotionalBaseCCY == 0) {
440
+ return [2 /*return*/, {
441
+ symbol: account.symbol,
442
+ positionNotionalBaseCCY: account.positionNotionalBaseCCY,
443
+ side: account.side,
444
+ entryPrice: account.entryPrice,
445
+ leverage: account.leverage,
446
+ markPrice: Sm,
447
+ unrealizedPnlQuoteCCY: account.unrealizedPnlQuoteCCY,
448
+ unrealizedFundingCollateralCCY: account.unrealizedFundingCollateralCCY,
449
+ collateralCC: account.collateralCC + deltaCollateral,
450
+ collToQuoteConversion: S3,
451
+ liquidationPrice: [0, undefined],
452
+ liquidationLvg: Infinity,
453
+ }];
454
+ }
455
+ positionBC = account.positionNotionalBaseCCY * (account.side == nodeSDKTypes_1.BUY_SIDE ? 1 : -1);
456
+ lockedInQC = account.entryPrice * positionBC;
457
+ newMarginCashCC = account.collateralCC + deltaCollateral;
458
+ newMarginBalanceCC = newMarginCashCC + account.unrealizedFundingCollateralCCY + (positionBC * Sm - lockedInQC) / S3;
459
+ if (newMarginBalanceCC <= 0) {
460
+ return [2 /*return*/, {
461
+ symbol: account.symbol,
462
+ positionNotionalBaseCCY: account.positionNotionalBaseCCY,
463
+ side: account.side,
464
+ entryPrice: account.entryPrice,
465
+ leverage: Infinity,
466
+ markPrice: Sm,
467
+ unrealizedPnlQuoteCCY: account.unrealizedPnlQuoteCCY,
468
+ unrealizedFundingCollateralCCY: account.unrealizedFundingCollateralCCY,
469
+ collateralCC: newMarginCashCC,
470
+ collToQuoteConversion: S3,
471
+ liquidationPrice: [S2, S3],
472
+ liquidationLvg: 0,
473
+ }];
474
+ }
475
+ newLeverage = (Math.abs(positionBC) * Sm) / S3 / newMarginBalanceCC;
476
+ _b = tslib_1.__read(MarketData._getLiquidationParams(account.symbol, lockedInQC, positionBC, newMarginCashCC, Sm, S3, this.symbolToPerpStaticInfo), 3), S2Liq = _b[0], S3Liq = _b[1], tau = _b[2];
477
+ newPositionRisk = {
478
+ symbol: account.symbol,
479
+ positionNotionalBaseCCY: account.positionNotionalBaseCCY,
480
+ side: account.side,
481
+ entryPrice: account.entryPrice,
482
+ leverage: newLeverage,
483
+ markPrice: Sm,
484
+ unrealizedPnlQuoteCCY: account.unrealizedPnlQuoteCCY,
485
+ unrealizedFundingCollateralCCY: account.unrealizedFundingCollateralCCY,
486
+ collateralCC: newMarginCashCC,
487
+ collToQuoteConversion: S3,
488
+ liquidationPrice: [S2Liq, S3Liq],
489
+ liquidationLvg: 1 / tau,
490
+ };
491
+ return [2 /*return*/, newPositionRisk];
492
+ }
493
+ });
494
+ });
495
+ };
496
+ MarketData._getLiquidationParams = function (symbol, lockedInQC, signedPositionBC, marginCashCC, markPrice, collToQuoteConversion, symbolToPerpStaticInfo) {
497
+ var S2Liq, S3Liq;
498
+ var tau = symbolToPerpStaticInfo.get(symbol).maintenanceMarginRate;
499
+ var ccyType = symbolToPerpStaticInfo.get(symbol).collateralCurrencyType;
431
500
  if (ccyType == nodeSDKTypes_1.CollaterlCCY.BASE) {
432
501
  S2Liq = (0, d8XMath_1.calculateLiquidationPriceCollateralBase)(lockedInQC, signedPositionBC, marginCashCC, tau);
433
502
  S3Liq = S2Liq;
@@ -443,53 +512,90 @@ class MarketData extends perpetualDataHandler_1.default {
443
512
  S2Liq = S2Liq < 0 ? 0 : S2Liq;
444
513
  S3Liq = S3Liq && S3Liq < 0 ? 0 : S3Liq;
445
514
  return [S2Liq, S3Liq, tau];
446
- }
515
+ };
447
516
  /**
448
517
  * Gets the wallet balance in the collateral currency corresponding to a given perpetual symbol.
449
518
  * @param address Address to check
450
519
  * @param symbol Symbol of the form ETH-USD-MATIC.
451
520
  * @returns Balance
452
521
  */
453
- async getWalletBalance(address, symbol, overrides) {
454
- let poolIdx = this.getPoolStaticInfoIndexFromSymbol(symbol);
455
- let marginTokenAddr = this.poolStaticInfos[poolIdx].poolMarginTokenAddr;
456
- let token = contracts_1.ERC20__factory.connect(marginTokenAddr, this.provider);
457
- let walletBalance = await token.balanceOf(address, overrides || {});
458
- let decimals = await token.decimals(overrides || {});
459
- return Number((0, units_1.formatUnits)(walletBalance, decimals));
460
- }
522
+ MarketData.prototype.getWalletBalance = function (address, symbol, overrides) {
523
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
524
+ var poolIdx, marginTokenAddr, token, walletBalance, decimals;
525
+ return tslib_1.__generator(this, function (_a) {
526
+ switch (_a.label) {
527
+ case 0:
528
+ poolIdx = this.getPoolStaticInfoIndexFromSymbol(symbol);
529
+ marginTokenAddr = this.poolStaticInfos[poolIdx].poolMarginTokenAddr;
530
+ token = contracts_1.ERC20__factory.connect(marginTokenAddr, this.provider);
531
+ return [4 /*yield*/, token.balanceOf(address, overrides || {})];
532
+ case 1:
533
+ walletBalance = _a.sent();
534
+ return [4 /*yield*/, token.decimals(overrides || {})];
535
+ case 2:
536
+ decimals = _a.sent();
537
+ return [2 /*return*/, Number((0, units_1.formatUnits)(walletBalance, decimals))];
538
+ }
539
+ });
540
+ });
541
+ };
461
542
  /**
462
543
  * Get the address' balance of the pool share token
463
544
  * @param address address of the liquidity provider
464
545
  * @param symbolOrId Symbol of the form ETH-USD-MATIC, or MATIC (collateral only), or Pool-Id
465
546
  */
466
- async getPoolShareTokenBalance(address, symbolOrId, overrides) {
467
- let poolId = this._poolSymbolOrIdToPoolId(symbolOrId);
468
- return this._getPoolShareTokenBalanceFromId(address, poolId, overrides);
469
- }
547
+ MarketData.prototype.getPoolShareTokenBalance = function (address, symbolOrId, overrides) {
548
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
549
+ var poolId;
550
+ return tslib_1.__generator(this, function (_a) {
551
+ poolId = this._poolSymbolOrIdToPoolId(symbolOrId);
552
+ return [2 /*return*/, this._getPoolShareTokenBalanceFromId(address, poolId, overrides)];
553
+ });
554
+ });
555
+ };
470
556
  /**
471
557
  * Query the pool share token holdings of address
472
558
  * @param address address of token holder
473
559
  * @param poolId pool id
474
560
  * @returns pool share token balance of address
475
561
  */
476
- async _getPoolShareTokenBalanceFromId(address, poolId, overrides) {
477
- let shareTokenAddr = this.poolStaticInfos[poolId - 1].shareTokenAddr;
478
- let shareToken = contracts_1.ERC20__factory.connect(shareTokenAddr, this.provider);
479
- let d18ShareTokenBalanceOfAddr = await shareToken.balanceOf(address, overrides || {});
480
- return (0, d8XMath_1.dec18ToFloat)(d18ShareTokenBalanceOfAddr);
481
- }
562
+ MarketData.prototype._getPoolShareTokenBalanceFromId = function (address, poolId, overrides) {
563
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
564
+ var shareTokenAddr, shareToken, d18ShareTokenBalanceOfAddr;
565
+ return tslib_1.__generator(this, function (_a) {
566
+ switch (_a.label) {
567
+ case 0:
568
+ shareTokenAddr = this.poolStaticInfos[poolId - 1].shareTokenAddr;
569
+ shareToken = contracts_1.ERC20__factory.connect(shareTokenAddr, this.provider);
570
+ return [4 /*yield*/, shareToken.balanceOf(address, overrides || {})];
571
+ case 1:
572
+ d18ShareTokenBalanceOfAddr = _a.sent();
573
+ return [2 /*return*/, (0, d8XMath_1.dec18ToFloat)(d18ShareTokenBalanceOfAddr)];
574
+ }
575
+ });
576
+ });
577
+ };
482
578
  /**
483
579
  * Value of pool token in collateral currency
484
580
  * @param symbolOrId symbol of the form ETH-USD-MATIC, MATIC (collateral), or poolId
485
581
  * @returns current pool share token price in collateral currency
486
582
  */
487
- async getShareTokenPrice(symbolOrId, overrides) {
488
- let poolId = this._poolSymbolOrIdToPoolId(symbolOrId);
489
- const priceDec18 = await this.proxyContract.getShareTokenPriceD18(poolId, overrides || {});
490
- const price = (0, d8XMath_1.dec18ToFloat)(priceDec18);
491
- return price;
492
- }
583
+ MarketData.prototype.getShareTokenPrice = function (symbolOrId, overrides) {
584
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
585
+ var poolId, priceDec18, price;
586
+ return tslib_1.__generator(this, function (_a) {
587
+ switch (_a.label) {
588
+ case 0:
589
+ poolId = this._poolSymbolOrIdToPoolId(symbolOrId);
590
+ return [4 /*yield*/, this.proxyContract.getShareTokenPriceD18(poolId, overrides || {})];
591
+ case 1:
592
+ priceDec18 = _a.sent();
593
+ price = (0, d8XMath_1.dec18ToFloat)(priceDec18);
594
+ return [2 /*return*/, price];
595
+ }
596
+ });
597
+ });
598
+ };
493
599
  /**
494
600
  * Value of the pool share tokens for this liquidity provider
495
601
  * in poolSymbol-currency (e.g. MATIC, USDC).
@@ -510,24 +616,36 @@ class MarketData extends perpetualDataHandler_1.default {
510
616
  * main();
511
617
  * @returns the value (in collateral tokens) of the pool share, #share tokens, shareTokenAddress
512
618
  */
513
- async getParticipationValue(address, symbolOrId, overrides) {
514
- let poolId = this._poolSymbolOrIdToPoolId(symbolOrId);
515
- const shareTokens = await this._getPoolShareTokenBalanceFromId(address, poolId, overrides);
516
- const priceDec18 = await this.proxyContract.getShareTokenPriceD18(poolId, overrides || {});
517
- const price = (0, d8XMath_1.dec18ToFloat)(priceDec18);
518
- const value = price * shareTokens;
519
- const shareTokenAddr = this.poolStaticInfos[poolId - 1].shareTokenAddr;
520
- return {
521
- value: value,
522
- shareTokenBalance: shareTokens,
523
- poolShareToken: shareTokenAddr,
524
- };
525
- }
526
- _poolSymbolOrIdToPoolId(poolSymbolOrId) {
619
+ MarketData.prototype.getParticipationValue = function (address, symbolOrId, overrides) {
620
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
621
+ var poolId, shareTokens, priceDec18, price, value, shareTokenAddr;
622
+ return tslib_1.__generator(this, function (_a) {
623
+ switch (_a.label) {
624
+ case 0:
625
+ poolId = this._poolSymbolOrIdToPoolId(symbolOrId);
626
+ return [4 /*yield*/, this._getPoolShareTokenBalanceFromId(address, poolId, overrides)];
627
+ case 1:
628
+ shareTokens = _a.sent();
629
+ return [4 /*yield*/, this.proxyContract.getShareTokenPriceD18(poolId, overrides || {})];
630
+ case 2:
631
+ priceDec18 = _a.sent();
632
+ price = (0, d8XMath_1.dec18ToFloat)(priceDec18);
633
+ value = price * shareTokens;
634
+ shareTokenAddr = this.poolStaticInfos[poolId - 1].shareTokenAddr;
635
+ return [2 /*return*/, {
636
+ value: value,
637
+ shareTokenBalance: shareTokens,
638
+ poolShareToken: shareTokenAddr,
639
+ }];
640
+ }
641
+ });
642
+ });
643
+ };
644
+ MarketData.prototype._poolSymbolOrIdToPoolId = function (poolSymbolOrId) {
527
645
  if (this.proxyContract == null || this.poolStaticInfos.length == 0) {
528
646
  throw Error("no proxy contract or wallet or data initialized. Use createProxyInstance().");
529
647
  }
530
- let poolId;
648
+ var poolId;
531
649
  if (isNaN(Number(poolSymbolOrId))) {
532
650
  poolId = perpetualDataHandler_1.default._getPoolIdFromSymbol(poolSymbolOrId, this.poolStaticInfos);
533
651
  }
@@ -535,7 +653,7 @@ class MarketData extends perpetualDataHandler_1.default {
535
653
  poolId = Number(poolSymbolOrId);
536
654
  }
537
655
  return poolId;
538
- }
656
+ };
539
657
  /**
540
658
  * Gets the maximal order size to open positions (increase size),
541
659
  * considering the existing position, state of the perpetual
@@ -544,24 +662,44 @@ class MarketData extends perpetualDataHandler_1.default {
544
662
  * @param positionRisk Current position risk (as seen in positionRisk)
545
663
  * @returns Maximal trade size, not signed
546
664
  */
547
- async maxOrderSizeForTrader(side, positionRisk, overrides) {
548
- let curPosition = side == nodeSDKTypes_1.BUY_SIDE ? positionRisk.positionNotionalBaseCCY : -positionRisk.positionNotionalBaseCCY;
549
- let perpId = this.getPerpIdFromSymbol(positionRisk.symbol);
550
- let perpMaxPositionABK = await this.proxyContract.getMaxSignedOpenTradeSizeForPos(perpId, (0, d8XMath_1.floatToABK64x64)(curPosition), side == nodeSDKTypes_1.BUY_SIDE, overrides || {});
551
- return (0, d8XMath_1.ABK64x64ToFloat)(perpMaxPositionABK.abs());
552
- }
665
+ MarketData.prototype.maxOrderSizeForTrader = function (side, positionRisk, overrides) {
666
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
667
+ var curPosition, perpId, perpMaxPositionABK;
668
+ return tslib_1.__generator(this, function (_a) {
669
+ switch (_a.label) {
670
+ case 0:
671
+ curPosition = side == nodeSDKTypes_1.BUY_SIDE ? positionRisk.positionNotionalBaseCCY : -positionRisk.positionNotionalBaseCCY;
672
+ perpId = this.getPerpIdFromSymbol(positionRisk.symbol);
673
+ return [4 /*yield*/, this.proxyContract.getMaxSignedOpenTradeSizeForPos(perpId, (0, d8XMath_1.floatToABK64x64)(curPosition), side == nodeSDKTypes_1.BUY_SIDE, overrides || {})];
674
+ case 1:
675
+ perpMaxPositionABK = _a.sent();
676
+ return [2 /*return*/, (0, d8XMath_1.ABK64x64ToFloat)(perpMaxPositionABK.abs())];
677
+ }
678
+ });
679
+ });
680
+ };
553
681
  /**
554
682
  *
555
683
  * @param side BUY_SIDE or SELL_SIDE
556
684
  * @param symbol of the form ETH-USD-MATIC.
557
685
  * @returns signed maximal position size in base currency
558
686
  */
559
- async maxSignedPosition(side, symbol, overrides) {
560
- let perpId = this.getPerpIdFromSymbol(symbol);
561
- let isBuy = side == nodeSDKTypes_1.BUY_SIDE;
562
- let maxSignedPos = await this.proxyContract.getMaxSignedOpenTradeSizeForPos(perpId, bignumber_1.BigNumber.from(0), isBuy, overrides || {});
563
- return (0, d8XMath_1.ABK64x64ToFloat)(maxSignedPos);
564
- }
687
+ MarketData.prototype.maxSignedPosition = function (side, symbol, overrides) {
688
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
689
+ var perpId, isBuy, maxSignedPos;
690
+ return tslib_1.__generator(this, function (_a) {
691
+ switch (_a.label) {
692
+ case 0:
693
+ perpId = this.getPerpIdFromSymbol(symbol);
694
+ isBuy = side == nodeSDKTypes_1.BUY_SIDE;
695
+ return [4 /*yield*/, this.proxyContract.getMaxSignedOpenTradeSizeForPos(perpId, bignumber_1.BigNumber.from(0), isBuy, overrides || {})];
696
+ case 1:
697
+ maxSignedPos = _a.sent();
698
+ return [2 /*return*/, (0, d8XMath_1.ABK64x64ToFloat)(maxSignedPos)];
699
+ }
700
+ });
701
+ });
702
+ };
565
703
  /**
566
704
  * Uses the Oracle(s) in the exchange to get the latest price of a given index in a given currency, if a route exists.
567
705
  * @param {string} base Index name, e.g. ETH.
@@ -582,13 +720,23 @@ class MarketData extends perpetualDataHandler_1.default {
582
720
  *
583
721
  * @returns {number} Price of index in given currency.
584
722
  */
585
- async getOraclePrice(base, quote, overrides) {
586
- if (!this.proxyContract) {
587
- throw Error("no proxy contract initialized. Use createProxyInstance().");
588
- }
589
- let px = await this.proxyContract.getOraclePrice([(0, utils_1.toBytes4)(base), (0, utils_1.toBytes4)(quote)], overrides || {});
590
- return px == undefined ? undefined : (0, d8XMath_1.ABK64x64ToFloat)(px);
591
- }
723
+ MarketData.prototype.getOraclePrice = function (base, quote, overrides) {
724
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
725
+ var px;
726
+ return tslib_1.__generator(this, function (_a) {
727
+ switch (_a.label) {
728
+ case 0:
729
+ if (!this.proxyContract) {
730
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
731
+ }
732
+ return [4 /*yield*/, this.proxyContract.getOraclePrice([(0, utils_1.toBytes4)(base), (0, utils_1.toBytes4)(quote)], overrides || {})];
733
+ case 1:
734
+ px = _a.sent();
735
+ return [2 /*return*/, px == undefined ? undefined : (0, d8XMath_1.ABK64x64ToFloat)(px)];
736
+ }
737
+ });
738
+ });
739
+ };
592
740
  /**
593
741
  *
594
742
  * @param symbol Symbol of the form ETH-USD-MATIC
@@ -596,14 +744,24 @@ class MarketData extends perpetualDataHandler_1.default {
596
744
  * @param overrides
597
745
  * @returns Order status ()
598
746
  */
599
- async getOrderStatus(symbol, orderId, overrides) {
600
- if (!this.proxyContract) {
601
- throw Error("no proxy contract initialized. Use createProxyInstance().");
602
- }
603
- const orderBookContract = this.getOrderBookContract(symbol);
604
- let status = await orderBookContract.getOrderStatus(orderId, overrides || {});
605
- return status;
606
- }
747
+ MarketData.prototype.getOrderStatus = function (symbol, orderId, overrides) {
748
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
749
+ var orderBookContract, status;
750
+ return tslib_1.__generator(this, function (_a) {
751
+ switch (_a.label) {
752
+ case 0:
753
+ if (!this.proxyContract) {
754
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
755
+ }
756
+ orderBookContract = this.getOrderBookContract(symbol);
757
+ return [4 /*yield*/, orderBookContract.getOrderStatus(orderId, overrides || {})];
758
+ case 1:
759
+ status = _a.sent();
760
+ return [2 /*return*/, status];
761
+ }
762
+ });
763
+ });
764
+ };
607
765
  /**
608
766
  * Get the current mark price
609
767
  * @param symbol symbol of the form ETH-USD-MATIC
@@ -623,16 +781,27 @@ class MarketData extends perpetualDataHandler_1.default {
623
781
  *
624
782
  * @returns mark price
625
783
  */
626
- async getMarkPrice(symbol, indexPrices) {
627
- if (this.proxyContract == null) {
628
- throw Error("no proxy contract initialized. Use createProxyInstance().");
629
- }
630
- if (indexPrices == undefined) {
631
- let obj = await this.priceFeedGetter.fetchPricesForPerpetual(symbol);
632
- indexPrices = [obj.idxPrices[0], obj.idxPrices[1]];
633
- }
634
- return await perpetualDataHandler_1.default._queryPerpetualMarkPrice(symbol, this.symbolToPerpStaticInfo, this.proxyContract, indexPrices);
635
- }
784
+ MarketData.prototype.getMarkPrice = function (symbol, indexPrices) {
785
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
786
+ var obj;
787
+ return tslib_1.__generator(this, function (_a) {
788
+ switch (_a.label) {
789
+ case 0:
790
+ if (this.proxyContract == null) {
791
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
792
+ }
793
+ if (!(indexPrices == undefined)) return [3 /*break*/, 2];
794
+ return [4 /*yield*/, this.priceFeedGetter.fetchPricesForPerpetual(symbol)];
795
+ case 1:
796
+ obj = _a.sent();
797
+ indexPrices = [obj.idxPrices[0], obj.idxPrices[1]];
798
+ _a.label = 2;
799
+ case 2: return [4 /*yield*/, perpetualDataHandler_1.default._queryPerpetualMarkPrice(symbol, this.symbolToPerpStaticInfo, this.proxyContract, indexPrices)];
800
+ case 3: return [2 /*return*/, _a.sent()];
801
+ }
802
+ });
803
+ });
804
+ };
636
805
  /**
637
806
  * get the current price for a given quantity
638
807
  * @param symbol symbol of the form ETH-USD-MATIC
@@ -653,72 +822,104 @@ class MarketData extends perpetualDataHandler_1.default {
653
822
  *
654
823
  * @returns price (number)
655
824
  */
656
- async getPerpetualPrice(symbol, quantity, indexPrices, overrides) {
657
- if (this.proxyContract == null) {
658
- throw Error("no proxy contract initialized. Use createProxyInstance().");
659
- }
660
- if (indexPrices == undefined) {
661
- // fetch from API
662
- let obj = await this.priceFeedGetter.fetchPricesForPerpetual(symbol);
663
- indexPrices = [obj.idxPrices[0], obj.idxPrices[1]];
664
- }
665
- return await perpetualDataHandler_1.default._queryPerpetualPrice(symbol, quantity, this.symbolToPerpStaticInfo, this.proxyContract, indexPrices, overrides);
666
- }
825
+ MarketData.prototype.getPerpetualPrice = function (symbol, quantity, indexPrices, overrides) {
826
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
827
+ var obj;
828
+ return tslib_1.__generator(this, function (_a) {
829
+ switch (_a.label) {
830
+ case 0:
831
+ if (this.proxyContract == null) {
832
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
833
+ }
834
+ if (!(indexPrices == undefined)) return [3 /*break*/, 2];
835
+ return [4 /*yield*/, this.priceFeedGetter.fetchPricesForPerpetual(symbol)];
836
+ case 1:
837
+ obj = _a.sent();
838
+ indexPrices = [obj.idxPrices[0], obj.idxPrices[1]];
839
+ _a.label = 2;
840
+ case 2: return [4 /*yield*/, perpetualDataHandler_1.default._queryPerpetualPrice(symbol, quantity, this.symbolToPerpStaticInfo, this.proxyContract, indexPrices, overrides)];
841
+ case 3: return [2 /*return*/, _a.sent()];
842
+ }
843
+ });
844
+ });
845
+ };
667
846
  /**
668
847
  * Query recent perpetual state from blockchain
669
848
  * @param symbol symbol of the form ETH-USD-MATIC
670
849
  * @param indexPrices S2 and S3 prices/isMarketOpen if not provided fetch via REST API
671
850
  * @returns PerpetualState reference
672
851
  */
673
- async getPerpetualState(symbol, indexPriceInfo, overrides) {
674
- if (this.proxyContract == null) {
675
- throw Error("no proxy contract initialized. Use createProxyInstance().");
676
- }
677
- if (indexPriceInfo == undefined) {
678
- let obj = await this.priceFeedGetter.fetchPricesForPerpetual(symbol);
679
- indexPriceInfo = [obj.idxPrices[0], obj.idxPrices[1], obj.mktClosed[0], obj.mktClosed[1]];
680
- }
681
- let state = await perpetualDataHandler_1.default._queryPerpetualState(symbol, this.symbolToPerpStaticInfo, this.proxyContract, indexPriceInfo, overrides);
682
- return state;
683
- }
852
+ MarketData.prototype.getPerpetualState = function (symbol, indexPriceInfo, overrides) {
853
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
854
+ var obj, state;
855
+ return tslib_1.__generator(this, function (_a) {
856
+ switch (_a.label) {
857
+ case 0:
858
+ if (this.proxyContract == null) {
859
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
860
+ }
861
+ if (!(indexPriceInfo == undefined)) return [3 /*break*/, 2];
862
+ return [4 /*yield*/, this.priceFeedGetter.fetchPricesForPerpetual(symbol)];
863
+ case 1:
864
+ obj = _a.sent();
865
+ indexPriceInfo = [obj.idxPrices[0], obj.idxPrices[1], obj.mktClosed[0], obj.mktClosed[1]];
866
+ _a.label = 2;
867
+ case 2: return [4 /*yield*/, perpetualDataHandler_1.default._queryPerpetualState(symbol, this.symbolToPerpStaticInfo, this.proxyContract, indexPriceInfo, overrides)];
868
+ case 3:
869
+ state = _a.sent();
870
+ return [2 /*return*/, state];
871
+ }
872
+ });
873
+ });
874
+ };
684
875
  /**
685
876
  * Query recent pool state from blockchain, not including perpetual states
686
877
  * @param symbol symbol of the form USDC
687
878
  * @param indexPrices S2 and S3 prices/isMarketOpen if not provided fetch via REST API
688
879
  * @returns PoolState reference
689
880
  */
690
- async getPoolState(poolSymbol, overrides) {
691
- if (this.proxyContract == null) {
692
- throw Error("no proxy contract initialized. Use createProxyInstance().");
693
- }
694
- const poolId = this._poolSymbolOrIdToPoolId(poolSymbol);
695
- const pool = await this.proxyContract.getLiquidityPool(poolId, overrides || {});
696
- let state = {
697
- isRunning: pool.isRunning,
698
- poolSymbol: poolSymbol,
699
- marginTokenAddr: pool.marginTokenAddress,
700
- poolShareTokenAddr: pool.shareTokenAddress,
701
- defaultFundCashCC: (0, d8XMath_1.ABK64x64ToFloat)(pool.fDefaultFundCashCC),
702
- pnlParticipantCashCC: (0, d8XMath_1.ABK64x64ToFloat)(pool.fPnLparticipantsCashCC),
703
- totalTargetAMMFundSizeCC: (0, d8XMath_1.ABK64x64ToFloat)(pool.fTargetAMMFundSize),
704
- brokerCollateralLotSize: (0, d8XMath_1.ABK64x64ToFloat)(pool.fBrokerCollateralLotSize),
705
- perpetuals: [],
706
- };
707
- return state;
708
- }
881
+ MarketData.prototype.getPoolState = function (poolSymbol, overrides) {
882
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
883
+ var poolId, pool, state;
884
+ return tslib_1.__generator(this, function (_a) {
885
+ switch (_a.label) {
886
+ case 0:
887
+ if (this.proxyContract == null) {
888
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
889
+ }
890
+ poolId = this._poolSymbolOrIdToPoolId(poolSymbol);
891
+ return [4 /*yield*/, this.proxyContract.getLiquidityPool(poolId, overrides || {})];
892
+ case 1:
893
+ pool = _a.sent();
894
+ state = {
895
+ isRunning: pool.isRunning,
896
+ poolSymbol: poolSymbol,
897
+ marginTokenAddr: pool.marginTokenAddress,
898
+ poolShareTokenAddr: pool.shareTokenAddress,
899
+ defaultFundCashCC: (0, d8XMath_1.ABK64x64ToFloat)(pool.fDefaultFundCashCC),
900
+ pnlParticipantCashCC: (0, d8XMath_1.ABK64x64ToFloat)(pool.fPnLparticipantsCashCC),
901
+ totalTargetAMMFundSizeCC: (0, d8XMath_1.ABK64x64ToFloat)(pool.fTargetAMMFundSize),
902
+ brokerCollateralLotSize: (0, d8XMath_1.ABK64x64ToFloat)(pool.fBrokerCollateralLotSize),
903
+ perpetuals: [],
904
+ };
905
+ return [2 /*return*/, state];
906
+ }
907
+ });
908
+ });
909
+ };
709
910
  /**
710
911
  * Query perpetual static info.
711
912
  * This information is queried once at createProxyInstance-time and remains static after that.
712
913
  * @param symbol symbol of the form ETH-USD-MATIC
713
914
  * @returns PerpetualStaticInfo copy.
714
915
  */
715
- getPerpetualStaticInfo(symbol) {
716
- let perpInfo = this.symbolToPerpStaticInfo.get(symbol);
916
+ MarketData.prototype.getPerpetualStaticInfo = function (symbol) {
917
+ var perpInfo = this.symbolToPerpStaticInfo.get(symbol);
717
918
  if (perpInfo == undefined) {
718
- throw Error(`Perpetual with symbol ${symbol} not found. Check symbol or use createProxyInstance().`);
919
+ throw Error("Perpetual with symbol ".concat(symbol, " not found. Check symbol or use createProxyInstance()."));
719
920
  }
720
921
  // return new copy, not a reference
721
- let res = {
922
+ var res = {
722
923
  id: perpInfo.id,
723
924
  poolId: perpInfo.poolId,
724
925
  limitOrderBookAddr: perpInfo.limitOrderBookAddr,
@@ -732,7 +933,7 @@ class MarketData extends perpetualDataHandler_1.default {
732
933
  priceIds: perpInfo.priceIds,
733
934
  };
734
935
  return res;
735
- }
936
+ };
736
937
  /**
737
938
  * get the current mid-price for a perpetual
738
939
  * @param symbol symbol of the form ETH-USD-MATIC
@@ -752,12 +953,20 @@ class MarketData extends perpetualDataHandler_1.default {
752
953
  *
753
954
  * @returns {number} price
754
955
  */
755
- async getPerpetualMidPrice(symbol) {
756
- if (this.proxyContract == null) {
757
- throw Error("no proxy contract initialized. Use createProxyInstance().");
758
- }
759
- return await this.getPerpetualPrice(symbol, 0);
760
- }
956
+ MarketData.prototype.getPerpetualMidPrice = function (symbol) {
957
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
958
+ return tslib_1.__generator(this, function (_a) {
959
+ switch (_a.label) {
960
+ case 0:
961
+ if (this.proxyContract == null) {
962
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
963
+ }
964
+ return [4 /*yield*/, this.getPerpetualPrice(symbol, 0)];
965
+ case 1: return [2 /*return*/, _a.sent()];
966
+ }
967
+ });
968
+ });
969
+ };
761
970
  /**
762
971
  * Query smart contract to get user orders and convert to user friendly order format.
763
972
  * @param {string} traderAddr Address of trader.
@@ -765,24 +974,35 @@ class MarketData extends perpetualDataHandler_1.default {
765
974
  * @returns {Order[]} Array of user friendly order struct.
766
975
  * @ignore
767
976
  */
768
- async openOrdersOnOrderBook(traderAddr, orderBookContract, overrides) {
769
- //eliminate empty orders and map to user friendly orders
770
- let userFriendlyOrders = new Array();
771
- let haveMoreOrders = true;
772
- let from = 0;
773
- const bulkSize = 15;
774
- while (haveMoreOrders) {
775
- let orders = await orderBookContract.getOrders(traderAddr, from, bulkSize, overrides || {});
776
- let k = 0;
777
- while (k < orders.length && orders[k].traderAddr !== nodeSDKTypes_1.ZERO_ADDRESS) {
778
- userFriendlyOrders.push(perpetualDataHandler_1.default.fromClientOrder(orders[k], this.symbolToPerpStaticInfo));
779
- k++;
780
- }
781
- haveMoreOrders = orders[orders.length - 1].traderAddr !== nodeSDKTypes_1.ZERO_ADDRESS;
782
- from = from + bulkSize;
783
- }
784
- return userFriendlyOrders;
785
- }
977
+ MarketData.prototype.openOrdersOnOrderBook = function (traderAddr, orderBookContract, overrides) {
978
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
979
+ var userFriendlyOrders, haveMoreOrders, from, bulkSize, orders, k;
980
+ return tslib_1.__generator(this, function (_a) {
981
+ switch (_a.label) {
982
+ case 0:
983
+ userFriendlyOrders = new Array();
984
+ haveMoreOrders = true;
985
+ from = 0;
986
+ bulkSize = 15;
987
+ _a.label = 1;
988
+ case 1:
989
+ if (!haveMoreOrders) return [3 /*break*/, 3];
990
+ return [4 /*yield*/, orderBookContract.getOrders(traderAddr, from, bulkSize, overrides || {})];
991
+ case 2:
992
+ orders = _a.sent();
993
+ k = 0;
994
+ while (k < orders.length && orders[k].traderAddr !== nodeSDKTypes_1.ZERO_ADDRESS) {
995
+ userFriendlyOrders.push(perpetualDataHandler_1.default.fromClientOrder(orders[k], this.symbolToPerpStaticInfo));
996
+ k++;
997
+ }
998
+ haveMoreOrders = orders[orders.length - 1].traderAddr !== nodeSDKTypes_1.ZERO_ADDRESS;
999
+ from = from + bulkSize;
1000
+ return [3 /*break*/, 1];
1001
+ case 3: return [2 /*return*/, userFriendlyOrders];
1002
+ }
1003
+ });
1004
+ });
1005
+ };
786
1006
  /**
787
1007
  *
788
1008
  * @param traderAddr Address of the trader
@@ -790,16 +1010,25 @@ class MarketData extends perpetualDataHandler_1.default {
790
1010
  * @returns Array of order-id's
791
1011
  * @ignore
792
1012
  */
793
- static async orderIdsOfTrader(traderAddr, orderBookContract, overrides) {
794
- let digestsRaw = await orderBookContract.limitDigestsOfTrader(traderAddr, 0, 15, overrides || {});
795
- let k = 0;
796
- let digests = [];
797
- while (k < digestsRaw.length && bignumber_1.BigNumber.from(digestsRaw[k]).gt(0)) {
798
- digests.push(digestsRaw[k]);
799
- k++;
800
- }
801
- return digests;
802
- }
1013
+ MarketData.orderIdsOfTrader = function (traderAddr, orderBookContract, overrides) {
1014
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
1015
+ var digestsRaw, k, digests;
1016
+ return tslib_1.__generator(this, function (_a) {
1017
+ switch (_a.label) {
1018
+ case 0: return [4 /*yield*/, orderBookContract.limitDigestsOfTrader(traderAddr, 0, 15, overrides || {})];
1019
+ case 1:
1020
+ digestsRaw = _a.sent();
1021
+ k = 0;
1022
+ digests = [];
1023
+ while (k < digestsRaw.length && bignumber_1.BigNumber.from(digestsRaw[k]).gt(0)) {
1024
+ digests.push(digestsRaw[k]);
1025
+ k++;
1026
+ }
1027
+ return [2 /*return*/, digests];
1028
+ }
1029
+ });
1030
+ });
1031
+ };
803
1032
  /**
804
1033
  * Query the available margin conditional on the given (or current) index prices
805
1034
  * Result is in collateral currency
@@ -808,106 +1037,165 @@ class MarketData extends perpetualDataHandler_1.default {
808
1037
  * @param indexPrices optional index prices, will otherwise fetch from REST API
809
1038
  * @returns available margin in collateral currency
810
1039
  */
811
- async getAvailableMargin(traderAddr, symbol, indexPrices, overrides) {
812
- if (!this.proxyContract) {
813
- throw Error("no proxy contract initialized. Use createProxyInstance().");
814
- }
815
- if (indexPrices == undefined) {
816
- // fetch from API
817
- let obj = await this.priceFeedGetter.fetchPricesForPerpetual(symbol);
818
- indexPrices = [obj.idxPrices[0], obj.idxPrices[1]];
819
- }
820
- let perpID = perpetualDataHandler_1.default.symbolToPerpetualId(symbol, this.symbolToPerpStaticInfo);
821
- let traderState = await this.proxyContract.getTraderState(perpID, traderAddr, indexPrices.map((x) => (0, d8XMath_1.floatToABK64x64)(x)), overrides || {});
822
- const idx_availableMargin = 1;
823
- let mgn = (0, d8XMath_1.ABK64x64ToFloat)(traderState[idx_availableMargin]);
824
- return mgn;
825
- }
1040
+ MarketData.prototype.getAvailableMargin = function (traderAddr, symbol, indexPrices, overrides) {
1041
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
1042
+ var obj, perpID, traderState, idx_availableMargin, mgn;
1043
+ return tslib_1.__generator(this, function (_a) {
1044
+ switch (_a.label) {
1045
+ case 0:
1046
+ if (!this.proxyContract) {
1047
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
1048
+ }
1049
+ if (!(indexPrices == undefined)) return [3 /*break*/, 2];
1050
+ return [4 /*yield*/, this.priceFeedGetter.fetchPricesForPerpetual(symbol)];
1051
+ case 1:
1052
+ obj = _a.sent();
1053
+ indexPrices = [obj.idxPrices[0], obj.idxPrices[1]];
1054
+ _a.label = 2;
1055
+ case 2:
1056
+ perpID = perpetualDataHandler_1.default.symbolToPerpetualId(symbol, this.symbolToPerpStaticInfo);
1057
+ return [4 /*yield*/, this.proxyContract.getTraderState(perpID, traderAddr, indexPrices.map(function (x) { return (0, d8XMath_1.floatToABK64x64)(x); }), overrides || {})];
1058
+ case 3:
1059
+ traderState = _a.sent();
1060
+ idx_availableMargin = 1;
1061
+ mgn = (0, d8XMath_1.ABK64x64ToFloat)(traderState[idx_availableMargin]);
1062
+ return [2 /*return*/, mgn];
1063
+ }
1064
+ });
1065
+ });
1066
+ };
826
1067
  /**
827
1068
  * Calculate a type of exchange loyality score based on trader volume
828
1069
  * @param traderAddr address of the trader
829
1070
  * @param brokerAddr address of the trader's broker or undefined
830
1071
  * @returns a loyality score (4 worst, 1 best)
831
1072
  */
832
- async getTraderLoyalityScore(traderAddr, brokerAddr, overrides) {
833
- if (this.proxyContract == null) {
834
- throw Error("no proxy contract or wallet initialized. Use createProxyInstance().");
835
- }
836
- // loop over all pools and query volumes
837
- let brokerProm = [];
838
- let traderProm = [];
839
- for (let k = 0; k < this.poolStaticInfos.length; k++) {
840
- if (brokerAddr != "" && brokerAddr != undefined) {
841
- let brkrVol = this.proxyContract.getCurrentBrokerVolume(this.poolStaticInfos[k].poolId, brokerAddr, overrides || {});
842
- brokerProm.push(brkrVol);
843
- }
844
- let trdrVol = this.proxyContract.getCurrentTraderVolume(this.poolStaticInfos[k].poolId, traderAddr, overrides || {});
845
- traderProm.push(trdrVol);
846
- }
847
- // sum
848
- let totalBrokerVolume = 0;
849
- let totalTraderVolume = 0;
850
- let brkrVol = await Promise.all(brokerProm);
851
- let trdrVol = await Promise.all(traderProm);
852
- for (let k = 0; k < this.poolStaticInfos.length; k++) {
853
- if (brokerAddr != "" && brokerAddr != undefined) {
854
- totalBrokerVolume += (0, d8XMath_1.ABK64x64ToFloat)(brkrVol[k]);
855
- }
856
- totalTraderVolume += (0, d8XMath_1.ABK64x64ToFloat)(trdrVol[k]);
857
- }
858
- const volumeCap = 500000;
859
- let score = totalBrokerVolume == 0 ? totalTraderVolume / volumeCap : totalBrokerVolume;
860
- // 5 different equally spaced categories: (4 is best, 1 worst)
861
- let rank4 = 1 + Math.floor(Math.min(score, 1 - 1e-15) * 4);
862
- // desired ranking starts at 4 (worst) and ends at 1 (best)
863
- return 5 - rank4;
864
- }
1073
+ MarketData.prototype.getTraderLoyalityScore = function (traderAddr, brokerAddr, overrides) {
1074
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
1075
+ var brokerProm, traderProm, k, brkrVol_1, trdrVol_1, totalBrokerVolume, totalTraderVolume, brkrVol, trdrVol, k, volumeCap, score, rank4;
1076
+ return tslib_1.__generator(this, function (_a) {
1077
+ switch (_a.label) {
1078
+ case 0:
1079
+ if (this.proxyContract == null) {
1080
+ throw Error("no proxy contract or wallet initialized. Use createProxyInstance().");
1081
+ }
1082
+ brokerProm = [];
1083
+ traderProm = [];
1084
+ for (k = 0; k < this.poolStaticInfos.length; k++) {
1085
+ if (brokerAddr != "" && brokerAddr != undefined) {
1086
+ brkrVol_1 = this.proxyContract.getCurrentBrokerVolume(this.poolStaticInfos[k].poolId, brokerAddr, overrides || {});
1087
+ brokerProm.push(brkrVol_1);
1088
+ }
1089
+ trdrVol_1 = this.proxyContract.getCurrentTraderVolume(this.poolStaticInfos[k].poolId, traderAddr, overrides || {});
1090
+ traderProm.push(trdrVol_1);
1091
+ }
1092
+ totalBrokerVolume = 0;
1093
+ totalTraderVolume = 0;
1094
+ return [4 /*yield*/, Promise.all(brokerProm)];
1095
+ case 1:
1096
+ brkrVol = _a.sent();
1097
+ return [4 /*yield*/, Promise.all(traderProm)];
1098
+ case 2:
1099
+ trdrVol = _a.sent();
1100
+ for (k = 0; k < this.poolStaticInfos.length; k++) {
1101
+ if (brokerAddr != "" && brokerAddr != undefined) {
1102
+ totalBrokerVolume += (0, d8XMath_1.ABK64x64ToFloat)(brkrVol[k]);
1103
+ }
1104
+ totalTraderVolume += (0, d8XMath_1.ABK64x64ToFloat)(trdrVol[k]);
1105
+ }
1106
+ volumeCap = 500000;
1107
+ score = totalBrokerVolume == 0 ? totalTraderVolume / volumeCap : totalBrokerVolume;
1108
+ rank4 = 1 + Math.floor(Math.min(score, 1 - 1e-15) * 4);
1109
+ // desired ranking starts at 4 (worst) and ends at 1 (best)
1110
+ return [2 /*return*/, 5 - rank4];
1111
+ }
1112
+ });
1113
+ });
1114
+ };
865
1115
  /**
866
1116
  * Get all off-chain prices
867
1117
  * @param _symbolToPerpStaticInfo mapping: PerpetualStaticInfo for each perpetual
868
1118
  * @param _priceFeedGetter priceFeed class from which we can get offchain price data
869
1119
  * @returns mapping of symbol-pair (e.g. BTC-USD) to price/isMarketClosed
870
1120
  */
871
- static async _getAllIndexPrices(_symbolToPerpStaticInfo, _priceFeedGetter) {
872
- // get all prices from off-chain price-sources
873
- let allSym = new Set();
874
- for (let perpSymbol of _symbolToPerpStaticInfo.keys()) {
875
- let sInfo = _symbolToPerpStaticInfo.get(perpSymbol);
876
- allSym.add(sInfo.S2Symbol);
877
- if (sInfo.S3Symbol != "") {
878
- allSym.add(sInfo.S3Symbol);
879
- }
880
- }
881
- let allSymArr = Array.from(allSym.values());
882
- let idxPriceMap = await _priceFeedGetter.fetchPrices(allSymArr);
883
- return idxPriceMap;
884
- }
1121
+ MarketData._getAllIndexPrices = function (_symbolToPerpStaticInfo, _priceFeedGetter) {
1122
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
1123
+ var allSym, _a, _b, perpSymbol, sInfo, allSymArr, idxPriceMap;
1124
+ var e_1, _c;
1125
+ return tslib_1.__generator(this, function (_d) {
1126
+ switch (_d.label) {
1127
+ case 0:
1128
+ allSym = new Set();
1129
+ try {
1130
+ for (_a = tslib_1.__values(_symbolToPerpStaticInfo.keys()), _b = _a.next(); !_b.done; _b = _a.next()) {
1131
+ perpSymbol = _b.value;
1132
+ sInfo = _symbolToPerpStaticInfo.get(perpSymbol);
1133
+ allSym.add(sInfo.S2Symbol);
1134
+ if (sInfo.S3Symbol != "") {
1135
+ allSym.add(sInfo.S3Symbol);
1136
+ }
1137
+ }
1138
+ }
1139
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1140
+ finally {
1141
+ try {
1142
+ if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
1143
+ }
1144
+ finally { if (e_1) throw e_1.error; }
1145
+ }
1146
+ allSymArr = Array.from(allSym.values());
1147
+ return [4 /*yield*/, _priceFeedGetter.fetchPrices(allSymArr)];
1148
+ case 1:
1149
+ idxPriceMap = _d.sent();
1150
+ return [2 /*return*/, idxPriceMap];
1151
+ }
1152
+ });
1153
+ });
1154
+ };
885
1155
  /**
886
1156
  * Get market open/closed status
887
1157
  * @param symbol Perpetual symbol of the form ETH-USD-MATIC
888
1158
  * @returns True if the market is closed
889
1159
  */
890
- async isMarketClosed(symbol) {
891
- if (this.proxyContract == null) {
892
- throw Error("no proxy contract initialized. Use createProxyInstance().");
893
- }
894
- return await MarketData._isMarketClosed(symbol, this.symbolToPerpStaticInfo, this.priceFeedGetter);
895
- }
896
- static async _isMarketClosed(symbol, _symbolToPerpStaticInfo, _priceFeedGetter) {
897
- const sInfo = _symbolToPerpStaticInfo.get(symbol);
898
- let priceSymbols = [];
899
- if (sInfo?.S2Symbol != undefined && sInfo.S2Symbol != "") {
900
- priceSymbols.push(sInfo.S2Symbol);
901
- }
902
- if (sInfo?.S3Symbol != undefined && sInfo.S3Symbol != "") {
903
- priceSymbols.push(sInfo.S3Symbol);
904
- }
905
- if (priceSymbols.length == 0) {
906
- throw new Error("symbol not found");
907
- }
908
- const priceInfos = await _priceFeedGetter.fetchPrices(priceSymbols);
909
- return [...priceInfos.values()].some((p) => p[1]);
910
- }
1160
+ MarketData.prototype.isMarketClosed = function (symbol) {
1161
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
1162
+ return tslib_1.__generator(this, function (_a) {
1163
+ switch (_a.label) {
1164
+ case 0:
1165
+ if (this.proxyContract == null) {
1166
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
1167
+ }
1168
+ return [4 /*yield*/, MarketData._isMarketClosed(symbol, this.symbolToPerpStaticInfo, this.priceFeedGetter)];
1169
+ case 1: return [2 /*return*/, _a.sent()];
1170
+ }
1171
+ });
1172
+ });
1173
+ };
1174
+ MarketData._isMarketClosed = function (symbol, _symbolToPerpStaticInfo, _priceFeedGetter) {
1175
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
1176
+ var sInfo, priceSymbols, priceInfos;
1177
+ return tslib_1.__generator(this, function (_a) {
1178
+ switch (_a.label) {
1179
+ case 0:
1180
+ sInfo = _symbolToPerpStaticInfo.get(symbol);
1181
+ priceSymbols = [];
1182
+ if ((sInfo === null || sInfo === void 0 ? void 0 : sInfo.S2Symbol) != undefined && sInfo.S2Symbol != "") {
1183
+ priceSymbols.push(sInfo.S2Symbol);
1184
+ }
1185
+ if ((sInfo === null || sInfo === void 0 ? void 0 : sInfo.S3Symbol) != undefined && sInfo.S3Symbol != "") {
1186
+ priceSymbols.push(sInfo.S3Symbol);
1187
+ }
1188
+ if (priceSymbols.length == 0) {
1189
+ throw new Error("symbol not found");
1190
+ }
1191
+ return [4 /*yield*/, _priceFeedGetter.fetchPrices(priceSymbols)];
1192
+ case 1:
1193
+ priceInfos = _a.sent();
1194
+ return [2 /*return*/, tslib_1.__spreadArray([], tslib_1.__read(priceInfos.values()), false).some(function (p) { return p[1]; })];
1195
+ }
1196
+ });
1197
+ });
1198
+ };
911
1199
  /**
912
1200
  * Collect all mid-prices
913
1201
  * @param _proxyContract contract instance
@@ -917,127 +1205,182 @@ class MarketData extends perpetualDataHandler_1.default {
917
1205
  * @param _idxPriceMap symbol to price/market closed
918
1206
  * @returns perpetual symbol to mid-prices mapping
919
1207
  */
920
- static async _queryMidPrices(_proxyContract, _nestedPerpetualIDs, _symbolToPerpStaticInfo, _perpetualIdToSymbol, _idxPriceMap, overrides) {
921
- // what is the maximal number of queries at once?
922
- const chunkSize = 10;
923
- let perpetualIDChunks = perpetualDataHandler_1.default.nestedIDsToChunks(chunkSize, _nestedPerpetualIDs);
924
- let midPriceMap = new Map();
925
- for (let k = 0; k < perpetualIDChunks.length; k++) {
926
- let indexPrices = [];
927
- // collect/order all index prices
928
- for (let j = 0; j < perpetualIDChunks[k].length; j++) {
929
- let id = perpetualIDChunks[k][j];
930
- let symbol3s = _perpetualIdToSymbol.get(id);
931
- let info = _symbolToPerpStaticInfo.get(symbol3s);
932
- let S2 = (0, d8XMath_1.floatToABK64x64)(_idxPriceMap.get(info.S2Symbol)[0]);
933
- let S3 = bignumber_1.BigNumber.from(0);
934
- if (info.S3Symbol != "") {
935
- S3 = (0, d8XMath_1.floatToABK64x64)(_idxPriceMap.get(info.S3Symbol)[0]);
1208
+ MarketData._queryMidPrices = function (_proxyContract, _nestedPerpetualIDs, _symbolToPerpStaticInfo, _perpetualIdToSymbol, _idxPriceMap, overrides) {
1209
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
1210
+ var chunkSize, perpetualIDChunks, midPriceMap, k, indexPrices, j, id, symbol3s, info, S2, S3, fMidPrice, j, id, symbol3s;
1211
+ return tslib_1.__generator(this, function (_a) {
1212
+ switch (_a.label) {
1213
+ case 0:
1214
+ chunkSize = 10;
1215
+ perpetualIDChunks = perpetualDataHandler_1.default.nestedIDsToChunks(chunkSize, _nestedPerpetualIDs);
1216
+ midPriceMap = new Map();
1217
+ k = 0;
1218
+ _a.label = 1;
1219
+ case 1:
1220
+ if (!(k < perpetualIDChunks.length)) return [3 /*break*/, 4];
1221
+ indexPrices = [];
1222
+ // collect/order all index prices
1223
+ for (j = 0; j < perpetualIDChunks[k].length; j++) {
1224
+ id = perpetualIDChunks[k][j];
1225
+ symbol3s = _perpetualIdToSymbol.get(id);
1226
+ info = _symbolToPerpStaticInfo.get(symbol3s);
1227
+ S2 = (0, d8XMath_1.floatToABK64x64)(_idxPriceMap.get(info.S2Symbol)[0]);
1228
+ S3 = bignumber_1.BigNumber.from(0);
1229
+ if (info.S3Symbol != "") {
1230
+ S3 = (0, d8XMath_1.floatToABK64x64)(_idxPriceMap.get(info.S3Symbol)[0]);
1231
+ }
1232
+ indexPrices.push(S2);
1233
+ indexPrices.push(S3);
1234
+ }
1235
+ return [4 /*yield*/, _proxyContract.queryMidPrices(perpetualIDChunks[k], indexPrices, overrides || {})];
1236
+ case 2:
1237
+ fMidPrice = _a.sent();
1238
+ for (j = 0; j < fMidPrice.length; j++) {
1239
+ id = perpetualIDChunks[k][j];
1240
+ symbol3s = _perpetualIdToSymbol.get(id);
1241
+ midPriceMap.set(symbol3s, (0, d8XMath_1.ABK64x64ToFloat)(fMidPrice[j]));
1242
+ }
1243
+ _a.label = 3;
1244
+ case 3:
1245
+ k++;
1246
+ return [3 /*break*/, 1];
1247
+ case 4: return [2 /*return*/, midPriceMap];
936
1248
  }
937
- indexPrices.push(S2);
938
- indexPrices.push(S3);
939
- }
940
- let fMidPrice = await _proxyContract.queryMidPrices(perpetualIDChunks[k], indexPrices, overrides || {});
941
- for (let j = 0; j < fMidPrice.length; j++) {
942
- let id = perpetualIDChunks[k][j];
943
- let symbol3s = _perpetualIdToSymbol.get(id);
944
- midPriceMap.set(symbol3s, (0, d8XMath_1.ABK64x64ToFloat)(fMidPrice[j]));
945
- }
946
- }
947
- return midPriceMap;
948
- }
949
- static async _queryPoolStates(_proxyContract, _poolStaticInfos, _numPools, overrides) {
950
- const chunkSize = 5;
951
- let iFrom = 1;
952
- let poolStates = [];
953
- while (iFrom <= _numPools) {
954
- let pools = await _proxyContract.getLiquidityPools(iFrom, iFrom + chunkSize, overrides || {});
955
- for (let k = 0; k < pools.length; k++) {
956
- let poolSymbol = _poolStaticInfos[iFrom + k - 1].poolMarginSymbol;
957
- let poolState = {
958
- isRunning: pools[k].isRunning,
959
- poolSymbol: poolSymbol,
960
- marginTokenAddr: pools[k].marginTokenAddress,
961
- poolShareTokenAddr: pools[k].shareTokenAddress,
962
- defaultFundCashCC: (0, d8XMath_1.ABK64x64ToFloat)(pools[k].fDefaultFundCashCC),
963
- pnlParticipantCashCC: (0, d8XMath_1.ABK64x64ToFloat)(pools[k].fPnLparticipantsCashCC),
964
- totalTargetAMMFundSizeCC: (0, d8XMath_1.ABK64x64ToFloat)(pools[k].fTargetAMMFundSize),
965
- brokerCollateralLotSize: (0, d8XMath_1.ABK64x64ToFloat)(pools[k].fBrokerCollateralLotSize),
966
- perpetuals: [],
967
- };
968
- poolStates.push(poolState);
969
- }
970
- iFrom = iFrom + chunkSize + 1;
971
- }
972
- return poolStates;
973
- }
974
- static async _queryPerpetualStates(_proxyContract, _nestedPerpetualIDs, _symbolList, overrides) {
975
- // what is the maximal number of queries at once?
976
- const chunkSize = 10;
977
- let perpetualIDChunks = perpetualDataHandler_1.default.nestedIDsToChunks(chunkSize, _nestedPerpetualIDs);
978
- let perpStateInfos = new Array();
979
- for (let k = 0; k < perpetualIDChunks.length; k++) {
980
- let perps = await _proxyContract.getPerpetuals(perpetualIDChunks[k], overrides || {});
981
- for (let j = 0; j < perps.length; j++) {
982
- let PerpetualState = {
983
- id: perps[j].id,
984
- state: nodeSDKTypes_1.PERP_STATE_STR[perps[j].state],
985
- baseCurrency: (0, utils_1.contractSymbolToSymbol)(perps[j].S2BaseCCY, _symbolList),
986
- quoteCurrency: (0, utils_1.contractSymbolToSymbol)(perps[j].S2QuoteCCY, _symbolList),
987
- indexPrice: 0,
988
- collToQuoteIndexPrice: 0,
989
- markPrice: (0, d8XMath_1.ABK64x64ToFloat)(perps[j].currentMarkPremiumRate.fPrice),
990
- midPrice: 0,
991
- currentFundingRateBps: 1e4 * (0, d8XMath_1.ABK64x64ToFloat)(perps[j].fCurrentFundingRate),
992
- openInterestBC: (0, d8XMath_1.ABK64x64ToFloat)(perps[j].fOpenInterest),
993
- isMarketClosed: false, //fill later
994
- };
995
- perpStateInfos.push(PerpetualState);
996
- }
997
- }
998
- return perpStateInfos;
999
- }
1000
- static async _exchangeInfo(_proxyContract, _poolStaticInfos, _symbolToPerpStaticInfo, _perpetualIdToSymbol, _nestedPerpetualIDs, _symbolList, _priceFeedGetter, overrides) {
1001
- // get the factory address (shared among all pools)
1002
- let factory = _poolStaticInfos[0].oracleFactoryAddr;
1003
- let info = { pools: [], oracleFactoryAddr: factory, proxyAddr: _proxyContract.address };
1004
- const numPools = _nestedPerpetualIDs.length;
1005
- // get all prices from off-chain price-sources
1006
- let idxPriceMap = await MarketData._getAllIndexPrices(_symbolToPerpStaticInfo, _priceFeedGetter);
1007
- // query mid-prices from on-chain conditional on the off-chain prices
1008
- let midPriceMap = await MarketData._queryMidPrices(_proxyContract, _nestedPerpetualIDs, _symbolToPerpStaticInfo, _perpetualIdToSymbol, idxPriceMap, overrides);
1009
- let poolStateInfos = await MarketData._queryPoolStates(_proxyContract, _poolStaticInfos, numPools, overrides);
1010
- let perpStateInfos = await MarketData._queryPerpetualStates(_proxyContract, _nestedPerpetualIDs, _symbolList, overrides);
1011
- // put together all info
1012
- for (let k = 0; k < perpStateInfos.length; k++) {
1013
- const perp = perpStateInfos[k];
1014
- let symbol3s = _perpetualIdToSymbol.get(perp.id);
1015
- let info = _symbolToPerpStaticInfo.get(symbol3s);
1016
- const idxPriceS2Pair = idxPriceMap.get(info.S2Symbol);
1017
- let idxPriceS3Pair = [0, false];
1018
- perp.isMarketClosed = idxPriceS2Pair[1];
1019
- if (info.S3Symbol != "") {
1020
- idxPriceS3Pair = idxPriceMap.get(info.S3Symbol);
1021
- perp.isMarketClosed = perp.isMarketClosed || idxPriceS3Pair[1];
1022
- }
1023
- perp.indexPrice = idxPriceS2Pair[0];
1024
- perp.markPrice = idxPriceS2Pair[0] * (1 + perp.markPrice); // currently filled with mark premium rate
1025
- let indexS3 = 1;
1026
- if (info.collateralCurrencyType == nodeSDKTypes_1.COLLATERAL_CURRENCY_BASE) {
1027
- indexS3 = idxPriceS2Pair[0];
1028
- }
1029
- else if (info.collateralCurrencyType == nodeSDKTypes_1.COLLATERAL_CURRENCY_QUANTO) {
1030
- indexS3 = idxPriceS3Pair[0];
1031
- }
1032
- perp.collToQuoteIndexPrice = indexS3;
1033
- perp.midPrice = midPriceMap.get(symbol3s);
1034
- // which pool?
1035
- const poolId = info.poolId;
1036
- poolStateInfos[poolId - 1].perpetuals.push(perp);
1037
- }
1038
- info.pools = poolStateInfos;
1039
- return info;
1040
- }
1041
- }
1249
+ });
1250
+ });
1251
+ };
1252
+ MarketData._queryPoolStates = function (_proxyContract, _poolStaticInfos, _numPools, overrides) {
1253
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
1254
+ var chunkSize, iFrom, poolStates, pools, k, poolSymbol, poolState;
1255
+ return tslib_1.__generator(this, function (_a) {
1256
+ switch (_a.label) {
1257
+ case 0:
1258
+ chunkSize = 5;
1259
+ iFrom = 1;
1260
+ poolStates = [];
1261
+ _a.label = 1;
1262
+ case 1:
1263
+ if (!(iFrom <= _numPools)) return [3 /*break*/, 3];
1264
+ return [4 /*yield*/, _proxyContract.getLiquidityPools(iFrom, iFrom + chunkSize, overrides || {})];
1265
+ case 2:
1266
+ pools = _a.sent();
1267
+ for (k = 0; k < pools.length; k++) {
1268
+ poolSymbol = _poolStaticInfos[iFrom + k - 1].poolMarginSymbol;
1269
+ poolState = {
1270
+ isRunning: pools[k].isRunning,
1271
+ poolSymbol: poolSymbol,
1272
+ marginTokenAddr: pools[k].marginTokenAddress,
1273
+ poolShareTokenAddr: pools[k].shareTokenAddress,
1274
+ defaultFundCashCC: (0, d8XMath_1.ABK64x64ToFloat)(pools[k].fDefaultFundCashCC),
1275
+ pnlParticipantCashCC: (0, d8XMath_1.ABK64x64ToFloat)(pools[k].fPnLparticipantsCashCC),
1276
+ totalTargetAMMFundSizeCC: (0, d8XMath_1.ABK64x64ToFloat)(pools[k].fTargetAMMFundSize),
1277
+ brokerCollateralLotSize: (0, d8XMath_1.ABK64x64ToFloat)(pools[k].fBrokerCollateralLotSize),
1278
+ perpetuals: [],
1279
+ };
1280
+ poolStates.push(poolState);
1281
+ }
1282
+ iFrom = iFrom + chunkSize + 1;
1283
+ return [3 /*break*/, 1];
1284
+ case 3: return [2 /*return*/, poolStates];
1285
+ }
1286
+ });
1287
+ });
1288
+ };
1289
+ MarketData._queryPerpetualStates = function (_proxyContract, _nestedPerpetualIDs, _symbolList, overrides) {
1290
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
1291
+ var chunkSize, perpetualIDChunks, perpStateInfos, k, perps, j, PerpetualState;
1292
+ return tslib_1.__generator(this, function (_a) {
1293
+ switch (_a.label) {
1294
+ case 0:
1295
+ chunkSize = 10;
1296
+ perpetualIDChunks = perpetualDataHandler_1.default.nestedIDsToChunks(chunkSize, _nestedPerpetualIDs);
1297
+ perpStateInfos = new Array();
1298
+ k = 0;
1299
+ _a.label = 1;
1300
+ case 1:
1301
+ if (!(k < perpetualIDChunks.length)) return [3 /*break*/, 4];
1302
+ return [4 /*yield*/, _proxyContract.getPerpetuals(perpetualIDChunks[k], overrides || {})];
1303
+ case 2:
1304
+ perps = _a.sent();
1305
+ for (j = 0; j < perps.length; j++) {
1306
+ PerpetualState = {
1307
+ id: perps[j].id,
1308
+ state: nodeSDKTypes_1.PERP_STATE_STR[perps[j].state],
1309
+ baseCurrency: (0, utils_1.contractSymbolToSymbol)(perps[j].S2BaseCCY, _symbolList),
1310
+ quoteCurrency: (0, utils_1.contractSymbolToSymbol)(perps[j].S2QuoteCCY, _symbolList),
1311
+ indexPrice: 0,
1312
+ collToQuoteIndexPrice: 0,
1313
+ markPrice: (0, d8XMath_1.ABK64x64ToFloat)(perps[j].currentMarkPremiumRate.fPrice),
1314
+ midPrice: 0,
1315
+ currentFundingRateBps: 1e4 * (0, d8XMath_1.ABK64x64ToFloat)(perps[j].fCurrentFundingRate),
1316
+ openInterestBC: (0, d8XMath_1.ABK64x64ToFloat)(perps[j].fOpenInterest),
1317
+ isMarketClosed: false, //fill later
1318
+ };
1319
+ perpStateInfos.push(PerpetualState);
1320
+ }
1321
+ _a.label = 3;
1322
+ case 3:
1323
+ k++;
1324
+ return [3 /*break*/, 1];
1325
+ case 4: return [2 /*return*/, perpStateInfos];
1326
+ }
1327
+ });
1328
+ });
1329
+ };
1330
+ MarketData._exchangeInfo = function (_proxyContract, _poolStaticInfos, _symbolToPerpStaticInfo, _perpetualIdToSymbol, _nestedPerpetualIDs, _symbolList, _priceFeedGetter, overrides) {
1331
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
1332
+ var factory, info, numPools, idxPriceMap, midPriceMap, poolStateInfos, perpStateInfos, k, perp, symbol3s, info_1, idxPriceS2Pair, idxPriceS3Pair, indexS3, poolId;
1333
+ return tslib_1.__generator(this, function (_a) {
1334
+ switch (_a.label) {
1335
+ case 0:
1336
+ factory = _poolStaticInfos[0].oracleFactoryAddr;
1337
+ info = { pools: [], oracleFactoryAddr: factory, proxyAddr: _proxyContract.address };
1338
+ numPools = _nestedPerpetualIDs.length;
1339
+ return [4 /*yield*/, MarketData._getAllIndexPrices(_symbolToPerpStaticInfo, _priceFeedGetter)];
1340
+ case 1:
1341
+ idxPriceMap = _a.sent();
1342
+ return [4 /*yield*/, MarketData._queryMidPrices(_proxyContract, _nestedPerpetualIDs, _symbolToPerpStaticInfo, _perpetualIdToSymbol, idxPriceMap, overrides)];
1343
+ case 2:
1344
+ midPriceMap = _a.sent();
1345
+ return [4 /*yield*/, MarketData._queryPoolStates(_proxyContract, _poolStaticInfos, numPools, overrides)];
1346
+ case 3:
1347
+ poolStateInfos = _a.sent();
1348
+ return [4 /*yield*/, MarketData._queryPerpetualStates(_proxyContract, _nestedPerpetualIDs, _symbolList, overrides)];
1349
+ case 4:
1350
+ perpStateInfos = _a.sent();
1351
+ // put together all info
1352
+ for (k = 0; k < perpStateInfos.length; k++) {
1353
+ perp = perpStateInfos[k];
1354
+ symbol3s = _perpetualIdToSymbol.get(perp.id);
1355
+ info_1 = _symbolToPerpStaticInfo.get(symbol3s);
1356
+ idxPriceS2Pair = idxPriceMap.get(info_1.S2Symbol);
1357
+ idxPriceS3Pair = [0, false];
1358
+ perp.isMarketClosed = idxPriceS2Pair[1];
1359
+ if (info_1.S3Symbol != "") {
1360
+ idxPriceS3Pair = idxPriceMap.get(info_1.S3Symbol);
1361
+ perp.isMarketClosed = perp.isMarketClosed || idxPriceS3Pair[1];
1362
+ }
1363
+ perp.indexPrice = idxPriceS2Pair[0];
1364
+ perp.markPrice = idxPriceS2Pair[0] * (1 + perp.markPrice); // currently filled with mark premium rate
1365
+ indexS3 = 1;
1366
+ if (info_1.collateralCurrencyType == nodeSDKTypes_1.COLLATERAL_CURRENCY_BASE) {
1367
+ indexS3 = idxPriceS2Pair[0];
1368
+ }
1369
+ else if (info_1.collateralCurrencyType == nodeSDKTypes_1.COLLATERAL_CURRENCY_QUANTO) {
1370
+ indexS3 = idxPriceS3Pair[0];
1371
+ }
1372
+ perp.collToQuoteIndexPrice = indexS3;
1373
+ perp.midPrice = midPriceMap.get(symbol3s);
1374
+ poolId = info_1.poolId;
1375
+ poolStateInfos[poolId - 1].perpetuals.push(perp);
1376
+ }
1377
+ info.pools = poolStateInfos;
1378
+ return [2 /*return*/, info];
1379
+ }
1380
+ });
1381
+ });
1382
+ };
1383
+ return MarketData;
1384
+ }(perpetualDataHandler_1.default));
1042
1385
  exports.default = MarketData;
1043
1386
  //# sourceMappingURL=marketData.js.map