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