@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 { __assign, __awaiter, __extends, __generator, __read } from "tslib";
1
2
  import { BigNumber } from "@ethersproject/bignumber";
2
3
  import { HashZero } from "@ethersproject/constants";
3
4
  import { BUY_SIDE, SELL_SIDE, ZERO_ADDRESS, ZERO_ORDER_ID, } from "./nodeSDKTypes";
@@ -9,7 +10,8 @@ import WriteAccessHandler from "./writeAccessHandler";
9
10
  * gas-payments.
10
11
  * @extends WriteAccessHandler
11
12
  */
12
- export default class OrderReferrerTool extends WriteAccessHandler {
13
+ var OrderReferrerTool = /** @class */ (function (_super) {
14
+ __extends(OrderReferrerTool, _super);
13
15
  /**
14
16
  * Constructor.
15
17
  * @param {NodeSDKConfig} config Configuration object, see PerpetualDataHandler.readSDKConfig.
@@ -29,10 +31,11 @@ export default class OrderReferrerTool extends WriteAccessHandler {
29
31
  *
30
32
  * @param {string | Signer} signer Private key or ethers Signer of the account
31
33
  */
32
- constructor(config, signer) {
33
- super(config, signer);
34
+ function OrderReferrerTool(config, signer) {
35
+ var _this = _super.call(this, config, signer) || this;
34
36
  // override parent's gas limit with a lower number
35
- this.gasLimit = 4000000;
37
+ _this.gasLimit = 4000000;
38
+ return _this;
36
39
  }
37
40
  /**
38
41
  * Executes an order by symbol and ID. This action interacts with the blockchain and incurs gas costs.
@@ -68,46 +71,66 @@ export default class OrderReferrerTool extends WriteAccessHandler {
68
71
  * main();
69
72
  * @returns Transaction object.
70
73
  */
71
- async executeOrder(symbol, orderId, referrerAddr, submission, overrides) {
72
- if (this.proxyContract == null || this.signer == null) {
73
- throw Error("no proxy contract or wallet initialized. Use createProxyInstance().");
74
- }
75
- const orderBookSC = this.getOrderBookContract(symbol);
76
- if (typeof referrerAddr == "undefined") {
77
- referrerAddr = this.traderAddr;
78
- }
79
- if (submission == undefined) {
80
- submission = await this.priceFeedGetter.fetchLatestFeedPriceInfoForPerpetual(symbol);
81
- }
82
- if (!overrides || overrides.value == undefined) {
83
- overrides = {
84
- value: submission.timestamps.length * this.PRICE_UPDATE_FEE_GWEI,
85
- gasLimit: overrides?.gasLimit ?? this.gasLimit,
86
- ...overrides,
87
- };
88
- }
89
- return await orderBookSC.executeOrder(orderId, referrerAddr, submission.priceFeedVaas, submission.timestamps, overrides);
90
- }
91
- async executeOrders(symbol, orderIds, referrerAddr, submission, overrides) {
92
- if (this.proxyContract == null || this.signer == null) {
93
- throw Error("no proxy contract or wallet initialized. Use createProxyInstance().");
94
- }
95
- const orderBookSC = this.getOrderBookContract(symbol);
96
- if (typeof referrerAddr == "undefined") {
97
- referrerAddr = this.traderAddr;
98
- }
99
- if (submission == undefined) {
100
- submission = await this.priceFeedGetter.fetchLatestFeedPriceInfoForPerpetual(symbol);
101
- }
102
- if (!overrides || overrides.value == undefined) {
103
- overrides = {
104
- value: submission.timestamps.length * this.PRICE_UPDATE_FEE_GWEI,
105
- gasLimit: overrides?.gasLimit ?? this.gasLimit,
106
- ...overrides,
107
- };
108
- }
109
- return await orderBookSC.executeOrders(orderIds, referrerAddr, submission?.priceFeedVaas, submission?.timestamps, overrides);
110
- }
74
+ OrderReferrerTool.prototype.executeOrder = function (symbol, orderId, referrerAddr, submission, overrides) {
75
+ var _a;
76
+ return __awaiter(this, void 0, void 0, function () {
77
+ var orderBookSC, nonce;
78
+ return __generator(this, function (_b) {
79
+ switch (_b.label) {
80
+ case 0:
81
+ if (this.proxyContract == null || this.signer == null) {
82
+ throw Error("no proxy contract or wallet initialized. Use createProxyInstance().");
83
+ }
84
+ orderBookSC = this.getOrderBookContract(symbol);
85
+ if (typeof referrerAddr == "undefined") {
86
+ referrerAddr = this.traderAddr;
87
+ }
88
+ if (!(submission == undefined)) return [3 /*break*/, 2];
89
+ return [4 /*yield*/, this.priceFeedGetter.fetchLatestFeedPriceInfoForPerpetual(symbol)];
90
+ case 1:
91
+ submission = _b.sent();
92
+ _b.label = 2;
93
+ case 2: return [4 /*yield*/, this.signer.getTransactionCount()];
94
+ case 3:
95
+ nonce = _b.sent();
96
+ if (!overrides || overrides.value == undefined) {
97
+ overrides = __assign({ value: submission.timestamps.length * this.PRICE_UPDATE_FEE_GWEI, gasLimit: (_a = overrides === null || overrides === void 0 ? void 0 : overrides.gasLimit) !== null && _a !== void 0 ? _a : this.gasLimit, nonce: nonce }, overrides);
98
+ }
99
+ return [4 /*yield*/, orderBookSC.executeOrder(orderId, referrerAddr, submission.priceFeedVaas, submission.timestamps, overrides)];
100
+ case 4: return [2 /*return*/, _b.sent()];
101
+ }
102
+ });
103
+ });
104
+ };
105
+ OrderReferrerTool.prototype.executeOrders = function (symbol, orderIds, referrerAddr, submission, overrides) {
106
+ var _a;
107
+ return __awaiter(this, void 0, void 0, function () {
108
+ var orderBookSC;
109
+ return __generator(this, function (_b) {
110
+ switch (_b.label) {
111
+ case 0:
112
+ if (this.proxyContract == null || this.signer == null) {
113
+ throw Error("no proxy contract or wallet initialized. Use createProxyInstance().");
114
+ }
115
+ orderBookSC = this.getOrderBookContract(symbol);
116
+ if (typeof referrerAddr == "undefined") {
117
+ referrerAddr = this.traderAddr;
118
+ }
119
+ if (!(submission == undefined)) return [3 /*break*/, 2];
120
+ return [4 /*yield*/, this.priceFeedGetter.fetchLatestFeedPriceInfoForPerpetual(symbol)];
121
+ case 1:
122
+ submission = _b.sent();
123
+ _b.label = 2;
124
+ case 2:
125
+ if (!overrides || overrides.value == undefined) {
126
+ overrides = __assign({ value: submission.timestamps.length * this.PRICE_UPDATE_FEE_GWEI, gasLimit: (_a = overrides === null || overrides === void 0 ? void 0 : overrides.gasLimit) !== null && _a !== void 0 ? _a : this.gasLimit }, overrides);
127
+ }
128
+ return [4 /*yield*/, orderBookSC.executeOrders(orderIds, referrerAddr, submission === null || submission === void 0 ? void 0 : submission.priceFeedVaas, submission === null || submission === void 0 ? void 0 : submission.timestamps, overrides)];
129
+ case 3: return [2 /*return*/, _b.sent()];
130
+ }
131
+ });
132
+ });
133
+ };
111
134
  /**
112
135
  * All the orders in the order book for a given symbol that are currently open.
113
136
  * @param {string} symbol Symbol of the form ETH-USD-MATIC.
@@ -128,10 +151,20 @@ export default class OrderReferrerTool extends WriteAccessHandler {
128
151
  *
129
152
  * @returns Array with all open orders and their IDs.
130
153
  */
131
- async getAllOpenOrders(symbol, overrides) {
132
- let totalOrders = await this.numberOfOpenOrders(symbol, overrides);
133
- return await this.pollLimitOrders(symbol, totalOrders, ZERO_ORDER_ID, overrides);
134
- }
154
+ OrderReferrerTool.prototype.getAllOpenOrders = function (symbol, overrides) {
155
+ return __awaiter(this, void 0, void 0, function () {
156
+ var totalOrders;
157
+ return __generator(this, function (_a) {
158
+ switch (_a.label) {
159
+ case 0: return [4 /*yield*/, this.numberOfOpenOrders(symbol, overrides)];
160
+ case 1:
161
+ totalOrders = _a.sent();
162
+ return [4 /*yield*/, this.pollLimitOrders(symbol, totalOrders, ZERO_ORDER_ID, overrides)];
163
+ case 2: return [2 /*return*/, _a.sent()];
164
+ }
165
+ });
166
+ });
167
+ };
135
168
  /**
136
169
  * Total number of limit orders for this symbol, excluding those that have been cancelled/removed.
137
170
  * @param {string} symbol Symbol of the form ETH-USD-MATIC.
@@ -152,14 +185,24 @@ export default class OrderReferrerTool extends WriteAccessHandler {
152
185
  *
153
186
  * @returns {number} Number of open orders.
154
187
  */
155
- async numberOfOpenOrders(symbol, overrides) {
156
- if (this.proxyContract == null) {
157
- throw Error("no proxy contract initialized. Use createProxyInstance().");
158
- }
159
- const orderBookSC = this.getOrderBookContract(symbol);
160
- let numOrders = await orderBookSC.numberOfOrderBookDigests(overrides || {});
161
- return Number(numOrders);
162
- }
188
+ OrderReferrerTool.prototype.numberOfOpenOrders = function (symbol, overrides) {
189
+ return __awaiter(this, void 0, void 0, function () {
190
+ var orderBookSC, numOrders;
191
+ return __generator(this, function (_a) {
192
+ switch (_a.label) {
193
+ case 0:
194
+ if (this.proxyContract == null) {
195
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
196
+ }
197
+ orderBookSC = this.getOrderBookContract(symbol);
198
+ return [4 /*yield*/, orderBookSC.numberOfOrderBookDigests(overrides || {})];
199
+ case 1:
200
+ numOrders = _a.sent();
201
+ return [2 /*return*/, Number(numOrders)];
202
+ }
203
+ });
204
+ });
205
+ };
163
206
  /**
164
207
  * Get order from the digest (=id)
165
208
  * @param symbol symbol of order book, e.g. ETH-USD-MATIC
@@ -182,15 +225,26 @@ export default class OrderReferrerTool extends WriteAccessHandler {
182
225
  *
183
226
  * @returns order or undefined
184
227
  */
185
- async getOrderById(symbol, id, overrides) {
186
- let ob = await this.getOrderBookContract(symbol);
187
- let smartContractOrder = await ob.orderOfDigest(id, overrides || {});
188
- if (smartContractOrder.traderAddr == ZERO_ADDRESS) {
189
- return undefined;
190
- }
191
- let order = OrderReferrerTool.fromSmartContractOrder(smartContractOrder, this.symbolToPerpStaticInfo);
192
- return order;
193
- }
228
+ OrderReferrerTool.prototype.getOrderById = function (symbol, id, overrides) {
229
+ return __awaiter(this, void 0, void 0, function () {
230
+ var ob, smartContractOrder, order;
231
+ return __generator(this, function (_a) {
232
+ switch (_a.label) {
233
+ case 0: return [4 /*yield*/, this.getOrderBookContract(symbol)];
234
+ case 1:
235
+ ob = _a.sent();
236
+ return [4 /*yield*/, ob.orderOfDigest(id, overrides || {})];
237
+ case 2:
238
+ smartContractOrder = _a.sent();
239
+ if (smartContractOrder.traderAddr == ZERO_ADDRESS) {
240
+ return [2 /*return*/, undefined];
241
+ }
242
+ order = OrderReferrerTool.fromSmartContractOrder(smartContractOrder, this.symbolToPerpStaticInfo);
243
+ return [2 /*return*/, order];
244
+ }
245
+ });
246
+ });
247
+ };
194
248
  /**
195
249
  * Get a list of active conditional orders in the order book.
196
250
  * This a read-only action and does not incur in gas costs.
@@ -214,25 +268,35 @@ export default class OrderReferrerTool extends WriteAccessHandler {
214
268
  *
215
269
  * @returns Array of orders and corresponding order IDs
216
270
  */
217
- async pollLimitOrders(symbol, numElements, startAfter, overrides) {
218
- if (this.proxyContract == null) {
219
- throw Error("no proxy contract initialized. Use createProxyInstance().");
220
- }
221
- const orderBookSC = this.getOrderBookContract(symbol);
222
- if (typeof startAfter == "undefined") {
223
- startAfter = ZERO_ORDER_ID;
224
- }
225
- let [orders, orderIds] = await orderBookSC.pollLimitOrders(startAfter, BigNumber.from(numElements), overrides || {});
226
- let userFriendlyOrders = new Array();
227
- let orderIdsOut = [];
228
- let k = 0;
229
- while (k < orders.length && orders[k].traderAddr != ZERO_ADDRESS) {
230
- userFriendlyOrders.push(WriteAccessHandler.fromClientOrder(orders[k], this.symbolToPerpStaticInfo));
231
- orderIdsOut.push(orderIds[k]);
232
- k++;
233
- }
234
- return [userFriendlyOrders, orderIdsOut];
235
- }
271
+ OrderReferrerTool.prototype.pollLimitOrders = function (symbol, numElements, startAfter, overrides) {
272
+ return __awaiter(this, void 0, void 0, function () {
273
+ var orderBookSC, _a, orders, orderIds, userFriendlyOrders, orderIdsOut, k;
274
+ return __generator(this, function (_b) {
275
+ switch (_b.label) {
276
+ case 0:
277
+ if (this.proxyContract == null) {
278
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
279
+ }
280
+ orderBookSC = this.getOrderBookContract(symbol);
281
+ if (typeof startAfter == "undefined") {
282
+ startAfter = ZERO_ORDER_ID;
283
+ }
284
+ return [4 /*yield*/, orderBookSC.pollLimitOrders(startAfter, BigNumber.from(numElements), overrides || {})];
285
+ case 1:
286
+ _a = __read.apply(void 0, [_b.sent(), 2]), orders = _a[0], orderIds = _a[1];
287
+ userFriendlyOrders = new Array();
288
+ orderIdsOut = [];
289
+ k = 0;
290
+ while (k < orders.length && orders[k].traderAddr != ZERO_ADDRESS) {
291
+ userFriendlyOrders.push(WriteAccessHandler.fromClientOrder(orders[k], this.symbolToPerpStaticInfo));
292
+ orderIdsOut.push(orderIds[k]);
293
+ k++;
294
+ }
295
+ return [2 /*return*/, [userFriendlyOrders, orderIdsOut]];
296
+ }
297
+ });
298
+ });
299
+ };
236
300
  /**
237
301
  * Check if a conditional order can be executed
238
302
  * @param order order structure
@@ -255,22 +319,41 @@ export default class OrderReferrerTool extends WriteAccessHandler {
255
319
  * main();
256
320
  * @returns true if order can be executed for the current state of the perpetuals
257
321
  */
258
- async isTradeable(order, blockTimestamp, indexPrices, overrides) {
259
- if (this.proxyContract == null) {
260
- throw Error("no proxy contract initialized. Use createProxyInstance().");
261
- }
262
- if (indexPrices == undefined) {
263
- let obj = await this.priceFeedGetter.fetchPricesForPerpetual(order.symbol);
264
- indexPrices = [obj.idxPrices[0], obj.idxPrices[1]];
265
- }
266
- let orderPrice = await PerpetualDataHandler._queryPerpetualPrice(order.symbol, order.quantity, this.symbolToPerpStaticInfo, this.proxyContract, indexPrices, overrides);
267
- let markPrice = await PerpetualDataHandler._queryPerpetualMarkPrice(order.symbol, this.symbolToPerpStaticInfo, this.proxyContract, indexPrices, overrides);
268
- if (blockTimestamp == undefined) {
269
- const currentBlock = await this.provider.getBlockNumber();
270
- blockTimestamp = (await this.provider.getBlock(currentBlock)).timestamp;
271
- }
272
- return await this._isTradeable(order, orderPrice, markPrice, blockTimestamp, this.symbolToPerpStaticInfo, overrides);
273
- }
322
+ OrderReferrerTool.prototype.isTradeable = function (order, blockTimestamp, indexPrices, overrides) {
323
+ return __awaiter(this, void 0, void 0, function () {
324
+ var obj, orderPrice, markPrice, currentBlock;
325
+ return __generator(this, function (_a) {
326
+ switch (_a.label) {
327
+ case 0:
328
+ if (this.proxyContract == null) {
329
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
330
+ }
331
+ if (!(indexPrices == undefined)) return [3 /*break*/, 2];
332
+ return [4 /*yield*/, this.priceFeedGetter.fetchPricesForPerpetual(order.symbol)];
333
+ case 1:
334
+ obj = _a.sent();
335
+ indexPrices = [obj.idxPrices[0], obj.idxPrices[1]];
336
+ _a.label = 2;
337
+ case 2: return [4 /*yield*/, PerpetualDataHandler._queryPerpetualPrice(order.symbol, order.quantity, this.symbolToPerpStaticInfo, this.proxyContract, indexPrices, overrides)];
338
+ case 3:
339
+ orderPrice = _a.sent();
340
+ return [4 /*yield*/, PerpetualDataHandler._queryPerpetualMarkPrice(order.symbol, this.symbolToPerpStaticInfo, this.proxyContract, indexPrices, overrides)];
341
+ case 4:
342
+ markPrice = _a.sent();
343
+ if (!(blockTimestamp == undefined)) return [3 /*break*/, 7];
344
+ return [4 /*yield*/, this.provider.getBlockNumber()];
345
+ case 5:
346
+ currentBlock = _a.sent();
347
+ return [4 /*yield*/, this.provider.getBlock(currentBlock)];
348
+ case 6:
349
+ blockTimestamp = (_a.sent()).timestamp;
350
+ _a.label = 7;
351
+ case 7: return [4 /*yield*/, this._isTradeable(order, orderPrice, markPrice, blockTimestamp, this.symbolToPerpStaticInfo, overrides)];
352
+ case 8: return [2 /*return*/, _a.sent()];
353
+ }
354
+ });
355
+ });
356
+ };
274
357
  /**
275
358
  * Check for a batch of orders on the same perpetual whether they can be traded
276
359
  * @param orders orders belonging to 1 perpetual
@@ -278,32 +361,57 @@ export default class OrderReferrerTool extends WriteAccessHandler {
278
361
  * if not defined.
279
362
  * @returns array of tradeable boolean
280
363
  */
281
- async isTradeableBatch(orders, blockTimestamp, indexPrices, overrides) {
282
- if (orders.length == 0) {
283
- return [];
284
- }
285
- if (this.proxyContract == null) {
286
- throw Error("no proxy contract initialized. Use createProxyInstance().");
287
- }
288
- if (orders.filter((o) => o.symbol == orders[0].symbol).length < orders.length) {
289
- throw Error("all orders in a batch must have the same symbol");
290
- }
291
- if (indexPrices == undefined) {
292
- let obj = await this.priceFeedGetter.fetchPricesForPerpetual(orders[0].symbol);
293
- indexPrices = [obj.idxPrices[0], obj.idxPrices[1], obj.mktClosed[0], obj.mktClosed[1]];
294
- }
295
- if (indexPrices[2] || indexPrices[3]) {
296
- // market closed
297
- return orders.map(() => false);
298
- }
299
- let orderPrice = await Promise.all(orders.map((o) => PerpetualDataHandler._queryPerpetualPrice(o.symbol, o.quantity, this.symbolToPerpStaticInfo, this.proxyContract, [indexPrices[0], indexPrices[1]], overrides)));
300
- let markPrice = await PerpetualDataHandler._queryPerpetualMarkPrice(orders[0].symbol, this.symbolToPerpStaticInfo, this.proxyContract, [indexPrices[0], indexPrices[1]], overrides);
301
- if (blockTimestamp == undefined) {
302
- const currentBlock = await this.provider.getBlockNumber();
303
- blockTimestamp = (await this.provider.getBlock(currentBlock)).timestamp;
304
- }
305
- return await Promise.all(orders.map((o, idx) => this._isTradeable(o, orderPrice[idx], markPrice, blockTimestamp, this.symbolToPerpStaticInfo, overrides)));
306
- }
364
+ OrderReferrerTool.prototype.isTradeableBatch = function (orders, blockTimestamp, indexPrices, overrides) {
365
+ return __awaiter(this, void 0, void 0, function () {
366
+ var obj, orderPrice, markPrice, currentBlock;
367
+ var _this = this;
368
+ return __generator(this, function (_a) {
369
+ switch (_a.label) {
370
+ case 0:
371
+ if (orders.length == 0) {
372
+ return [2 /*return*/, []];
373
+ }
374
+ if (this.proxyContract == null) {
375
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
376
+ }
377
+ if (orders.filter(function (o) { return o.symbol == orders[0].symbol; }).length < orders.length) {
378
+ throw Error("all orders in a batch must have the same symbol");
379
+ }
380
+ if (!(indexPrices == undefined)) return [3 /*break*/, 2];
381
+ return [4 /*yield*/, this.priceFeedGetter.fetchPricesForPerpetual(orders[0].symbol)];
382
+ case 1:
383
+ obj = _a.sent();
384
+ indexPrices = [obj.idxPrices[0], obj.idxPrices[1], obj.mktClosed[0], obj.mktClosed[1]];
385
+ _a.label = 2;
386
+ case 2:
387
+ if (indexPrices[2] || indexPrices[3]) {
388
+ // market closed
389
+ return [2 /*return*/, orders.map(function () { return false; })];
390
+ }
391
+ return [4 /*yield*/, Promise.all(orders.map(function (o) {
392
+ return PerpetualDataHandler._queryPerpetualPrice(o.symbol, o.quantity, _this.symbolToPerpStaticInfo, _this.proxyContract, [indexPrices[0], indexPrices[1]], overrides);
393
+ }))];
394
+ case 3:
395
+ orderPrice = _a.sent();
396
+ return [4 /*yield*/, PerpetualDataHandler._queryPerpetualMarkPrice(orders[0].symbol, this.symbolToPerpStaticInfo, this.proxyContract, [indexPrices[0], indexPrices[1]], overrides)];
397
+ case 4:
398
+ markPrice = _a.sent();
399
+ if (!(blockTimestamp == undefined)) return [3 /*break*/, 7];
400
+ return [4 /*yield*/, this.provider.getBlockNumber()];
401
+ case 5:
402
+ currentBlock = _a.sent();
403
+ return [4 /*yield*/, this.provider.getBlock(currentBlock)];
404
+ case 6:
405
+ blockTimestamp = (_a.sent()).timestamp;
406
+ _a.label = 7;
407
+ case 7: return [4 /*yield*/, Promise.all(orders.map(function (o, idx) {
408
+ return _this._isTradeable(o, orderPrice[idx], markPrice, blockTimestamp, _this.symbolToPerpStaticInfo, overrides);
409
+ }))];
410
+ case 8: return [2 /*return*/, _a.sent()];
411
+ }
412
+ });
413
+ });
414
+ };
307
415
  /**
308
416
  * Can the order be executed?
309
417
  * @param order order struct
@@ -313,78 +421,95 @@ export default class OrderReferrerTool extends WriteAccessHandler {
313
421
  * @param symbolToPerpInfoMap metadata
314
422
  * @returns true if trading conditions met, false otherwise
315
423
  */
316
- async _isTradeable(order, tradePrice, markPrice, blockTimestamp, symbolToPerpInfoMap, overrides) {
317
- // check expiration date
318
- if (order.deadline != undefined && order.deadline < Date.now() / 1000) {
319
- console.log("order expired");
320
- return false;
321
- }
322
- const nextBlockTimestamp = blockTimestamp + 2;
323
- // TODO: replace 2 by a chain-dependent constant - 1 for zkEVM
324
- if (nextBlockTimestamp < order.executionTimestamp) {
325
- console.log(`execution deferred to ${order.executionTimestamp - nextBlockTimestamp} more seconds`);
326
- return false;
327
- }
328
- if (order.submittedTimestamp != undefined &&
329
- nextBlockTimestamp < order.submittedTimestamp + OrderReferrerTool.TRADE_DELAY) {
330
- // next block should be in ~2 seconds, so + 2
331
- console.log(`on hold for ${OrderReferrerTool.TRADE_DELAY + order.submittedTimestamp - nextBlockTimestamp} more seconds`);
332
- return false;
333
- }
334
- // check order size
335
- const lotSize = PerpetualDataHandler._getLotSize(order.symbol, symbolToPerpInfoMap);
336
- if (order.quantity < lotSize) {
337
- // console.log(`order size too small: ${order.quantity} < ${lotSize}`);
338
- return false;
339
- }
340
- // check limit price: fromSmartContractOrder will set it to undefined when not tradeable
341
- if (order.limitPrice == undefined) {
342
- // console.log("limit price undefined");
343
- return false;
344
- }
345
- let limitPrice = order.limitPrice;
346
- if ((order.side == BUY_SIDE && tradePrice > limitPrice) || (order.side == SELL_SIDE && tradePrice < limitPrice)) {
347
- // console.log(`limit price not met: ${limitPrice} ${order.side} @ ${tradePrice}`);
348
- return false;
349
- }
350
- // check stop price
351
- if (order.stopPrice != undefined &&
352
- ((order.side == BUY_SIDE && markPrice < order.stopPrice) ||
353
- (order.side == SELL_SIDE && markPrice > order.stopPrice))) {
354
- // console.log("stop price not met");
355
- return false;
356
- }
357
- //check dependency
358
- if (order.parentChildOrderIds != undefined &&
359
- order.parentChildOrderIds[0] == HashZero &&
360
- order.parentChildOrderIds[1] != HashZero) {
361
- // order has a parent
362
- const orderBookContract = this.getOrderBookContract(order.symbol);
363
- const parentStatus = await orderBookContract.getOrderStatus(order.parentChildOrderIds[1], overrides || {});
364
- if (parentStatus == 2 || parentStatus == 3) {
365
- // console.log("parent not executed/cancelled");
366
- // parent is open or unknown
367
- return false;
368
- }
369
- return true;
370
- }
371
- // all checks passed -> order is tradeable
372
- return true;
373
- }
424
+ OrderReferrerTool.prototype._isTradeable = function (order, tradePrice, markPrice, blockTimestamp, symbolToPerpInfoMap, overrides) {
425
+ return __awaiter(this, void 0, void 0, function () {
426
+ var nextBlockTimestamp, lotSize, limitPrice, orderBookContract, parentStatus;
427
+ return __generator(this, function (_a) {
428
+ switch (_a.label) {
429
+ case 0:
430
+ // check expiration date
431
+ if (order.deadline != undefined && order.deadline < Date.now() / 1000) {
432
+ console.log("order expired");
433
+ return [2 /*return*/, false];
434
+ }
435
+ nextBlockTimestamp = blockTimestamp + 2;
436
+ // TODO: replace 2 by a chain-dependent constant - 1 for zkEVM
437
+ if (nextBlockTimestamp < order.executionTimestamp) {
438
+ console.log("execution deferred to ".concat(order.executionTimestamp - nextBlockTimestamp, " more seconds"));
439
+ return [2 /*return*/, false];
440
+ }
441
+ if (order.submittedTimestamp != undefined &&
442
+ nextBlockTimestamp < order.submittedTimestamp + OrderReferrerTool.TRADE_DELAY) {
443
+ // next block should be in ~2 seconds, so + 2
444
+ console.log("on hold for ".concat(OrderReferrerTool.TRADE_DELAY + order.submittedTimestamp - nextBlockTimestamp, " more seconds"));
445
+ return [2 /*return*/, false];
446
+ }
447
+ lotSize = PerpetualDataHandler._getLotSize(order.symbol, symbolToPerpInfoMap);
448
+ if (order.quantity < lotSize) {
449
+ // console.log(`order size too small: ${order.quantity} < ${lotSize}`);
450
+ return [2 /*return*/, false];
451
+ }
452
+ // check limit price: fromSmartContractOrder will set it to undefined when not tradeable
453
+ if (order.limitPrice == undefined) {
454
+ // console.log("limit price undefined");
455
+ return [2 /*return*/, false];
456
+ }
457
+ limitPrice = order.limitPrice;
458
+ if ((order.side == BUY_SIDE && tradePrice > limitPrice) || (order.side == SELL_SIDE && tradePrice < limitPrice)) {
459
+ // console.log(`limit price not met: ${limitPrice} ${order.side} @ ${tradePrice}`);
460
+ return [2 /*return*/, false];
461
+ }
462
+ // check stop price
463
+ if (order.stopPrice != undefined &&
464
+ ((order.side == BUY_SIDE && markPrice < order.stopPrice) ||
465
+ (order.side == SELL_SIDE && markPrice > order.stopPrice))) {
466
+ // console.log("stop price not met");
467
+ return [2 /*return*/, false];
468
+ }
469
+ if (!(order.parentChildOrderIds != undefined &&
470
+ order.parentChildOrderIds[0] == HashZero &&
471
+ order.parentChildOrderIds[1] != HashZero)) return [3 /*break*/, 2];
472
+ orderBookContract = this.getOrderBookContract(order.symbol);
473
+ return [4 /*yield*/, orderBookContract.getOrderStatus(order.parentChildOrderIds[1], overrides || {})];
474
+ case 1:
475
+ parentStatus = _a.sent();
476
+ if (parentStatus == 2 || parentStatus == 3) {
477
+ // console.log("parent not executed/cancelled");
478
+ // parent is open or unknown
479
+ return [2 /*return*/, false];
480
+ }
481
+ return [2 /*return*/, true];
482
+ case 2:
483
+ // all checks passed -> order is tradeable
484
+ return [2 /*return*/, true];
485
+ }
486
+ });
487
+ });
488
+ };
374
489
  /**
375
490
  * Wrapper of static method to use after mappings have been loaded into memory.
376
491
  * @param scOrder Perpetual order as received in the proxy events.
377
492
  * @returns A user-friendly order struct.
378
493
  */
379
- smartContractOrderToOrder(scOrder) {
494
+ OrderReferrerTool.prototype.smartContractOrderToOrder = function (scOrder) {
380
495
  return PerpetualDataHandler.fromSmartContractOrder(scOrder, this.symbolToPerpStaticInfo);
381
- }
382
- async getTransactionCount(blockTag) {
383
- if (this.signer == null) {
384
- throw Error("no wallet initialized. Use createProxyInstance().");
385
- }
386
- return await this.signer.getTransactionCount(blockTag);
387
- }
388
- }
389
- OrderReferrerTool.TRADE_DELAY = 4;
496
+ };
497
+ OrderReferrerTool.prototype.getTransactionCount = function (blockTag) {
498
+ return __awaiter(this, void 0, void 0, function () {
499
+ return __generator(this, function (_a) {
500
+ switch (_a.label) {
501
+ case 0:
502
+ if (this.signer == null) {
503
+ throw Error("no wallet initialized. Use createProxyInstance().");
504
+ }
505
+ return [4 /*yield*/, this.signer.getTransactionCount(blockTag)];
506
+ case 1: return [2 /*return*/, _a.sent()];
507
+ }
508
+ });
509
+ });
510
+ };
511
+ OrderReferrerTool.TRADE_DELAY = 4;
512
+ return OrderReferrerTool;
513
+ }(WriteAccessHandler));
514
+ export default OrderReferrerTool;
390
515
  //# sourceMappingURL=orderReferrerTool.js.map